From f2f626a09b64a25dfdbb9d5e8ff929e3ef083518 Mon Sep 17 00:00:00 2001 From: Moses Narrow Date: Wed, 3 Aug 2022 11:47:51 -0500 Subject: [PATCH 01/72] add skychat rework ; begin to fix make format check errors --- .../internal/app/chat/commands/add_chat.go | 48 + .../internal/app/chat/commands/delete_chat.go | 49 + .../app/chat/commands/send_text_message.go | 37 + .../app/chat/queries/get_all_chats.go | 46 + .../queries/get_all_messages_from_chat.go | 48 + .../app/chat/queries/get_chat_by_pk.go | 54 + .../skychat/internal/app/chat/services.go | 45 + .../internal/app/messenger/messenger.go | 15 + .../internal/app/notification/notification.go | 69 + cmd/apps/skychat/internal/app/services.go | 26 + .../internal/app/user/commands/set_info.go | 44 + .../app/user/commands/set_settings.go | 41 + .../internal/app/user/queries/get_info.go | 39 + .../internal/app/user/queries/get_settings.go | 46 + .../skychat/internal/app/user/services.go | 40 + cmd/apps/skychat/internal/domain/chat/chat.go | 88 + .../internal/domain/chat/chat_repository.go | 13 + .../skychat/internal/domain/client/client.go | 126 ++ .../domain/client/client_repository.go | 7 + cmd/apps/skychat/internal/domain/info/info.go | 80 + .../internal/domain/message/message.go | 180 +++ cmd/apps/skychat/internal/domain/peer/peer.go | 11 + .../skychat/internal/domain/server/server.go | 21 + .../internal/domain/settings/settings.go | 46 + cmd/apps/skychat/internal/domain/user/user.go | 52 + .../internal/domain/user/user_repository.go | 7 + .../internal/inputports/http/chat/handler.go | 200 +++ .../http/notification.go/handler.go | 49 + .../internal/inputports/http/server.go | 92 ++ .../inputports/http/static/favicon.ico | Bin 0 -> 15086 bytes .../inputports/http/static/index.html | 1426 +++++++++++++++++ .../inputports/http}/static/p.png | Bin .../internal/inputports/http/user/handler.go | 144 ++ .../skychat/internal/inputports/services.go | 16 + .../messenger/netcon/messenger_service.go | 427 +++++ .../notification/http/notification_service.go | 36 + .../internal/interfaceadapters/services.go | 38 + .../storage/memory/chat_repo.go | 118 ++ .../storage/memory/client_repo.go | 55 + .../storage/memory/user_repo.go | 56 + cmd/apps/skychat/skychat.go | 280 +--- cmd/apps/skychat/static/index.html | 745 --------- 42 files changed, 3961 insertions(+), 999 deletions(-) create mode 100644 cmd/apps/skychat/internal/app/chat/commands/add_chat.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/delete_chat.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/send_text_message.go create mode 100644 cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go create mode 100644 cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go create mode 100644 cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go create mode 100644 cmd/apps/skychat/internal/app/chat/services.go create mode 100644 cmd/apps/skychat/internal/app/messenger/messenger.go create mode 100644 cmd/apps/skychat/internal/app/notification/notification.go create mode 100644 cmd/apps/skychat/internal/app/services.go create mode 100644 cmd/apps/skychat/internal/app/user/commands/set_info.go create mode 100644 cmd/apps/skychat/internal/app/user/commands/set_settings.go create mode 100644 cmd/apps/skychat/internal/app/user/queries/get_info.go create mode 100644 cmd/apps/skychat/internal/app/user/queries/get_settings.go create mode 100644 cmd/apps/skychat/internal/app/user/services.go create mode 100644 cmd/apps/skychat/internal/domain/chat/chat.go create mode 100644 cmd/apps/skychat/internal/domain/chat/chat_repository.go create mode 100644 cmd/apps/skychat/internal/domain/client/client.go create mode 100644 cmd/apps/skychat/internal/domain/client/client_repository.go create mode 100644 cmd/apps/skychat/internal/domain/info/info.go create mode 100644 cmd/apps/skychat/internal/domain/message/message.go create mode 100644 cmd/apps/skychat/internal/domain/peer/peer.go create mode 100644 cmd/apps/skychat/internal/domain/server/server.go create mode 100644 cmd/apps/skychat/internal/domain/settings/settings.go create mode 100644 cmd/apps/skychat/internal/domain/user/user.go create mode 100644 cmd/apps/skychat/internal/domain/user/user_repository.go create mode 100644 cmd/apps/skychat/internal/inputports/http/chat/handler.go create mode 100644 cmd/apps/skychat/internal/inputports/http/notification.go/handler.go create mode 100644 cmd/apps/skychat/internal/inputports/http/server.go create mode 100644 cmd/apps/skychat/internal/inputports/http/static/favicon.ico create mode 100644 cmd/apps/skychat/internal/inputports/http/static/index.html rename cmd/apps/skychat/{ => internal/inputports/http}/static/p.png (100%) create mode 100644 cmd/apps/skychat/internal/inputports/http/user/handler.go create mode 100644 cmd/apps/skychat/internal/inputports/services.go create mode 100644 cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go create mode 100644 cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go create mode 100644 cmd/apps/skychat/internal/interfaceadapters/services.go create mode 100644 cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go create mode 100644 cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go create mode 100644 cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go delete mode 100644 cmd/apps/skychat/static/index.html diff --git a/cmd/apps/skychat/internal/app/chat/commands/add_chat.go b/cmd/apps/skychat/internal/app/chat/commands/add_chat.go new file mode 100644 index 000000000..a99d93605 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/add_chat.go @@ -0,0 +1,48 @@ +package commands + +import ( + "fmt" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" +) + +//AddChatModel of AddChatRequestHandler +type AddChatRequest struct { + Pk cipher.PubKey +} + +//AddNewChatRequestHandler struct that allows handling AddChatRequest +type AddChatRequestHandler interface { + Handle(command AddChatRequest) error +} + +type addChatRequestHandler struct { + messengerService messenger.Service + chatRepo chat.ChatRepository +} + +//NewAddChatRequestHandler Initializes an AddCommandHandler +func NewAddChatRequestHandler(chatRepo chat.ChatRepository, messengerService messenger.Service) AddChatRequestHandler { + return addChatRequestHandler{chatRepo: chatRepo, messengerService: messengerService} +} + +//Handle Handles the AddChatRequest +func (h addChatRequestHandler) Handle(req AddChatRequest) error { + fmt.Println("AddChatHandler - Request: " + req.Pk.Hex()) + //1. check if the pubkey is already in chats + _, err := h.chatRepo.GetByPK(req.Pk) + if err == nil { + return fmt.Errorf("chat %s already added", req.Pk.Hex()) + } + + err = h.messengerService.SendChatRequestMessage(req.Pk) + if err != nil { + return err + } + + go h.messengerService.Handle(req.Pk) //nolint:errcheck + + return nil +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_chat.go b/cmd/apps/skychat/internal/app/chat/commands/delete_chat.go new file mode 100644 index 000000000..cd1b23141 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/delete_chat.go @@ -0,0 +1,49 @@ +package commands + +import ( + "fmt" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" +) + +//DeleteChatRequest Command Model +type DeleteChatRequest struct { + Pk cipher.PubKey +} + +//DeleteChatRequestHandler Handler Struct with Dependencies +type DeleteChatRequestHandler interface { + Handle(command DeleteChatRequest) error +} + +type deleteChatRequestHandler struct { + cliRepo client.ClientRepository + chatRepo chat.ChatRepository +} + +//NewDeleteChatRequestHandler Handler constructor +func NewDeleteChatRequestHandler(cliRepo client.ClientRepository, chatRepo chat.ChatRepository) DeleteChatRequestHandler { + return deleteChatRequestHandler{cliRepo: cliRepo, chatRepo: chatRepo} +} + +//Handle Handles the DeleteChatRequest request +func (h deleteChatRequestHandler) Handle(command DeleteChatRequest) error { + _, err := h.chatRepo.GetByPK(command.Pk) + if err != nil { + return err + } + + pCli, err := h.cliRepo.GetClient() + if err != nil { + fmt.Printf("Error Getting client") + return err + } + + //close all routes + //TODO:this does not work as expected --> shouldnt only the routes be closed? + pCli.GetAppClient().Close() + + return h.chatRepo.Delete(command.Pk) +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go new file mode 100644 index 000000000..c825d77c3 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go @@ -0,0 +1,37 @@ +package commands + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" +) + +//SendTextMessageModel of SendTextMessageRequestHandler +type SendTextMessageRequest struct { + Pk cipher.PubKey + Msg []byte +} + +//SendTextMessageRequestHandler struct that allows handling SendTextMessageRequest +type SendTextMessageRequestHandler interface { + Handle(command SendTextMessageRequest) error +} + +type sendTextMessageRequestHandler struct { + messengerService messenger.Service +} + +//NewAddChatRequestHandler Initializes an AddCommandHandler +func NewSendTextMessageRequestHandler(messengerService messenger.Service) SendTextMessageRequestHandler { + return sendTextMessageRequestHandler{messengerService: messengerService} +} + +//Handle Handles the AddCragRequest +func (h sendTextMessageRequestHandler) Handle(req SendTextMessageRequest) error { + + err := h.messengerService.SendTextMessage(req.Pk, req.Msg) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go b/cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go new file mode 100644 index 000000000..2a1195417 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go @@ -0,0 +1,46 @@ +package queries + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" +) + +// GetAllChatsResult is the result of the GetAllChatsRequest Query +type GetAllChatsResult struct { + Pk cipher.PubKey + CType int + Info info.Info + Msgs []message.Message + Peers []peer.Peer +} + +//GetAllChatsRequestHandler Contains the dependencies of the Handler +type GetAllChatsRequestHandler interface { + Handle() ([]GetAllChatsResult, error) +} + +type getAllChatsRequestHandler struct { + repo chat.ChatRepository +} + +//NewGetAllChatsRequestHandler Handler constructor +func NewGetAllChatsRequestHandler(repo chat.ChatRepository) GetAllChatsRequestHandler { + return getAllChatsRequestHandler{repo: repo} +} + +//Handle Handles the query +func (h getAllChatsRequestHandler) Handle() ([]GetAllChatsResult, error) { + + res, err := h.repo.GetAll() + if err != nil { + return nil, err + } + var result []GetAllChatsResult + for _, chat := range res { + result = append(result, GetAllChatsResult{Pk: chat.GetPK(), CType: chat.GetType(), Info: chat.GetInfo(), Msgs: chat.GetMessages(), Peers: chat.GetPeers()}) + } + return result, nil +} diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go b/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go new file mode 100644 index 000000000..460f9c5c9 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go @@ -0,0 +1,48 @@ +package queries + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" +) + +//GetAllMessagesFromChat Model of the Handler +type GetAllMessagesFromChatRequest struct { + pk cipher.PubKey +} + +// GetAllMessagesFromChatResult is the return model of Chat Query Handlers +type GetAllMessagesFromChatResult struct { + messages []message.Message +} + +//type GetAllMessagesFromChatRequestHandler provides an interfaces to handle a GetAllMessagesFromChatRequest and return a *GetAllMessagesFromChatResult +type GetAllMessagesFromChatRequestHandler interface { + Handle(query GetAllMessagesFromChatRequest) (GetAllMessagesFromChatResult, error) +} + +type getAllMessagesFromChatRequestHandler struct { + repo chat.ChatRepository +} + +//NewGetAllMessagesFromChatRequestHandler Handler Constructor +func NewGetAllMessagesFromChatRequestHandler(repo chat.ChatRepository) GetAllMessagesFromChatRequestHandler { + return getAllMessagesFromChatRequestHandler{repo: repo} +} + +//Handle Handlers the GetAllMessagesFromChatRequest query +func (h getAllMessagesFromChatRequestHandler) Handle(query GetAllMessagesFromChatRequest) (GetAllMessagesFromChatResult, error) { + var result GetAllMessagesFromChatResult + + chat, err := h.repo.GetByPK(query.pk) + if err != nil { + return result, err + } + + msgs := chat.GetMessages() + + if msgs != nil { + result = GetAllMessagesFromChatResult{messages: msgs} + } + return result, err +} diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go b/cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go new file mode 100644 index 000000000..6b74d9026 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go @@ -0,0 +1,54 @@ +package queries + +import ( + "net" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" +) + +//GetChatByPK Model of the Handler +type GetChatByPKRequest struct { + Pk cipher.PubKey +} + +// GetChatByPKResult is the result of the GetChatByPKRequest Query +type GetChatByPKResult struct { + Pk cipher.PubKey + CType int + Conn net.Conn + Info info.Info + Msgs []message.Message + Peers []peer.Peer +} + +//GetChatByPKRequestHandler Contains the dependencies of the Handler +type GetChatByPKRequestHandler interface { + Handle(query GetChatByPKRequest) (GetChatByPKResult, error) +} + +type getChatByPKRequestHandler struct { + repo chat.ChatRepository +} + +//NewGetChatByPKRequestHandler Handler constructor +func NewGetChatByPKRequestHandler(repo chat.ChatRepository) GetChatByPKRequestHandler { + return getChatByPKRequestHandler{repo: repo} +} + +//Handle Handles the query +func (h getChatByPKRequestHandler) Handle(query GetChatByPKRequest) (GetChatByPKResult, error) { + + res, err := h.repo.GetByPK(query.Pk) + var result GetChatByPKResult + + if err != nil { + return result, err + } + result = GetChatByPKResult{Pk: res.GetPK(), CType: res.GetType(), Conn: res.GetConnection(), Info: res.GetInfo(), Msgs: res.GetMessages(), Peers: res.GetPeers()} + + return result, nil +} diff --git a/cmd/apps/skychat/internal/app/chat/services.go b/cmd/apps/skychat/internal/app/chat/services.go new file mode 100644 index 000000000..69ad4e701 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/services.go @@ -0,0 +1,45 @@ +package chatservices + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/chat/commands" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/chat/queries" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" +) + +//Queries Contains all available query handlers of this app +type Queries struct { + GetAllChatsHandler queries.GetAllChatsRequestHandler + GetChatByPKHandler queries.GetChatByPKRequestHandler + GetAllMessagesFromChatHandler queries.GetAllMessagesFromChatRequestHandler +} + +//Commands Contains all available command handlers of this app +type Commands struct { + AddChatHandler commands.AddChatRequestHandler + DeleteChatHandler commands.DeleteChatRequestHandler + SendTextHandler commands.SendTextMessageRequestHandler +} + +//ChatServices Contains the grouped queries and commands of the app layer +type ChatServices struct { + Queries Queries + Commands Commands +} + +// NewServices Bootstraps Application Layer dependencies +func NewServices(cliRepo client.ClientRepository, chatRepo chat.ChatRepository, ms messenger.Service) ChatServices { + return ChatServices{ + Queries: Queries{ + GetAllChatsHandler: queries.NewGetAllChatsRequestHandler(chatRepo), + GetChatByPKHandler: queries.NewGetChatByPKRequestHandler(chatRepo), + GetAllMessagesFromChatHandler: queries.NewGetAllMessagesFromChatRequestHandler(chatRepo), + }, + Commands: Commands{ + AddChatHandler: commands.NewAddChatRequestHandler(chatRepo, ms), + DeleteChatHandler: commands.NewDeleteChatRequestHandler(cliRepo, chatRepo), + SendTextHandler: commands.NewSendTextMessageRequestHandler(ms), + }, + } +} diff --git a/cmd/apps/skychat/internal/app/messenger/messenger.go b/cmd/apps/skychat/internal/app/messenger/messenger.go new file mode 100644 index 000000000..b0c864bad --- /dev/null +++ b/cmd/apps/skychat/internal/app/messenger/messenger.go @@ -0,0 +1,15 @@ +package messenger + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" +) + +// Service interface is the interface to the service +type Service interface { + Handle(pk cipher.PubKey) error + Listen() + SendTextMessage(pk cipher.PubKey, msg []byte) error + SendChatRequestMessage(pk cipher.PubKey) error + SendInfoMessage(pk cipher.PubKey, info info.Info) error +} diff --git a/cmd/apps/skychat/internal/app/notification/notification.go b/cmd/apps/skychat/internal/app/notification/notification.go new file mode 100644 index 000000000..d293f80ee --- /dev/null +++ b/cmd/apps/skychat/internal/app/notification/notification.go @@ -0,0 +1,69 @@ +package notification + +import ( + "encoding/json" + "fmt" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" +) + +const ( + // ErrNotifType notify about errors + ErrNotifType = iota + NewAddChatNotifType //notify about an added chat by the user + NewChatNotifType //notify about a new chat initiated by a peer + NewMsgNotifType //notify about new message + //DeleteChatNotifType //notify about a deleted chat + //TODO: add SentMsgnNotifType +) + +// Notification provides a struct to send messages via the Service +type Notification struct { + Type int64 `json:"type"` + Message string `json:"message"` +} + +func NewMsgNotification(pk cipher.PubKey, msg message.Message) Notification { + Msg, err := json.Marshal(message.NewJSONMessage(msg)) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + } + + clientMsg, err := json.Marshal(map[string]string{"pk": pk.Hex(), "message": string(Msg)}) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + } + return Notification{ + Type: NewMsgNotifType, + Message: string(clientMsg), + } +} + +func NewAddChatNotification(pk cipher.PubKey) Notification { + clientMsg, err := json.Marshal(map[string]string{"pk": pk.Hex()}) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + } + return Notification{ + Type: NewAddChatNotifType, + Message: string(clientMsg), + } +} + +func NewChatNotification(pk cipher.PubKey) Notification { + clientMsg, err := json.Marshal(map[string]string{"pk": pk.Hex()}) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + } + return Notification{ + Type: NewChatNotifType, + Message: string(clientMsg), + } +} + +// Service sends Notification +type Service interface { + GetChannel() chan string + Notify(notification Notification) error +} diff --git a/cmd/apps/skychat/internal/app/services.go b/cmd/apps/skychat/internal/app/services.go new file mode 100644 index 000000000..3106c2cf3 --- /dev/null +++ b/cmd/apps/skychat/internal/app/services.go @@ -0,0 +1,26 @@ +package app + +import ( + chatservices "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" + userservices "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/user" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" +) + +//Services contains all exposed services of the application layer +type Services struct { + NotificationService notification.Service + ChatServices chatservices.ChatServices + UserServices userservices.UserServices +} + +// NewServices Bootstraps Application Layer dependencies +func NewServices(cliRepo client.ClientRepository, usrRepo user.UserRepository, chatRepo chat.ChatRepository, notifService notification.Service, ms messenger.Service) Services { + return Services{ + NotificationService: notifService, + ChatServices: chatservices.NewServices(cliRepo, chatRepo, ms), + UserServices: userservices.NewServices(usrRepo, chatRepo)} +} diff --git a/cmd/apps/skychat/internal/app/user/commands/set_info.go b/cmd/apps/skychat/internal/app/user/commands/set_info.go new file mode 100644 index 000000000..5027fb085 --- /dev/null +++ b/cmd/apps/skychat/internal/app/user/commands/set_info.go @@ -0,0 +1,44 @@ +package commands + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" +) + +//SetInfoModel of SetInfoRequestHandler +type SetInfoRequest struct { + Alias string + Desc string + Img string +} + +//SetInfoRequestHandler struct that allows handling SetInfoRequest +type SetInfoRequestHandler interface { + Handle(command SetInfoRequest) error +} + +type setInfoRequestHandler struct { + usrRepo user.UserRepository +} + +//NewSetInfoRequestHandler Initializes an SetInfoHandler +func NewSetInfoRequestHandler(usrRepo user.UserRepository) SetInfoRequestHandler { + return setInfoRequestHandler{usrRepo: usrRepo} +} + +//Handle Handles the SetInfoRequest +func (h setInfoRequestHandler) Handle(req SetInfoRequest) error { + + pUsr, err := h.usrRepo.GetUser() + if err != nil { + //TODO: implement error + } + + i := info.NewInfo(pUsr.GetInfo().GetPK(), req.Alias, req.Desc, req.Img) + + pUsr.SetInfo(i) + + //TODO:Send info to peers that the info was updated + + return h.usrRepo.SetUser(pUsr) +} diff --git a/cmd/apps/skychat/internal/app/user/commands/set_settings.go b/cmd/apps/skychat/internal/app/user/commands/set_settings.go new file mode 100644 index 000000000..9270215f3 --- /dev/null +++ b/cmd/apps/skychat/internal/app/user/commands/set_settings.go @@ -0,0 +1,41 @@ +package commands + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/settings" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" +) + +//SetSettingsRequestModel of SetSettingsRequestHandler +type SetSettingsRequest struct { + Blacklist []cipher.PubKey +} + +//SetSettingsRequestHandler struct that allows handling SetSettingsRequest +type SetSettingsRequestHandler interface { + Handle(command SetSettingsRequest) error +} + +type setSettingsRequestHandler struct { + usrRepo user.UserRepository +} + +//NewSetSettingsRequestHandler Initializes an SetSettingsRequestHandler +func NewSetSettingsRequestHandler(usrRepo user.UserRepository) SetSettingsRequestHandler { + return setSettingsRequestHandler{usrRepo: usrRepo} +} + +//Handle Handles the SetSettingsRequest +func (h setSettingsRequestHandler) Handle(req SetSettingsRequest) error { + + pUsr, err := h.usrRepo.GetUser() + if err != nil { + //TODO: implement error + } + + s := settings.NewSettings(req.Blacklist) + + pUsr.SetSettings(s) + + return h.usrRepo.SetUser(pUsr) +} diff --git a/cmd/apps/skychat/internal/app/user/queries/get_info.go b/cmd/apps/skychat/internal/app/user/queries/get_info.go new file mode 100644 index 000000000..60fb0855b --- /dev/null +++ b/cmd/apps/skychat/internal/app/user/queries/get_info.go @@ -0,0 +1,39 @@ +package queries + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" +) + +// GetUserInfoResult is the result of the GetUserInfoRequest Query +type GetUserInfoResult struct { + Pk string + Alias string + Desc string + Img string +} + +//GetUserInfoRequestHandler Contains the dependencies of the Handler +type GetUserInfoRequestHandler interface { + Handle() (*GetUserInfoResult, error) +} + +type getUserInfoRequestHandler struct { + usrRepo user.UserRepository +} + +//NewGetUserInfoRequestHandler Handler constructor +func NewGetUserInfoRequestHandler(usrRepo user.UserRepository) GetUserInfoRequestHandler { + return getUserInfoRequestHandler{usrRepo: usrRepo} +} + +//Handle Handles the query +func (h getUserInfoRequestHandler) Handle() (*GetUserInfoResult, error) { + usr, err := h.usrRepo.GetUser() + var result *GetUserInfoResult + if usr != nil && err == nil { + i := usr.GetInfo() + result = &GetUserInfoResult{Pk: i.GetPK().Hex(), Alias: i.GetAlias(), Desc: i.GetDescription(), Img: i.GetImg()} + } + + return result, nil +} diff --git a/cmd/apps/skychat/internal/app/user/queries/get_settings.go b/cmd/apps/skychat/internal/app/user/queries/get_settings.go new file mode 100644 index 000000000..5d642ffde --- /dev/null +++ b/cmd/apps/skychat/internal/app/user/queries/get_settings.go @@ -0,0 +1,46 @@ +package queries + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" +) + +// GetUserSettingsResult is the result of the GetUserSettingsRequest Query +type GetUserSettingsResult struct { + Blacklist []string +} + +//GetUserSettingsRequestHandler Contains the dependencies of the Handler +type GetUserSettingsRequestHandler interface { + Handle() (*GetUserSettingsResult, error) +} + +type getUserSettingsRequestHandler struct { + usrRepo user.UserRepository +} + +//NewGetUserSettingsRequestHandler Handler constructor +func NewGetUserSettingsRequestHandler(usrRepo user.UserRepository) GetUserSettingsRequestHandler { + return getUserSettingsRequestHandler{usrRepo: usrRepo} +} + +//Handle Handles the query +func (h getUserSettingsRequestHandler) Handle() (*GetUserSettingsResult, error) { + usr, err := h.usrRepo.GetUser() + var result *GetUserSettingsResult + + if usr != nil && err == nil { + s := usr.GetSettings() + + var blacklist []string + for _, element := range s.GetBlacklist() { + blacklist = append(blacklist, element.Hex()) + } + if blacklist == nil { + blacklist = []string{""} + } + + result = &GetUserSettingsResult{Blacklist: blacklist} + } + + return result, nil +} diff --git a/cmd/apps/skychat/internal/app/user/services.go b/cmd/apps/skychat/internal/app/user/services.go new file mode 100644 index 000000000..33415a4d6 --- /dev/null +++ b/cmd/apps/skychat/internal/app/user/services.go @@ -0,0 +1,40 @@ +package userservices + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/user/commands" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/user/queries" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" +) + +//Queries Contains all available query handlers of this app +type Queries struct { + GetUserInfoHandler queries.GetUserInfoRequestHandler + GetUserSettingsHandler queries.GetUserSettingsRequestHandler +} + +//Commands Contains all available command handlers of this app +type Commands struct { + SetInfoHandler commands.SetInfoRequestHandler + SetSettingsHandler commands.SetSettingsRequestHandler +} + +//UserServices Contains the grouped queries and commands of the app layer +type UserServices struct { + Queries Queries + Commands Commands +} + +// NewServices Bootstraps Application Layer dependencies +func NewServices(cliRepo user.UserRepository, chatRepo chat.ChatRepository) UserServices { + return UserServices{ + Queries: Queries{ + GetUserInfoHandler: queries.NewGetUserInfoRequestHandler(cliRepo), + GetUserSettingsHandler: queries.NewGetUserSettingsRequestHandler(cliRepo), + }, + Commands: Commands{ + SetInfoHandler: commands.NewSetInfoRequestHandler(cliRepo), + SetSettingsHandler: commands.NewSetSettingsRequestHandler(cliRepo), + }, + } +} diff --git a/cmd/apps/skychat/internal/domain/chat/chat.go b/cmd/apps/skychat/internal/domain/chat/chat.go new file mode 100644 index 000000000..cbefb0710 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/chat/chat.go @@ -0,0 +1,88 @@ +package chat + +import ( + "net" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" +) + +const ( + errChatType = iota + GroupChat + PeerChat +) + +type Chat struct { + PK cipher.PubKey + CType int + Conn net.Conn + Info info.Info + Msgs []message.Message + + //GroupChat + peers []peer.Peer +} + +// Getter +func (c *Chat) GetPK() cipher.PubKey { + return c.PK +} + +func (c *Chat) GetType() int { + return c.CType +} + +func (c *Chat) GetConnection() net.Conn { + return c.Conn +} + +func (c *Chat) GetInfo() info.Info { + return c.Info +} + +func (c *Chat) GetMessages() []message.Message { + return c.Msgs +} + +func (c *Chat) GetPeers() []peer.Peer { + return c.peers +} + +//Setter + +func (c *Chat) SetConnection(Conn net.Conn) { + c.Conn = Conn +} + +func (c *Chat) DeleteConnection() { + c.Conn = nil +} + +//Add the given message to the given chat +func (c *Chat) AddMessage(m message.Message) { + c.Msgs = append(c.Msgs, m) +} + +//Constructors + +func NewUndefinedChat(PK cipher.PubKey) Chat { + c := Chat{} + c.PK = PK + c.CType = errChatType + c.Conn = nil + c.Info = info.NewDefaultInfo() + c.Msgs = []message.Message{} + return c +} + +func NewChat(PK cipher.PubKey, CType int, i info.Info, Msgs []message.Message) Chat { + c := Chat{} + c.PK = PK + c.CType = CType + c.Info = i + c.Msgs = Msgs + return c +} diff --git a/cmd/apps/skychat/internal/domain/chat/chat_repository.go b/cmd/apps/skychat/internal/domain/chat/chat_repository.go new file mode 100644 index 000000000..43c611a55 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/chat/chat_repository.go @@ -0,0 +1,13 @@ +package chat + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" +) + +type ChatRepository interface { + GetByPK(pk cipher.PubKey) (*Chat, error) + GetAll() ([]Chat, error) + Add(c Chat) error + Update(c Chat) error + Delete(pk cipher.PubKey) error +} diff --git a/cmd/apps/skychat/internal/domain/client/client.go b/cmd/apps/skychat/internal/domain/client/client.go new file mode 100644 index 000000000..cc6987021 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/client/client.go @@ -0,0 +1,126 @@ +package client + +import ( + "fmt" + "os" + "os/signal" + "runtime" + + ipc "github.com/james-barrow/golang-ipc" + + "github.com/skycoin/skywire-utilities/pkg/buildinfo" + "github.com/skycoin/skywire-utilities/pkg/logging" + "github.com/skycoin/skywire/pkg/app" + "github.com/skycoin/skywire/pkg/app/appnet" + "github.com/skycoin/skywire/pkg/app/appserver" + "github.com/skycoin/skywire/pkg/routing" + "github.com/skycoin/skywire/pkg/skyenv" +) + +type Client struct { + appCl *app.Client // Skywire app client + ipcCl *ipc.Client // IPC client + netType appnet.Type // app netType + port routing.Port // app port + log *logging.Logger // app logger + clientCh chan string // client channel +} + +//Getter + +func (c *Client) GetAppClient() *app.Client { + return c.appCl +} + +func (c *Client) GetNetType() appnet.Type { + return c.netType +} + +func (c *Client) GetPort() routing.Port { + return c.port +} +func (c *Client) GetLog() *logging.Logger { + return c.log +} + +func (c *Client) GetChannel() chan string { + return c.clientCh +} + +// +func NewClient() *Client { + c := Client{} + c.appCl = app.NewClient(nil) + //defer c.appCl.Close() + + if _, err := buildinfo.Get().WriteTo(os.Stdout); err != nil { + fmt.Printf("Failed to output build info: %v", err) + } + + c.log = logging.MustGetLogger("chat") + c.netType = appnet.TypeSkynet + c.port = routing.Port(1) + + c.clientCh = make(chan string) + //defer close(c.clientCh) + + if c.appCl != nil { + c.SetAppStatus(appserver.AppDetailedStatusRunning) + } + + if runtime.GOOS == "windows" { + var err error + c.ipcCl, err = ipc.StartClient(skyenv.SkychatName, nil) + if err != nil { + fmt.Printf("Error creating ipc server for skychat client: %v\n", err) + c.SetAppError(err) + os.Exit(1) + } + go handleIPCSignal(c.ipcCl) + } + + if runtime.GOOS != "windows" { + termCh := make(chan os.Signal, 1) + signal.Notify(termCh, os.Interrupt) + + go func() { + <-termCh + c.SetAppStatus(appserver.AppDetailedStatusStopped) + os.Exit(1) + }() + } + + return &c +} + +func (c *Client) IsEmtpy() bool { + return *c == Client{} +} + +func (c *Client) SetAppStatus(status appserver.AppDetailedStatus) { + err := c.appCl.SetDetailedStatus(string(status)) + if err != nil { + fmt.Printf("Failed to set status %v: %v\n", status, err) + } +} + +func (c *Client) SetAppError(appErr error) { + err := c.appCl.SetError(appErr.Error()) + if err != nil { + fmt.Printf("Failed to set error %v: %v\n", appErr, err) + } +} + +func handleIPCSignal(client *ipc.Client) { + for { + m, err := client.Read() + if err != nil { + fmt.Printf("%s IPC received error: %v", skyenv.SkychatName, err) + } + if m.MsgType == skyenv.IPCShutdownMessageType { + fmt.Println("Stopping " + skyenv.SkychatName + " via IPC") + break + } + } + os.Exit(0) +} diff --git a/cmd/apps/skychat/internal/domain/client/client_repository.go b/cmd/apps/skychat/internal/domain/client/client_repository.go new file mode 100644 index 000000000..3d7c89e15 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/client/client_repository.go @@ -0,0 +1,7 @@ +package client + +type ClientRepository interface { + New() (Client, error) + GetClient() (*Client, error) + SetClient(c Client) error +} diff --git a/cmd/apps/skychat/internal/domain/info/info.go b/cmd/apps/skychat/internal/domain/info/info.go new file mode 100644 index 000000000..56cd9bc66 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/info/info.go @@ -0,0 +1,80 @@ +package info + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" +) + +// Info is conceptually similar to "account info" +type Info struct { + Pk cipher.PubKey + Alias string + Desc string + Img string +} + +// GetPK returns the public key +func (i Info) GetPK() cipher.PubKey { + return i.Pk +} + +// GetAlias returns the alias string +func (i Info) GetAlias() string { + return i.Alias +} + +// GetDescription returns the description string +func (i Info) GetDescription() string { + return i.Desc +} + +// GetDescription returns the Img string +func (i Info) GetImg() string { + return i.Img +} + +// SetPK sets the public key +func (i *Info) SetPK(Pk cipher.PubKey) { + i.Pk = Pk +} + +// SetAlias sets the alias string +func (i *Info) SetAlias(a string) { + i.Alias = a +} + +// SetDescription sets the description string +func (i *Info) SetDescription(d string) { + i.Desc = d +} + +// SetImg sets the Img string +func (i *Info) SetImg(Img string) { + i.Img = Img +} + +// NewInfo assembles and returns the Info struct +func NewInfo(Pk cipher.PubKey, Alias string, Desc string, Img string) Info { + info := Info{} + info.Pk = Pk + info.Alias = Alias + info.Desc = Desc + info.Img = Img + return info +} + +// NewDefaultInfo creates the defaults +func NewDefaultInfo() Info { + info := Info{} + info.Pk = cipher.PubKey{} + info.Alias = "Unknown" + info.Desc = "Unknown" + + info.Img = "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAIAAAAHjs1qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5OTMyNUUzOTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjY5OTMyNUU0OTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6Njk5MzI1RTE5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Njk5MzI1RTI5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7FIRCzAAAPn0lEQVR42uyd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" + + return info +} + +// IsEmpty checks if info is empty +func (i *Info) IsEmpty() bool { + return *i == Info{} +} diff --git a/cmd/apps/skychat/internal/domain/message/message.go b/cmd/apps/skychat/internal/domain/message/message.go new file mode 100644 index 000000000..efc5edce3 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -0,0 +1,180 @@ +package message + +import ( + "encoding/json" + "time" + + "github.com/skycoin/skywire-utilities/pkg/cipher" +) + +//types of messages +const ( + ErrMsgType = iota + ConnMsgType //used to handle connections + TxtMsgType //the txt peers send to each other or within groups + InfoMsgType //used to send and ask for info like what type of chat is the pk (group/peer), get all msgs, member infos etc. + CmdMsgType //used to control a server (e.g. send ban-peer or delete-msg commands) +) + +//subtypes of connMsgType +const ( + ErrConnMsg = iota + ConnMsgTypeRequest + ConnMsgTypeAccept + ConnMsgTypeReject +) + +//types of messageStatus +const ( + MsgStatusInitial = iota + MsgStatusSent + MsgStatusReceived +) + +type Message struct { + ID int64 //an identifier for p2p chats and groups, Id is set by the receiver/server + Origin cipher.PubKey //the originator of the Message + Time time.Time //the utc+0 timestamp of the Message + Sender cipher.PubKey //from who the Message was received (e.g. peer/group) + Msgtype int //see const above + MsgSubtype int //see consts above + Message []byte //the actual Message + Status int //"Sent" or "Received" + Seen bool //flag to save whether the Message was read or not by the receiver (only for local notifications) -> online feedback will be implemented in future versions +} + +type JSONMessage struct { + ID int64 `json:"Id"` + Origin cipher.PubKey `json:"Origin"` + Time time.Time `json:"Time"` + Sender cipher.PubKey `json:"Sender"` + Msgtype int `json:"Msgtype"` + MsgSubtype int `json:"MsgSubtype"` + Message string `json:"Message"` + Status int `json:"Status"` + Seen bool `json:"Seen"` +} + +func NewJSONMessage(m Message) JSONMessage { + return JSONMessage{ + m.ID, + m.Origin, + m.Time, + m.Sender, + m.Msgtype, + m.MsgSubtype, + string(m.Message), + m.Status, + m.Seen, + } +} + +func NewMessage(m JSONMessage) Message { + return Message{ + m.ID, + m.Origin, + m.Time, + m.Sender, + m.Msgtype, + m.MsgSubtype, + []byte(m.Message), + m.Status, + m.Seen, + } +} + +func (m Message) MarshalJSON() ([]byte, error) { + return json.Marshal(NewJSONMessage(m)) +} + +func NewTextMessage(pk cipher.PubKey, msg []byte) Message { + m := Message{} + m.Origin = pk + m.Sender = pk + m.Msgtype = TxtMsgType + m.MsgSubtype = 0 + m.Message = msg + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + +func NewChatRequestMessage(pk cipher.PubKey) Message { + m := Message{} + m.Origin = pk + m.Sender = pk + m.Msgtype = ConnMsgType + m.MsgSubtype = ConnMsgTypeRequest + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + +func NewChatAcceptMessage(pk cipher.PubKey) Message { + m := Message{} + m.Origin = pk + m.Sender = pk + m.Msgtype = ConnMsgType + m.MsgSubtype = ConnMsgTypeAccept + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + +func NewChatRejectMessage(pk cipher.PubKey) Message { + m := Message{} + m.Origin = pk + m.Sender = pk + m.Msgtype = ConnMsgType + m.MsgSubtype = ConnMsgTypeReject + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + +func NewChatInfoMessage(pk cipher.PubKey, info []byte) Message { + m := Message{} + m.Origin = pk + m.Sender = pk + m.Msgtype = InfoMsgType + m.Message = info + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + +func (m *Message) GetId() int64 { + return m.ID +} + +func (m *Message) GetOrigin() cipher.PubKey { + return m.Origin +} + +func (m *Message) GetTime() time.Time { + return m.Time +} + +func (m *Message) GetSender() cipher.PubKey { + return m.Sender +} + +func (m *Message) GetMessageType() int { + return m.Msgtype +} + +func (m *Message) GetMessage() []byte { + return m.Message +} + +func (m *Message) GetStatus() int { + return m.Status +} + +func (m *Message) GetSeen() bool { + return m.Seen +} + +func (m *Message) SetStatus(status int) { + m.Status = status +} diff --git a/cmd/apps/skychat/internal/domain/peer/peer.go b/cmd/apps/skychat/internal/domain/peer/peer.go new file mode 100644 index 000000000..e9e3802ff --- /dev/null +++ b/cmd/apps/skychat/internal/domain/peer/peer.go @@ -0,0 +1,11 @@ +package peer + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" +) + +type Peer struct { + Info info.Info + //TODO: make peerRepository so the user can give each Peer a Custom Alias + //TODO: CustomAlias string +} diff --git a/cmd/apps/skychat/internal/domain/server/server.go b/cmd/apps/skychat/internal/domain/server/server.go new file mode 100644 index 000000000..74cac3c4d --- /dev/null +++ b/cmd/apps/skychat/internal/domain/server/server.go @@ -0,0 +1,21 @@ +package server + +import ( + "sync" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" + "github.com/skycoin/skywire/pkg/app" +) + +type Server struct { + appCl *app.Client // Skywire app client + clientCh chan string // + conns map[cipher.PubKey]peer.Peer // peer connections + info info.Info // the public info of the server + msgs []message.Message // all messages send/received + blacklist []cipher.PubKey // Blacklist to block inocming connections + connsMu sync.Mutex // +} diff --git a/cmd/apps/skychat/internal/domain/settings/settings.go b/cmd/apps/skychat/internal/domain/settings/settings.go new file mode 100644 index 000000000..47064cdfe --- /dev/null +++ b/cmd/apps/skychat/internal/domain/settings/settings.go @@ -0,0 +1,46 @@ +package settings + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" +) + +type Settings struct { + blacklist []cipher.PubKey // Blacklist to block inocming connections +} + +//Getter +func (s Settings) GetBlacklist() []cipher.PubKey { + return s.blacklist +} + +//Setter +func (s *Settings) SetBlacklist(bl []cipher.PubKey) { + s.blacklist = bl +} + +//Methods +func (s Settings) InBlacklist(pk cipher.PubKey) bool { + for _, b := range s.blacklist { + if b == pk { + return true + } + } + return false +} + +//Constructor for default settings +func NewDefaultSettings() Settings { + s := Settings{} + s.blacklist = []cipher.PubKey{} + return s +} + +func NewSettings(blacklist []cipher.PubKey) Settings { + s := Settings{} + s.blacklist = blacklist + return s +} + +func (s *Settings) IsEmpty() bool { + return len(s.blacklist) <= 0 +} diff --git a/cmd/apps/skychat/internal/domain/user/user.go b/cmd/apps/skychat/internal/domain/user/user.go new file mode 100644 index 000000000..df9e8a02d --- /dev/null +++ b/cmd/apps/skychat/internal/domain/user/user.go @@ -0,0 +1,52 @@ +package user + +import ( + "fmt" + + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/settings" +) + +type User struct { + info info.Info // the info of the local user + settings settings.Settings // the settings of the local user +} + +//Getter +func (u *User) GetInfo() *info.Info { + return &u.info +} + +func (u *User) GetSettings() *settings.Settings { + return &u.settings +} + +//Setter +func (u *User) SetInfo(i info.Info) { + u.info = i +} + +func (u *User) SetSettings(s settings.Settings) { + u.settings = s +} + +// +func NewDefaultUser() *User { + fmt.Println("user - NewDefaultUser") + u := User{} + + u.info = info.NewDefaultInfo() + u.settings = settings.NewDefaultSettings() + fmt.Println(u) + + return &u +} + +func (u *User) IsEmpty() bool { + + if u.info.IsEmpty() && u.settings.IsEmpty() { + return true + } else { + return false + } +} diff --git a/cmd/apps/skychat/internal/domain/user/user_repository.go b/cmd/apps/skychat/internal/domain/user/user_repository.go new file mode 100644 index 000000000..40aef9793 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/user/user_repository.go @@ -0,0 +1,7 @@ +package user + +type UserRepository interface { + NewUser() (User, error) + GetUser() (*User, error) + SetUser(u *User) error +} diff --git a/cmd/apps/skychat/internal/inputports/http/chat/handler.go b/cmd/apps/skychat/internal/inputports/http/chat/handler.go new file mode 100644 index 000000000..1fe55d760 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/chat/handler.go @@ -0,0 +1,200 @@ +package chat + +import ( + "encoding/json" + "fmt" + "net/http" + "strings" + + "github.com/gorilla/mux" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + chatservices "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/chat/commands" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/chat/queries" +) + +//Handler Chat http request handler +type Handler struct { + chatServices chatservices.ChatServices +} + +//NewHandler Constructor +func NewHandler(cs chatservices.ChatServices) *Handler { + return &Handler{chatServices: cs} +} + +//GetAll Returns all available chats +func (c Handler) GetAll(w http.ResponseWriter, r *http.Request) { + fmt.Println(formatRequest(r)) + chats, err := c.chatServices.Queries.GetAllChatsHandler.Handle() + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprintf(w, err.Error()) + return + } + + err = json.NewEncoder(w).Encode(chats) + if err != nil { + return + } +} + +// GetChatPKURLParam contains the parameter identifier to be parsed by the handler +const GetChatPKURLParam = "chatPK" + +//GetByPK Returns the chat with the provided pk +func (c Handler) GetByPK(w http.ResponseWriter, r *http.Request) { + fmt.Println(formatRequest(r)) + vars := mux.Vars(r) + pk := cipher.PubKey{} + err := pk.Set(vars[GetChatPKURLParam]) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + + chat, err := c.chatServices.Queries.GetChatByPKHandler.Handle(queries.GetChatByPKRequest{Pk: pk}) + + /*if err == nil && chat == nil { + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, "Not Found") + return + }*/ + + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + err = json.NewEncoder(w).Encode(chat) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } +} + +//AddChatRequestModel represents the request model expected for Add request +type AddChatRequestModel struct { + Pk string `json:"pk"` +} + +//AddChat adds the provided pk +func (c Handler) Add(w http.ResponseWriter, r *http.Request) { + //fmt.Println(formatRequest(r)) + var chatToAdd AddChatRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&chatToAdd) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr.Error()) + return + } + fmt.Println("HTTPHandler - Add - PK: " + chatToAdd.Pk) + + pk := cipher.PubKey{} + err := pk.Set(chatToAdd.Pk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + + err = c.chatServices.Commands.AddChatHandler.Handle(commands.AddChatRequest{ + Pk: pk, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + w.WriteHeader(http.StatusOK) +} + +//DeleteChatPKURLParam contains the parameter identifier to be parsed by the handler +const DeleteChatPKURLParam = "delete" + +//Delete Deletes the crag with the provided id +func (c Handler) Delete(w http.ResponseWriter, r *http.Request) { + fmt.Println(formatRequest(r)) + vars := mux.Vars(r) + fmt.Println(vars) + fmt.Println(vars[DeleteChatPKURLParam]) + chatPK := cipher.PubKey{} + err := chatPK.Set(vars[DeleteChatPKURLParam]) + if err != nil { + fmt.Println("could not convert pubkey") + } + fmt.Println(chatPK.Hex()) + err = c.chatServices.Commands.DeleteChatHandler.Handle(commands.DeleteChatRequest{Pk: chatPK}) + if err != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, err.Error()) + } + +} + +//SendTextMessagePKURLParam contains the parameter identifier to be parsed by the handler +const SendTextMessagePKURLParam = "sendTxtMsg" + +//SendTextMessageRequestModel represents the request model expected for Add request +type SendTextMessageRequestModel struct { + Pk string `json:"pk"` + Msg string `json:"message"` +} + +//SendTextMessage sends a message to the provided pk +func (c Handler) SendTextMessage(w http.ResponseWriter, r *http.Request) { + fmt.Println(formatRequest(r)) + var msgToSend SendTextMessageRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&msgToSend) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr.Error()) + return + } + + pk := cipher.PubKey{} + err := pk.Set(msgToSend.Pk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + + err = c.chatServices.Commands.SendTextHandler.Handle(commands.SendTextMessageRequest{ + Pk: pk, + Msg: []byte(msgToSend.Msg), + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + w.WriteHeader(http.StatusOK) +} + +// formatRequest generates ascii representation of a request +func formatRequest(r *http.Request) string { + // Create return string + var request []string // Add the request string + request = append(request, "--------------------------------------\n") + url := fmt.Sprintf("%v %v %v", r.Method, r.URL, r.Proto) + request = append(request, url) // Add the host + request = append(request, fmt.Sprintf("Host: %v", r.Host)) // Loop through headers + for name, headers := range r.Header { + name = strings.ToLower(name) + for _, h := range headers { + request = append(request, fmt.Sprintf("%v: %v", name, h)) + } + } + // If this is a POST, add post data + if r.Method == "POST" { + r.ParseForm() + request = append(request, "\n") + request = append(request, r.Form.Encode()) + } // Return the request as a string + request = append(request, "--------------------------------------\n") + return strings.Join(request, "\n") +} diff --git a/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go b/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go new file mode 100644 index 000000000..208756ed2 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go @@ -0,0 +1,49 @@ +package notification + +import ( + "fmt" + "net/http" + + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" +) + +//Handler Chat http request handler +type Handler struct { + ns notification.Service +} + +//NewHandler Constructor +func NewHandler(ns notification.Service) *Handler { + return &Handler{ns: ns} +} + +//SubscribeNotifications sends all received msgs from channel to http +func (c Handler) SubscribeNotifications(w http.ResponseWriter, r *http.Request) { + + f, ok := w.(http.Flusher) + if !ok { + http.Error(w, "Streaming unsupported!", http.StatusBadRequest) + return + } + + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("Connection", "keep-alive") + w.Header().Set("Transfer-Encoding", "chunked") + + for { + select { + case <-r.Context().Done(): + fmt.Println("SSE connection were closed.") + return + + default: + msg, ok := <-c.ns.GetChannel() + if !ok { + return + } + fmt.Fprintf(w, "data: %s\n\n", msg) + f.Flush() + } + } +} diff --git a/cmd/apps/skychat/internal/inputports/http/server.go b/cmd/apps/skychat/internal/inputports/http/server.go new file mode 100644 index 000000000..90e27ffd3 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/server.go @@ -0,0 +1,92 @@ +package http + +import ( + "embed" + "fmt" + "io/fs" + "log" + "net/http" + + "github.com/gorilla/mux" + + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/http/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/http/notification.go" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/http/user" +) + +// the go embed static points to skywire/cmd/apps/skychat/internal/inputports/http/static + +//go:embed static/* +var embededFiles embed.FS + +// Server Represents the http server running for this service +type Server struct { + appServices app.Services + router *mux.Router +} + +//NewServer HTTP Server constructor +func NewServer(appServices app.Services) *Server { + httpServer := &Server{appServices: appServices} + httpServer.router = mux.NewRouter() + httpServer.router.Handle("/", http.FileServer(getFileSystem())) + //TODO: add router to favicon.ico instead of html base64 string + //TODO: could not get it to work with go embed but it should work withit + httpServer.AddChatHTTPRoutes() + httpServer.AddUserHTTPRoutes() + httpServer.AddNotificationHTTPRoutes() + http.Handle("/", httpServer.router) + + return httpServer +} + +// AddChatHTTPRoutes registers chat route handlers +func (httpServer *Server) AddChatHTTPRoutes() { + const chatsHTTPRoutePath = "/chats" + //Queries + httpServer.router.HandleFunc(chatsHTTPRoutePath, chat.NewHandler(httpServer.appServices.ChatServices).GetAll).Methods("GET") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/{"+chat.GetChatPKURLParam+"}", chat.NewHandler(httpServer.appServices.ChatServices).GetByPK).Methods("GET") + + //Commands + httpServer.router.HandleFunc(chatsHTTPRoutePath, chat.NewHandler(httpServer.appServices.ChatServices).Add).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/sendmessage", chat.NewHandler(httpServer.appServices.ChatServices).SendTextMessage).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/{"+chat.DeleteChatPKURLParam+"}", chat.NewHandler(httpServer.appServices.ChatServices).Delete).Methods("DELETE") + +} + +// AddUserHTTPRoutes registers user route handlers +func (httpServer *Server) AddUserHTTPRoutes() { + const userHTTPRoutePath = "/user" + //Queries + httpServer.router.HandleFunc(userHTTPRoutePath+"/"+user.GetInfoURLParam, user.NewHandler(httpServer.appServices.UserServices).GetInfo).Methods("GET") + httpServer.router.HandleFunc(userHTTPRoutePath+"/"+user.GetSettingsURLParam, user.NewHandler(httpServer.appServices.UserServices).GetSettings).Methods("GET") + + //Commands + httpServer.router.HandleFunc(userHTTPRoutePath+"/"+user.SetInfoURLParam, user.NewHandler(httpServer.appServices.UserServices).SetInfo).Methods("PUT") + httpServer.router.HandleFunc(userHTTPRoutePath+"/"+user.SetSettingsURLParam, user.NewHandler(httpServer.appServices.UserServices).SetSettings).Methods("PUT") +} + +// AddNotificationHTTPRoutes adds the sse route +func (httpServer *Server) AddNotificationHTTPRoutes() { + const notificationHTTPRoutePath = "/notifications" + // + httpServer.router.HandleFunc(notificationHTTPRoutePath, notification.NewHandler(httpServer.appServices.NotificationService).SubscribeNotifications).Methods("GET") +} + +//ListenAndServe Starts listening for requests +func (httpServer *Server) ListenAndServe(addr *string) { + fmt.Println("Serving HTTP on", *addr) + log.Fatal(http.ListenAndServe(*addr, nil)) + +} + +//get index file +func getFileSystem() http.FileSystem { + fsys, err := fs.Sub(embededFiles, "static") + if err != nil { + panic(err) + } + + return http.FS(fsys) +} diff --git a/cmd/apps/skychat/internal/inputports/http/static/favicon.ico b/cmd/apps/skychat/internal/inputports/http/static/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..cc325fd3cb29e15c66be1d29875f842fdc522be0 GIT binary patch literal 15086 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 literal 0 HcmV?d00001 diff --git a/cmd/apps/skychat/internal/inputports/http/static/index.html b/cmd/apps/skychat/internal/inputports/http/static/index.html new file mode 100644 index 000000000..87020c717 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/static/index.html @@ -0,0 +1,1426 @@ + + + + + + Skychat + + + + + + + + + +
+
+
+ +
+
    +
      + + +
      + + + + + + + \ No newline at end of file diff --git a/cmd/apps/skychat/static/p.png b/cmd/apps/skychat/internal/inputports/http/static/p.png similarity index 100% rename from cmd/apps/skychat/static/p.png rename to cmd/apps/skychat/internal/inputports/http/static/p.png diff --git a/cmd/apps/skychat/internal/inputports/http/user/handler.go b/cmd/apps/skychat/internal/inputports/http/user/handler.go new file mode 100644 index 000000000..9e5e23fe8 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/user/handler.go @@ -0,0 +1,144 @@ +package user + +import ( + "encoding/json" + "fmt" + "net/http" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + userservices "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/user" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/user/commands" +) + +//Handler User http request handler +type Handler struct { + userServices userservices.UserServices +} + +//NewHandler Constructor +func NewHandler(app userservices.UserServices) *Handler { + return &Handler{userServices: app} +} + +// GetSettingsURLParam contains the parameter identifier to be parsed by the handler +const GetSettingsURLParam = "settings" + +//GetSettings Returns the settings of the user +func (c Handler) GetSettings(w http.ResponseWriter, r *http.Request) { + settings, err := c.userServices.Queries.GetUserSettingsHandler.Handle() + if err == nil && settings == nil { + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, "Not Found") + return + } + + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + err = json.NewEncoder(w).Encode(settings) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } +} + +// GetInfoURLParam contains the parameter identifier to be parsed by the handler +const GetInfoURLParam = "info" + +//GetInfo Returns the info of the user +func (c Handler) GetInfo(w http.ResponseWriter, r *http.Request) { + info, err := c.userServices.Queries.GetUserInfoHandler.Handle() + if err == nil && info == nil { + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, "Not Found") + return + } + + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + err = json.NewEncoder(w).Encode(info) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } +} + +// SetInfoURLParam contains the parameter identifier to be parsed by the handler +const SetInfoURLParam = "info" + +//SetInfoRequestModel represents the request model of Update +type SetInfoRequestModel struct { + Alias string `json:"alias"` + Desc string `json:"desc"` + Img string `json:"img"` +} + +//SetInfo Updates the user's info with the provided data +func (c Handler) SetInfo(w http.ResponseWriter, r *http.Request) { + + var reqInfoToUpdate SetInfoRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&reqInfoToUpdate) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr) + return + } + + infoUpdateCommand := commands.SetInfoRequest{ + Alias: reqInfoToUpdate.Alias, + Desc: reqInfoToUpdate.Desc, + Img: reqInfoToUpdate.Img, + } + + err := c.userServices.Commands.SetInfoHandler.Handle(infoUpdateCommand) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprintf(w, err.Error()) + } + w.WriteHeader(http.StatusOK) +} + +// SetSettingsURLParam contains the parameter identifier to be parsed by the handler +const SetSettingsURLParam = "settings" + +//SetSettingsRequestModel represents the request model of SetSettings +type SetSettingsRequestModel struct { + Blacklist string `json:"blacklist"` +} + +//SetSettings sets the user's settings with the provided data +func (c Handler) SetSettings(w http.ResponseWriter, r *http.Request) { + + var reqSettingsToSet SetSettingsRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&reqSettingsToSet) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr) + return + } + + var keys cipher.PubKeys + err := keys.Set(reqSettingsToSet.Blacklist) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprintf(w, err.Error()) + } else { + setSettingsCommand := commands.SetSettingsRequest{ + Blacklist: keys, + } + + err = c.userServices.Commands.SetSettingsHandler.Handle(setSettingsCommand) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprintf(w, err.Error()) + } + } + w.WriteHeader(http.StatusOK) +} diff --git a/cmd/apps/skychat/internal/inputports/services.go b/cmd/apps/skychat/internal/inputports/services.go new file mode 100644 index 000000000..6402ca403 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/services.go @@ -0,0 +1,16 @@ +package inputports + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/http" +) + +//Services contains the ports services +type Services struct { + Server *http.Server +} + +//NewServices instantiates the services of input ports +func NewServices(appServices app.Services) Services { + return Services{Server: http.NewServer(appServices)} +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go new file mode 100644 index 000000000..542530844 --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -0,0 +1,427 @@ +package netcon + +import ( + "context" + "encoding/json" + "fmt" + "net" + "time" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire-utilities/pkg/netutil" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" + "github.com/skycoin/skywire/pkg/app/appnet" +) + +// MessengerService provides a netcon implementation of the Service +type MessengerService struct { + ctx context.Context + ns notification.Service + cliRepo client.ClientRepository + usrRepo user.UserRepository + chatRepo chat.ChatRepository +} + +// NewMessengerService constructor for MessengerService +func NewMessengerService(ns notification.Service, cR client.ClientRepository, uR user.UserRepository, chR chat.ChatRepository) *MessengerService { + ms := MessengerService{} + + /*ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + ms.ctx = ctx*/ + ms.ns = ns + ms.cliRepo = cR + ms.usrRepo = uR + ms.chatRepo = chR + + return &ms +} + +// Handle handles the chat connection and incoming messanges +func (ms MessengerService) Handle(pk cipher.PubKey) error { + var err error + + c, err := ms.chatRepo.GetByPK(pk) + if err != nil { + ch := chat.NewUndefinedChat(pk) + ms.chatRepo.Add(ch) + c = &ch + fmt.Printf("New skychat added: %s\n", pk) + } + + conn := c.GetConnection() + if conn == nil { + fmt.Printf("Error, no connection\n") + conn, err = ms.Dial(pk) + if err != nil { + return err + } + } + + for { + buf := make([]byte, 32*1024) + n, err := conn.Read(buf) + if err != nil { + fmt.Println("Failed to read packet:", err) + c.DeleteConnection() + return err + } + + //unmarshal the received bytes to a message.Message + m := message.Message{} + + err = json.Unmarshal(buf[:n], &m) + if err != nil { + fmt.Printf("Failed to unmarshal json message: %v", err) + } + + //TODO: first message has to be a request message, if not block and delete + //--> if we don't handle this it would be possible to send something else than request message via another + // app and bypass the blacklist + + //TODO: think about how to handle this + //If the received message has status MsgSTatusInitial it was just send and we have to send it back to let the + //peer know that we received it. + //if m.GetStatus() == message.MsgStatusInitial { + // m.SetStatus(message.MsgStatusReceived) + // ms.sendMessage(pk, m) + //} + //notify that a new message has been received + //save message to chatrepo + //TODO: make NewReceivedTextMessage + //! Can also be a message of the remote that the own send message has been received + + //get the current chat so when updating nothing gets overwritten + c, _ := ms.chatRepo.GetByPK(pk) + + switch m.GetMessageType() { + case message.ConnMsgType: + c.AddMessage(m) + ms.chatRepo.Update(*c) + err := ms.handleConnMsgType(m) + if err != nil { + fmt.Println(err) + } + case message.InfoMsgType: + jm := message.JSONMessage{} + err = json.Unmarshal(buf[:n], &jm) + if err != nil { + fmt.Printf("Failed to unmarshal json message: %v", err) + } + m = message.NewMessage(jm) + c.AddMessage(m) + ms.chatRepo.Update(*c) + + err = ms.handleInfoMsgType(c, m) + if err != nil { + fmt.Println(err) + } + case message.TxtMsgType: + jm := message.JSONMessage{} + err = json.Unmarshal(buf[:n], &jm) + if err != nil { + fmt.Printf("Failed to unmarshal json message: %v", err) + } + m = message.NewMessage(jm) + c.AddMessage(m) + ms.chatRepo.Update(*c) + err := ms.handleTextMsgType(c, m) + if err != nil { + fmt.Println(err) + } + case message.CmdMsgType: + //not allowed, only for servers/groups + default: + fmt.Printf("Incorrect data received") + } + } +} + +//Handles an incoming connection message and either accepts it and sends back the own info as message +//or if the public key is in the blacklist rejects the chat request. +func (ms MessengerService) handleConnMsgType(m message.Message) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + switch m.MsgSubtype { + case message.ConnMsgTypeRequest: + //check if sender is in blacklist, if not so send info message back, else reject chat + if !usr.GetSettings().InBlacklist(m.Sender) { + //notify about the new chat initiated by the user + an := notification.NewChatNotification(m.Sender) + ms.ns.Notify(an) + + msg := message.NewChatAcceptMessage(usr.GetInfo().GetPK()) + ms.sendMessage(m.Sender, msg) + + ms.SendInfoMessage(m.Sender, *usr.GetInfo()) + + //n := notification.NewMsgNotification(m.Sender, m) + //ms.ns.Notify(n) + } else { + msg := message.NewChatRejectMessage(usr.GetInfo().GetPK()) + ms.sendMessage(m.Sender, msg) + ms.chatRepo.Delete(m.Sender) + + //TODO: notify about a rejected chat request cause of blacklist + return fmt.Errorf("pk in blacklist") + } + case message.ConnMsgTypeAccept: + ms.SendInfoMessage(m.Sender, *usr.GetInfo()) + + case message.ConnMsgTypeReject: + //ms.chatRepo.Delete(m.Sender) + + n := notification.NewMsgNotification(m.Sender, m) + ms.ns.Notify(n) + return fmt.Errorf("peer rejected chat") + + } + + return nil +} + +//TODO: document what function does +func (ms MessengerService) handleInfoMsgType(c *chat.Chat, m message.Message) error { + //save info in chat info + //unmarshal the received message bytes to info.Info + i := info.Info{} + err := json.Unmarshal(m.Message, &i) + if err != nil { + fmt.Printf("Failed to unmarshal json message: %v", err) + } + c.Info = i + ms.chatRepo.Update(*c) + + //notify about new info message + n := notification.NewMsgNotification(c.GetPK(), m) + ms.ns.Notify(n) + + return nil +} + +//TODO: document what function does +func (ms MessengerService) handleTextMsgType(c *chat.Chat, m message.Message) error { + + n := notification.NewMsgNotification(c.GetPK(), message.NewTextMessage(m.Sender, m.Message)) + ms.ns.Notify(n) + + return nil +} + +// Dial dials the remote chat +func (ms MessengerService) Dial(pk cipher.PubKey) (net.Conn, error) { + + c, err := ms.chatRepo.GetByPK(pk) + if err != nil { + //Should not happen as before dial chats get added to repo + return nil, err + } + + pCli, err := ms.cliRepo.GetClient() + if err != nil { + fmt.Printf("Error Getting client") + return nil, err + } + + conn := c.GetConnection() + if conn != nil { + //TODO: maybe delete old connection and reconnect? + //TODO: or skip dialing if connection alive + //pCli.GetAppClient().Close() + } + + addr := appnet.Addr{ + Net: pCli.GetNetType(), + PubKey: c.GetPK(), + Port: pCli.GetPort(), + } + + var r = netutil.NewRetrier(pCli.GetLog(), 50*time.Millisecond, netutil.DefaultMaxBackoff, 5, 2) + + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + ms.ctx = ctx + + err = r.Do(ms.ctx, func() error { + //TODO: notify that dialing is happening? + conn, err = pCli.GetAppClient().Dial(addr) + //could not find a valid connection to a chat, so delete it. + ms.chatRepo.Delete(c.PK) + return err + }) + + if err != nil { + return nil, err + } + + c.SetConnection(conn) + ms.chatRepo.Update(*c) + return conn, nil +} + +//sendMessage sends a message to the given chat +func (ms MessengerService) sendMessage(pk cipher.PubKey, m message.Message) error { + c, err := ms.chatRepo.GetByPK(pk) + if err != nil { + ch := chat.NewUndefinedChat(pk) + ms.chatRepo.Add(ch) + c = &ch + fmt.Printf("New skychat added: %s\n", pk) + } + + bytes, err := json.Marshal(m) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + } + + conn := c.GetConnection() + if conn == nil { + conn, err = ms.Dial(pk) + if err != nil { + return err + } + } + + _, err = conn.Write(bytes) + if err != nil { + return err + } + + c, _ = ms.chatRepo.GetByPK(pk) + c.AddMessage(m) + ms.chatRepo.Update(*c) + + return nil +} + +//SendChatRequestMessage sends a chat request message to request a chat +func (ms MessengerService) SendChatRequestMessage(pk cipher.PubKey) error { + + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + m := message.NewChatRequestMessage(usr.GetInfo().GetPK()) + + err = ms.sendMessage(pk, m) + if err != nil { + return err + } + + //TODO: think about putting this notification in add_chat usecase + //notify about the added chat + an := notification.NewAddChatNotification(pk) + ms.ns.Notify(an) + + //notify about sent chat request message + n := notification.NewMsgNotification(pk, m) + ms.ns.Notify(n) + + return nil +} + +//SendTextMessage sends a text message to the given chat +func (ms MessengerService) SendTextMessage(pk cipher.PubKey, msg []byte) error { + fmt.Println("MessengerService - SendTextMessage") + + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + m := message.NewTextMessage(usr.GetInfo().GetPK(), msg) + + err = ms.sendMessage(pk, m) + if err != nil { + return err + } + + //notify about sent text message + n := notification.NewMsgNotification(pk, m) + ms.ns.Notify(n) + + return nil +} + +//SendInfoMessage sends a info message to the given chat +func (ms MessengerService) SendInfoMessage(pk cipher.PubKey, info info.Info) error { + fmt.Println("MessengerService - SendInfoMessage") + + bytes, err := json.Marshal(info) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + } + + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + m := message.NewChatInfoMessage(usr.GetInfo().GetPK(), bytes) + + err = ms.sendMessage(pk, m) + if err != nil { + return err + } + + //notify about sent info message + n := notification.NewMsgNotification(pk, m) + ms.ns.Notify(n) + + return nil +} + +//used to listen for new incoming chats and pass them to the connection_handle routine +func (ms MessengerService) Listen() { + pCli, err := ms.cliRepo.GetClient() + if err != nil { + fmt.Printf("Error getting client from repository: %s", err) + } + + l, err := pCli.GetAppClient().Listen(pCli.GetNetType(), pCli.GetPort()) + if err != nil { + fmt.Printf("Error listening network %v on port %d: %v\n", pCli.GetNetType(), pCli.GetPort(), err) + return + } + + for { + fmt.Println("Accepting skychat conn...") + conn, err := l.Accept() + if err != nil { + fmt.Println("Failed to accept conn:", err) + return + } + fmt.Println("Accepted skychat conn") + raddr := conn.RemoteAddr().(appnet.Addr) + + fmt.Printf("Accepted skychat conn on %s from %s\n", conn.LocalAddr(), raddr.PubKey) + + //check if the remote addr already is a saved chat + c, err := ms.chatRepo.GetByPK(raddr.PubKey) + if err != nil { + ch := chat.NewUndefinedChat(raddr.PubKey) + ms.chatRepo.Add(ch) + c = &ch + fmt.Printf("New skychat added: %s\n", raddr.PubKey) + } + c.SetConnection(conn) + ms.chatRepo.Update(*c) + + go ms.Handle(raddr.PubKey) + } +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go b/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go new file mode 100644 index 000000000..e67e7e71e --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go @@ -0,0 +1,36 @@ +package channel + +import ( + "encoding/json" + + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" +) + +// NotificationService provides a channel implementation of the Service +type NotificationService struct { + notifCh chan string +} + +// NewNotificationService constructor for NotificationService +func NewNotificationService() *NotificationService { + n := NotificationService{} + n.notifCh = make(chan string) + + return &n +} + +// Notify sends out the notifications to the channel +func (ns NotificationService) Notify(notification notification.Notification) error { + jsonNotification, err := json.Marshal(notification) + if err != nil { + return err + } + + ns.GetChannel() <- string(jsonNotification) + return nil +} + +// GetChannel returns the channel of the notification service +func (ns NotificationService) GetChannel() chan string { + return ns.notifCh +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/services.go b/cmd/apps/skychat/internal/interfaceadapters/services.go new file mode 100644 index 000000000..0705e1d40 --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/services.go @@ -0,0 +1,38 @@ +package interfaceadapters + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon" + channel "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/notification/http" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/storage/memory" +) + +//Services contains the exposed services of interface adapters +type Services struct { + ClientRepository client.ClientRepository + UserRepository user.UserRepository + ChatRepository chat.ChatRepository + MessengerService messenger.Service + NotificationService notification.Service +} + +//NewServices Instantiates the interface adapter services +func NewServices() Services { + cliRepo := memory.NewClientRepo() + cli, _ := cliRepo.GetClient() + usrRepo := memory.NewUserRepo(cli.GetAppClient().Config().VisorPK) + chtRepo := memory.NewChatRepo() //memory.NewDummyChatRepo(cli.GetAppClient().Config().VisorPK) + ns := channel.NewNotificationService() + + return Services{ + ClientRepository: cliRepo, + UserRepository: usrRepo, + ChatRepository: chtRepo, + MessengerService: netcon.NewMessengerService(ns, cliRepo, usrRepo, chtRepo), + NotificationService: ns, + } +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go new file mode 100644 index 000000000..23bf873b0 --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go @@ -0,0 +1,118 @@ +package memory + +import ( + "fmt" + "sync" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" +) + +//ChatRepo Implements the Repository Interface to provide an in-memory storage provider +type ChatRepo struct { + chats map[cipher.PubKey]chat.Chat + chatsMu sync.Mutex +} + +//NewRepo Constructor +func NewChatRepo() *ChatRepo { + cR := ChatRepo{} + cR.chats = make(map[cipher.PubKey]chat.Chat) + return &cR +} + +//GetByPK Returns the chat with the provided pk +func (r *ChatRepo) GetByPK(pk cipher.PubKey) (*chat.Chat, error) { + r.chatsMu.Lock() + defer r.chatsMu.Unlock() + + chat, ok := r.chats[pk] + if !ok { + return nil, fmt.Errorf("chat not found") + } + return &chat, nil +} + +//GetAll Returns all stored chats +func (r *ChatRepo) GetAll() ([]chat.Chat, error) { + r.chatsMu.Lock() + defer r.chatsMu.Unlock() + + keys := make([]cipher.PubKey, 0) + + for key := range r.chats { + keys = append(keys, key) + } + + var values []chat.Chat + for _, value := range r.chats { + values = append(values, value) + } + + return values, nil +} + +//Add the provided chat +func (r *ChatRepo) Add(chat chat.Chat) error { + r.chatsMu.Lock() + defer r.chatsMu.Unlock() + + r.chats[chat.GetPK()] = chat + return nil +} + +//Update the provided chat +func (r *ChatRepo) Update(chat chat.Chat) error { + r.chatsMu.Lock() + defer r.chatsMu.Unlock() + + r.chats[chat.GetPK()] = chat + return nil +} + +//Delete the chat with the provided pk +func (r *ChatRepo) Delete(pk cipher.PubKey) error { + r.chatsMu.Lock() + defer r.chatsMu.Unlock() + + _, exists := r.chats[pk] + if !exists { + return fmt.Errorf("id %v not found", pk.String()) + } + delete(r.chats, pk) + return nil +} + +func NewDummyChatRepo(pk cipher.PubKey) *ChatRepo { + cR := ChatRepo{} + + defaultpng := "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAIAAAAHjs1qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5OTMyNUUzOTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjY5OTMyNUU0OTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6Njk5MzI1RTE5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Njk5MzI1RTI5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7FIRCzAAAPn0lEQVR42uyd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" + + //Origin1 + pk1 := cipher.PubKey{} + pk1.Set("0200369389087217c9e9b5936c329c120c7ed1b29b404d708bc88634e4d6b4966b") + i1 := info.NewInfo(pk1, "Peer1", "Peer1 Description", defaultpng) + //TODO: make chat.NewChat() + //make dummy chats + PC1msg1 := message.NewTextMessage(pk1, []byte("Hello")) + PC1msg2 := message.NewTextMessage(pk, []byte("Hello Back")) + PC1 := chat.NewChat(pk1, chat.PeerChat, i1, []message.Message{PC1msg1, PC1msg2}) + + //Origin2 + pk2 := cipher.PubKey{} + pk2.Set("0200369389087217c9e9b5936c329c120c7ed1b29b404d708bc88634e4d6b4966a") + i2 := info.NewInfo(pk2, "Peer2", "Peer2 Description", defaultpng) + //TODO: make chat.NewChat() + //make dummy chats + PC2msg1 := message.NewTextMessage(pk2, []byte("Hello Peer2")) + PC2msg2 := message.NewTextMessage(pk, []byte("Hello Back Peer2")) + PC2 := chat.NewChat(pk2, chat.PeerChat, i2, []message.Message{PC2msg1, PC2msg2}) + + cR.chats = make(map[cipher.PubKey]chat.Chat) + cR.chats[pk1] = PC1 + cR.chats[pk2] = PC2 + + return &cR +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go new file mode 100644 index 000000000..e8120df2c --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go @@ -0,0 +1,55 @@ +package memory + +import ( + "fmt" + "sync" + + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" +) + +//ClientRepo Implements the Repository Interface to provide an in-memory storage provider +type ClientRepo struct { + client client.Client + cliMu sync.Mutex +} + +//NewRepo Constructor +func NewClientRepo() *ClientRepo { + cR := ClientRepo{} + + cR.client, _ = cR.New() + + return &cR +} + +//New fills repo with a new client, if none has been set +//also returns a client when a client has been set already +func (r *ClientRepo) New() (client.Client, error) { + if !r.client.IsEmtpy() { + return r.client, fmt.Errorf("client already defined") + } else { + r.SetClient(*client.NewClient()) + return r.client, nil + } +} + +//Get Returns the client +func (r *ClientRepo) GetClient() (*client.Client, error) { + r.cliMu.Lock() + defer r.cliMu.Unlock() + + if r.client.IsEmtpy() { + return nil, fmt.Errorf("client not found") + } else { + return &r.client, nil + } +} + +//Update the provided client +func (r *ClientRepo) SetClient(client client.Client) error { + r.cliMu.Lock() + defer r.cliMu.Unlock() + + r.client = client + return nil +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go new file mode 100644 index 000000000..5d0bd0bcf --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go @@ -0,0 +1,56 @@ +package memory + +import ( + "fmt" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" +) + +//UserRepo Implements the Repository Interface to provide an in-memory storage provider +type UserRepo struct { + user user.User +} + +//NewRepo Constructor +func NewUserRepo(pk cipher.PubKey) *UserRepo { + uR := UserRepo{} + + var err error + uR.user, err = uR.NewUser() + uR.user.GetInfo().SetPK(pk) + if err != nil { + fmt.Println(err) + } + + return &uR +} + +//New fills repo with a new user, if none has been set +//also returns a user when a user has been set already +func (r *UserRepo) NewUser() (user.User, error) { + if !r.user.IsEmpty() { + return r.user, fmt.Errorf("user already defined") + } else { + r.SetUser(user.NewDefaultUser()) + fmt.Printf("New DefaultUser at %p\n", &r.user) + return r.user, nil + } +} + +//Get Returns the user +func (r *UserRepo) GetUser() (*user.User, error) { + fmt.Printf("user-repo adress %p\n", r) + if r.user.IsEmpty() { + return nil, fmt.Errorf("user not found") + } else { + fmt.Printf("Get User at %p", &r.user) + return &r.user, nil + } +} + +//Update the provided user +func (r *UserRepo) SetUser(user *user.User) error { + r.user = *user + return nil +} diff --git a/cmd/apps/skychat/skychat.go b/cmd/apps/skychat/skychat.go index 190cac0a5..f9aea6951 100644 --- a/cmd/apps/skychat/skychat.go +++ b/cmd/apps/skychat/skychat.go @@ -1,277 +1,49 @@ -/* -skychat app for skywire visor -*/ package main import ( - "context" - "embed" - "encoding/json" "flag" - "fmt" - "io/fs" - "net" - "net/http" - "os" - "os/signal" - "runtime" - "sync" - "time" - - ipc "github.com/james-barrow/golang-ipc" - "github.com/skycoin/skywire-utilities/pkg/buildinfo" - "github.com/skycoin/skywire-utilities/pkg/cipher" - "github.com/skycoin/skywire-utilities/pkg/netutil" - "github.com/skycoin/skywire/pkg/app" - "github.com/skycoin/skywire/pkg/app/appnet" - "github.com/skycoin/skywire/pkg/app/appserver" - "github.com/skycoin/skywire/pkg/routing" - "github.com/skycoin/skywire/pkg/skyenv" -) - -const ( - netType = appnet.TypeSkynet - port = routing.Port(1) + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters" ) var addr = flag.String("addr", ":8001", "address to bind") -var r = netutil.NewRetrier(nil, 50*time.Millisecond, netutil.DefaultMaxBackoff, 5, 2) - -var ( - appCl *app.Client - clientCh chan string - conns map[cipher.PubKey]net.Conn // Chat connections - connsMu sync.Mutex -) - -// the go embed static points to skywire/cmd/apps/skychat/static - -//go:embed static -var embededFiles embed.FS func main() { - appCl = app.NewClient(nil) - defer appCl.Close() - - if _, err := buildinfo.Get().WriteTo(os.Stdout); err != nil { - print(fmt.Sprintf("Failed to output build info: %v\n", err)) - } flag.Parse() - fmt.Println("Successfully started skychat.") - - clientCh = make(chan string) - defer close(clientCh) - - conns = make(map[cipher.PubKey]net.Conn) - go listenLoop() - - if runtime.GOOS == "windows" { - ipcClient, err := ipc.StartClient(skyenv.SkychatName, nil) - if err != nil { - print(fmt.Sprintf("Error creating ipc server for skychat client: %v\n", err)) - setAppError(appCl, err) - os.Exit(1) - } - go handleIPCSignal(ipcClient) - } - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - http.Handle("/", http.FileServer(getFileSystem())) - http.HandleFunc("/message", messageHandler(ctx)) - http.HandleFunc("/sse", sseHandler) - - fmt.Println("Serving HTTP on", *addr) - if runtime.GOOS != "windows" { - termCh := make(chan os.Signal, 1) - signal.Notify(termCh, os.Interrupt) - - go func() { - <-termCh - setAppStatus(appCl, appserver.AppDetailedStatusStopped) - os.Exit(1) - }() - } - setAppStatus(appCl, appserver.AppDetailedStatusRunning) - - err := http.ListenAndServe(*addr, nil) - if err != nil { - print(err.Error()) - setAppError(appCl, err) - os.Exit(1) - } - -} - -func listenLoop() { - l, err := appCl.Listen(netType, port) - if err != nil { - print(fmt.Sprintf("Error listening network %v on port %d: %v\n", netType, port, err)) - setAppError(appCl, err) - return - } - - for { - fmt.Println("Accepting skychat conn...") - conn, err := l.Accept() - if err != nil { - print(fmt.Sprintf("Failed to accept conn: %v\n", err)) - return - } - fmt.Println("Accepted skychat conn") - raddr := conn.RemoteAddr().(appnet.Addr) - connsMu.Lock() - conns[raddr.PubKey] = conn - connsMu.Unlock() - fmt.Printf("Accepted skychat conn on %s from %s\n", conn.LocalAddr(), raddr.PubKey) + interfaceAdapterServices := interfaceadapters.NewServices() + appServices := app.NewServices(interfaceAdapterServices.ClientRepository, interfaceAdapterServices.UserRepository, interfaceAdapterServices.ChatRepository, interfaceAdapterServices.NotificationService, interfaceAdapterServices.MessengerService) + inputPortsServices := inputports.NewServices(appServices) - go handleConn(conn) - } -} + //appclient listen + go interfaceAdapterServices.MessengerService.Listen() -func handleConn(conn net.Conn) { - raddr := conn.RemoteAddr().(appnet.Addr) - for { - buf := make([]byte, 32*1024) - n, err := conn.Read(buf) - if err != nil { - fmt.Println("Failed to read packet:", err) - raddr := conn.RemoteAddr().(appnet.Addr) - connsMu.Lock() - delete(conns, raddr.PubKey) - connsMu.Unlock() - return - } + //http-server + inputPortsServices.Server.ListenAndServe(addr) - clientMsg, err := json.Marshal(map[string]string{"sender": raddr.PubKey.Hex(), "message": string(buf[:n])}) - if err != nil { - print(fmt.Sprintf("Failed to marshal json: %v\n", err)) - } - select { - case clientCh <- string(clientMsg): - fmt.Printf("Received and sent to ui: %s\n", clientMsg) - default: - fmt.Printf("Received and trashed: %s\n", clientMsg) - } - } } -func messageHandler(ctx context.Context) func(w http.ResponseWriter, rreq *http.Request) { - return func(w http.ResponseWriter, req *http.Request) { - - data := map[string]string{} - if err := json.NewDecoder(req.Body).Decode(&data); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - pk := cipher.PubKey{} - if err := pk.UnmarshalText([]byte(data["recipient"])); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - addr := appnet.Addr{ - Net: netType, - PubKey: pk, - Port: 1, - } - connsMu.Lock() - conn, ok := conns[pk] - connsMu.Unlock() - - if !ok { - var err error - err = r.Do(ctx, func() error { - conn, err = appCl.Dial(addr) - return err - }) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - connsMu.Lock() - conns[pk] = conn - connsMu.Unlock() - - go handleConn(conn) - } - - _, err := conn.Write([]byte(data["message"])) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - - connsMu.Lock() - delete(conns, pk) - connsMu.Unlock() - - return - } - } -} +//TEST: +// cd .. +// cd .. +// cd .. +// mingw32-make build-windows +// .\skywire-cli.exe config gen -i -r -o .\skywire-config.json +// .\skywire-visor.exe -c .\skywire-config.json -func sseHandler(w http.ResponseWriter, req *http.Request) { - f, ok := w.(http.Flusher) - if !ok { - http.Error(w, "Streaming unsupported!", http.StatusBadRequest) - return - } - - w.Header().Set("Content-Type", "text/event-stream") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - w.Header().Set("Transfer-Encoding", "chunked") - - for { - select { - case msg, ok := <-clientCh: - if !ok { - return - } - _, _ = fmt.Fprintf(w, "data: %s\n\n", msg) - f.Flush() - - case <-req.Context().Done(): - fmt.Print("SSE connection were closed.") - return - } - } -} +/* -func getFileSystem() http.FileSystem { - fsys, err := fs.Sub(embededFiles, "static") - if err != nil { - panic(err) - } - return http.FS(fsys) -} +Text message +{"Id":0,"Origin":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Time":"2022-07-02T00:06:33.0067605+02:00","Sender":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Msgtype":2,"MsgSubtype":0,"Message":"Hey Friend","Status":1,"Seen":false} -func handleIPCSignal(client *ipc.Client) { - for { - m, err := client.Read() - if err != nil { - fmt.Printf("%s IPC received error: %v", skyenv.SkychatName, err) - } - if m.MsgType == skyenv.IPCShutdownMessageType { - fmt.Println("Stopping " + skyenv.SkychatName + " via IPC") - break - } - } - os.Exit(0) -} +Accept message +{"Id":0,"Origin":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Time":"2022-07-02T00:06:33.0067605+02:00","Sender":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Msgtype":1,"MsgSubtype":2,"Message":"","Status":1,"Seen":false} -func setAppStatus(appCl *app.Client, status appserver.AppDetailedStatus) { - if err := appCl.SetDetailedStatus(string(status)); err != nil { - print(fmt.Sprintf("Failed to set status %v: %v\n", status, err)) - } -} +Request message +{"Id":0,"Origin":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Time":"2022-07-02T00:06:33.0067605+02:00","Sender":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Msgtype":1,"MsgSubtype":1,"Message":"","Status":1,"Seen":false} -func setAppError(appCl *app.Client, appErr error) { - if err := appCl.SetError(appErr.Error()); err != nil { - print(fmt.Sprintf("Failed to set error %v: %v\n", appErr, err)) - } -} +{"Id":0,"Origin":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Time":"2022-07-02T14:01:02.3116213+02:00","Sender":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Msgtype":3,"MsgSubtype":0,"Message":"{\"Pk\":\"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22\",\"Alias\":\"Meister\",\"Desc\":\"Unknown\",\"Img\":\""}","Status":1,"Seen":false} +*/ diff --git a/cmd/apps/skychat/static/index.html b/cmd/apps/skychat/static/index.html deleted file mode 100644 index df658eae0..000000000 --- a/cmd/apps/skychat/static/index.html +++ /dev/null @@ -1,745 +0,0 @@ - - - - - - - - - - - - - -
      - -
        - - -
        - - - - - - - \ No newline at end of file From 203bbc71943c0de51e390bcbc55a9cec6883c505 Mon Sep 17 00:00:00 2001 From: Moses Narrow Date: Fri, 5 Aug 2022 14:52:54 -0500 Subject: [PATCH 02/72] fix some make check errors --- .../internal/app/chat/commands/add_chat.go | 8 +++---- .../internal/app/chat/commands/delete_chat.go | 6 +++--- .../app/chat/commands/send_text_message.go | 4 ++-- .../app/chat/queries/get_all_chats.go | 4 ++-- .../queries/get_all_messages_from_chat.go | 8 +++---- .../app/chat/queries/get_chat_by_pk.go | 6 +++--- .../skychat/internal/app/chat/services.go | 2 +- .../internal/app/notification/notification.go | 3 +++ cmd/apps/skychat/internal/app/services.go | 2 +- .../internal/app/user/commands/set_info.go | 10 +++++---- .../app/user/commands/set_settings.go | 6 +++--- .../internal/app/user/queries/get_info.go | 4 ++-- .../internal/app/user/queries/get_settings.go | 4 ++-- .../skychat/internal/app/user/services.go | 2 +- cmd/apps/skychat/internal/domain/chat/chat.go | 18 +++++++++++++--- .../internal/domain/chat/chat_repository.go | 3 ++- .../skychat/internal/domain/client/client.go | 14 +++++++++++-- .../domain/client/client_repository.go | 3 ++- cmd/apps/skychat/internal/domain/info/info.go | 2 +- .../internal/domain/message/message.go | 21 ++++++++++++++++++- cmd/apps/skychat/internal/domain/peer/peer.go | 1 + .../skychat/internal/domain/server/server.go | 15 ++++++------- .../internal/domain/settings/settings.go | 11 ++++++---- cmd/apps/skychat/internal/domain/user/user.go | 14 +++++++------ .../internal/domain/user/user_repository.go | 3 ++- .../internal/inputports/http/chat/handler.go | 6 +++--- .../messenger/netcon/messenger_service.go | 10 ++++----- .../internal/interfaceadapters/services.go | 8 +++---- .../storage/memory/chat_repo.go | 4 ++-- .../storage/memory/client_repo.go | 2 +- go.mod | 1 + go.sum | 2 ++ vendor/modules.txt | 3 +++ 33 files changed, 136 insertions(+), 74 deletions(-) diff --git a/cmd/apps/skychat/internal/app/chat/commands/add_chat.go b/cmd/apps/skychat/internal/app/chat/commands/add_chat.go index a99d93605..51ebe52e5 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/add_chat.go +++ b/cmd/apps/skychat/internal/app/chat/commands/add_chat.go @@ -8,23 +8,23 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" ) -//AddChatModel of AddChatRequestHandler +//AddChatRequest of AddChatRequestHandler type AddChatRequest struct { Pk cipher.PubKey } -//AddNewChatRequestHandler struct that allows handling AddChatRequest +//AddChatRequestHandler struct that allows handling AddChatRequest type AddChatRequestHandler interface { Handle(command AddChatRequest) error } type addChatRequestHandler struct { messengerService messenger.Service - chatRepo chat.ChatRepository + chatRepo chat.Repository } //NewAddChatRequestHandler Initializes an AddCommandHandler -func NewAddChatRequestHandler(chatRepo chat.ChatRepository, messengerService messenger.Service) AddChatRequestHandler { +func NewAddChatRequestHandler(chatRepo chat.Repository, messengerService messenger.Service) AddChatRequestHandler { return addChatRequestHandler{chatRepo: chatRepo, messengerService: messengerService} } diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_chat.go b/cmd/apps/skychat/internal/app/chat/commands/delete_chat.go index cd1b23141..36b66d60b 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/delete_chat.go +++ b/cmd/apps/skychat/internal/app/chat/commands/delete_chat.go @@ -19,12 +19,12 @@ type DeleteChatRequestHandler interface { } type deleteChatRequestHandler struct { - cliRepo client.ClientRepository - chatRepo chat.ChatRepository + cliRepo client.Repository + chatRepo chat.Repository } //NewDeleteChatRequestHandler Handler constructor -func NewDeleteChatRequestHandler(cliRepo client.ClientRepository, chatRepo chat.ChatRepository) DeleteChatRequestHandler { +func NewDeleteChatRequestHandler(cliRepo client.Repository, chatRepo chat.Repository) DeleteChatRequestHandler { return deleteChatRequestHandler{cliRepo: cliRepo, chatRepo: chatRepo} } diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go index c825d77c3..8b13ed210 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go +++ b/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go @@ -5,7 +5,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" ) -//SendTextMessageModel of SendTextMessageRequestHandler +//SendTextMessageRequest of SendTextMessageRequestHandler type SendTextMessageRequest struct { Pk cipher.PubKey Msg []byte @@ -20,7 +20,7 @@ type sendTextMessageRequestHandler struct { messengerService messenger.Service } -//NewAddChatRequestHandler Initializes an AddCommandHandler +//NewSendTextMessageRequestHandler Initializes an AddCommandHandler func NewSendTextMessageRequestHandler(messengerService messenger.Service) SendTextMessageRequestHandler { return sendTextMessageRequestHandler{messengerService: messengerService} } diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go b/cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go index 2a1195417..30c94c32b 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go @@ -23,11 +23,11 @@ type GetAllChatsRequestHandler interface { } type getAllChatsRequestHandler struct { - repo chat.ChatRepository + repo chat.Repository } //NewGetAllChatsRequestHandler Handler constructor -func NewGetAllChatsRequestHandler(repo chat.ChatRepository) GetAllChatsRequestHandler { +func NewGetAllChatsRequestHandler(repo chat.Repository) GetAllChatsRequestHandler { return getAllChatsRequestHandler{repo: repo} } diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go b/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go index 460f9c5c9..dd5520314 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go @@ -6,7 +6,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" ) -//GetAllMessagesFromChat Model of the Handler +//GetAllMessagesFromChatRequest Model of the Handler type GetAllMessagesFromChatRequest struct { pk cipher.PubKey } @@ -16,17 +16,17 @@ type GetAllMessagesFromChatResult struct { messages []message.Message } -//type GetAllMessagesFromChatRequestHandler provides an interfaces to handle a GetAllMessagesFromChatRequest and return a *GetAllMessagesFromChatResult +//GetAllMessagesFromChatRequestHandler provides an interfaces to handle a GetAllMessagesFromChatRequest and return a *GetAllMessagesFromChatResult type GetAllMessagesFromChatRequestHandler interface { Handle(query GetAllMessagesFromChatRequest) (GetAllMessagesFromChatResult, error) } type getAllMessagesFromChatRequestHandler struct { - repo chat.ChatRepository + repo chat.Repository } //NewGetAllMessagesFromChatRequestHandler Handler Constructor -func NewGetAllMessagesFromChatRequestHandler(repo chat.ChatRepository) GetAllMessagesFromChatRequestHandler { +func NewGetAllMessagesFromChatRequestHandler(repo chat.Repository) GetAllMessagesFromChatRequestHandler { return getAllMessagesFromChatRequestHandler{repo: repo} } diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go b/cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go index 6b74d9026..a522f8b64 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go @@ -10,7 +10,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" ) -//GetChatByPK Model of the Handler +//GetChatByPKRequest Model of the Handler type GetChatByPKRequest struct { Pk cipher.PubKey } @@ -31,11 +31,11 @@ type GetChatByPKRequestHandler interface { } type getChatByPKRequestHandler struct { - repo chat.ChatRepository + repo chat.Repository } //NewGetChatByPKRequestHandler Handler constructor -func NewGetChatByPKRequestHandler(repo chat.ChatRepository) GetChatByPKRequestHandler { +func NewGetChatByPKRequestHandler(repo chat.Repository) GetChatByPKRequestHandler { return getChatByPKRequestHandler{repo: repo} } diff --git a/cmd/apps/skychat/internal/app/chat/services.go b/cmd/apps/skychat/internal/app/chat/services.go index 69ad4e701..fa48cebc3 100644 --- a/cmd/apps/skychat/internal/app/chat/services.go +++ b/cmd/apps/skychat/internal/app/chat/services.go @@ -29,7 +29,7 @@ type ChatServices struct { } // NewServices Bootstraps Application Layer dependencies -func NewServices(cliRepo client.ClientRepository, chatRepo chat.ChatRepository, ms messenger.Service) ChatServices { +func NewServices(cliRepo client.Repository, chatRepo chat.Repository, ms messenger.Service) ChatServices { return ChatServices{ Queries: Queries{ GetAllChatsHandler: queries.NewGetAllChatsRequestHandler(chatRepo), diff --git a/cmd/apps/skychat/internal/app/notification/notification.go b/cmd/apps/skychat/internal/app/notification/notification.go index d293f80ee..851c982a9 100644 --- a/cmd/apps/skychat/internal/app/notification/notification.go +++ b/cmd/apps/skychat/internal/app/notification/notification.go @@ -24,6 +24,7 @@ type Notification struct { Message string `json:"message"` } +// NewMsgNotification notifies the user of a new message func NewMsgNotification(pk cipher.PubKey, msg message.Message) Notification { Msg, err := json.Marshal(message.NewJSONMessage(msg)) if err != nil { @@ -40,6 +41,7 @@ func NewMsgNotification(pk cipher.PubKey, msg message.Message) Notification { } } +// NewAddChatNotification notifies the user about add chat request func NewAddChatNotification(pk cipher.PubKey) Notification { clientMsg, err := json.Marshal(map[string]string{"pk": pk.Hex()}) if err != nil { @@ -51,6 +53,7 @@ func NewAddChatNotification(pk cipher.PubKey) Notification { } } +// NewChatNotification notifies the user about new chat func NewChatNotification(pk cipher.PubKey) Notification { clientMsg, err := json.Marshal(map[string]string{"pk": pk.Hex()}) if err != nil { diff --git a/cmd/apps/skychat/internal/app/services.go b/cmd/apps/skychat/internal/app/services.go index 3106c2cf3..a05c1132a 100644 --- a/cmd/apps/skychat/internal/app/services.go +++ b/cmd/apps/skychat/internal/app/services.go @@ -18,7 +18,7 @@ type Services struct { } // NewServices Bootstraps Application Layer dependencies -func NewServices(cliRepo client.ClientRepository, usrRepo user.UserRepository, chatRepo chat.ChatRepository, notifService notification.Service, ms messenger.Service) Services { +func NewServices(cliRepo client.Repository, usrRepo user.Repository, chatRepo chat.Repository, notifService notification.Service, ms messenger.Service) Services { return Services{ NotificationService: notifService, ChatServices: chatservices.NewServices(cliRepo, chatRepo, ms), diff --git a/cmd/apps/skychat/internal/app/user/commands/set_info.go b/cmd/apps/skychat/internal/app/user/commands/set_info.go index 5027fb085..52703103c 100644 --- a/cmd/apps/skychat/internal/app/user/commands/set_info.go +++ b/cmd/apps/skychat/internal/app/user/commands/set_info.go @@ -1,11 +1,13 @@ package commands import ( + "errors" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) -//SetInfoModel of SetInfoRequestHandler +//SetInfoRequest of SetInfoRequestHandler type SetInfoRequest struct { Alias string Desc string @@ -18,11 +20,11 @@ type SetInfoRequestHandler interface { } type setInfoRequestHandler struct { - usrRepo user.UserRepository + usrRepo user.Repository } //NewSetInfoRequestHandler Initializes an SetInfoHandler -func NewSetInfoRequestHandler(usrRepo user.UserRepository) SetInfoRequestHandler { +func NewSetInfoRequestHandler(usrRepo user.Repository) SetInfoRequestHandler { return setInfoRequestHandler{usrRepo: usrRepo} } @@ -31,7 +33,7 @@ func (h setInfoRequestHandler) Handle(req SetInfoRequest) error { pUsr, err := h.usrRepo.GetUser() if err != nil { - //TODO: implement error + return errors.New("failed to get user") } i := info.NewInfo(pUsr.GetInfo().GetPK(), req.Alias, req.Desc, req.Img) diff --git a/cmd/apps/skychat/internal/app/user/commands/set_settings.go b/cmd/apps/skychat/internal/app/user/commands/set_settings.go index 9270215f3..e055d0b78 100644 --- a/cmd/apps/skychat/internal/app/user/commands/set_settings.go +++ b/cmd/apps/skychat/internal/app/user/commands/set_settings.go @@ -6,7 +6,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) -//SetSettingsRequestModel of SetSettingsRequestHandler +//SetSettingsRequest of SetSettingsRequestHandler type SetSettingsRequest struct { Blacklist []cipher.PubKey } @@ -17,11 +17,11 @@ type SetSettingsRequestHandler interface { } type setSettingsRequestHandler struct { - usrRepo user.UserRepository + usrRepo user.Repository } //NewSetSettingsRequestHandler Initializes an SetSettingsRequestHandler -func NewSetSettingsRequestHandler(usrRepo user.UserRepository) SetSettingsRequestHandler { +func NewSetSettingsRequestHandler(usrRepo user.Repository) SetSettingsRequestHandler { return setSettingsRequestHandler{usrRepo: usrRepo} } diff --git a/cmd/apps/skychat/internal/app/user/queries/get_info.go b/cmd/apps/skychat/internal/app/user/queries/get_info.go index 60fb0855b..ace76c5fe 100644 --- a/cmd/apps/skychat/internal/app/user/queries/get_info.go +++ b/cmd/apps/skychat/internal/app/user/queries/get_info.go @@ -18,11 +18,11 @@ type GetUserInfoRequestHandler interface { } type getUserInfoRequestHandler struct { - usrRepo user.UserRepository + usrRepo user.Repository } //NewGetUserInfoRequestHandler Handler constructor -func NewGetUserInfoRequestHandler(usrRepo user.UserRepository) GetUserInfoRequestHandler { +func NewGetUserInfoRequestHandler(usrRepo user.Repository) GetUserInfoRequestHandler { return getUserInfoRequestHandler{usrRepo: usrRepo} } diff --git a/cmd/apps/skychat/internal/app/user/queries/get_settings.go b/cmd/apps/skychat/internal/app/user/queries/get_settings.go index 5d642ffde..8ea80edaa 100644 --- a/cmd/apps/skychat/internal/app/user/queries/get_settings.go +++ b/cmd/apps/skychat/internal/app/user/queries/get_settings.go @@ -15,11 +15,11 @@ type GetUserSettingsRequestHandler interface { } type getUserSettingsRequestHandler struct { - usrRepo user.UserRepository + usrRepo user.Repository } //NewGetUserSettingsRequestHandler Handler constructor -func NewGetUserSettingsRequestHandler(usrRepo user.UserRepository) GetUserSettingsRequestHandler { +func NewGetUserSettingsRequestHandler(usrRepo user.Repository) GetUserSettingsRequestHandler { return getUserSettingsRequestHandler{usrRepo: usrRepo} } diff --git a/cmd/apps/skychat/internal/app/user/services.go b/cmd/apps/skychat/internal/app/user/services.go index 33415a4d6..764abdc0d 100644 --- a/cmd/apps/skychat/internal/app/user/services.go +++ b/cmd/apps/skychat/internal/app/user/services.go @@ -26,7 +26,7 @@ type UserServices struct { } // NewServices Bootstraps Application Layer dependencies -func NewServices(cliRepo user.UserRepository, chatRepo chat.ChatRepository) UserServices { +func NewServices(cliRepo user.Repository, chatRepo chat.Repository) UserServices { return UserServices{ Queries: Queries{ GetUserInfoHandler: queries.NewGetUserInfoRequestHandler(cliRepo), diff --git a/cmd/apps/skychat/internal/domain/chat/chat.go b/cmd/apps/skychat/internal/domain/chat/chat.go index cbefb0710..24492eb67 100644 --- a/cmd/apps/skychat/internal/domain/chat/chat.go +++ b/cmd/apps/skychat/internal/domain/chat/chat.go @@ -11,10 +11,13 @@ import ( const ( errChatType = iota + // GroupChat is a group chat GroupChat + // PeerChat is a direct message PeerChat ) +// Chat is the struct of the chat itself type Chat struct { PK cipher.PubKey CType int @@ -26,48 +29,56 @@ type Chat struct { peers []peer.Peer } -// Getter +// GetPK gets the public key func (c *Chat) GetPK() cipher.PubKey { return c.PK } +// GetType gets the chat type func (c *Chat) GetType() int { return c.CType } +// GetConnection returns net.Conn func (c *Chat) GetConnection() net.Conn { return c.Conn } +// GetInfo returns info.Info func (c *Chat) GetInfo() info.Info { return c.Info } +// GetMessages returns []message.Message func (c *Chat) GetMessages() []message.Message { return c.Msgs } +// GetPeers returns []peer.Peer func (c *Chat) GetPeers() []peer.Peer { return c.peers } //Setter +// SetConnection sets the connection type used func (c *Chat) SetConnection(Conn net.Conn) { c.Conn = Conn } +// DeleteConnection clears the connection func (c *Chat) DeleteConnection() { c.Conn = nil } -//Add the given message to the given chat +// AddMessage Add the given message to the given chat func (c *Chat) AddMessage(m message.Message) { c.Msgs = append(c.Msgs, m) } -//Constructors +// Constructors +// NewUndefinedChat creates undefined empty chat to a public key func NewUndefinedChat(PK cipher.PubKey) Chat { c := Chat{} c.PK = PK @@ -78,6 +89,7 @@ func NewUndefinedChat(PK cipher.PubKey) Chat { return c } +// NewChat creates a new chat func NewChat(PK cipher.PubKey, CType int, i info.Info, Msgs []message.Message) Chat { c := Chat{} c.PK = PK diff --git a/cmd/apps/skychat/internal/domain/chat/chat_repository.go b/cmd/apps/skychat/internal/domain/chat/chat_repository.go index 43c611a55..b4fcb3726 100644 --- a/cmd/apps/skychat/internal/domain/chat/chat_repository.go +++ b/cmd/apps/skychat/internal/domain/chat/chat_repository.go @@ -4,7 +4,8 @@ import ( "github.com/skycoin/skywire-utilities/pkg/cipher" ) -type ChatRepository interface { +// Repository is the interface to the chat repository +type Repository interface { GetByPK(pk cipher.PubKey) (*Chat, error) GetAll() ([]Chat, error) Add(c Chat) error diff --git a/cmd/apps/skychat/internal/domain/client/client.go b/cmd/apps/skychat/internal/domain/client/client.go index cc6987021..26d070317 100644 --- a/cmd/apps/skychat/internal/domain/client/client.go +++ b/cmd/apps/skychat/internal/domain/client/client.go @@ -17,6 +17,7 @@ import ( "github.com/skycoin/skywire/pkg/skyenv" ) +// Client defines a chat client type Client struct { appCl *app.Client // Skywire app client ipcCl *ipc.Client // IPC client @@ -26,28 +27,34 @@ type Client struct { clientCh chan string // client channel } -//Getter +// Getter +// GetAppClient returns *app.Client func (c *Client) GetAppClient() *app.Client { return c.appCl } +// GetNetType returns appnet.Type func (c *Client) GetNetType() appnet.Type { return c.netType } +// GetPort returns routing.Port func (c *Client) GetPort() routing.Port { return c.port } + +// GetLog returns *logging.Logger func (c *Client) GetLog() *logging.Logger { return c.log } +// GetChannel returns chan string func (c *Client) GetChannel() chan string { return c.clientCh } -// +// NewClient retrns *Client func NewClient() *Client { c := Client{} c.appCl = app.NewClient(nil) @@ -93,10 +100,12 @@ func NewClient() *Client { return &c } +// IsEmtpy checks if the cient is empty func (c *Client) IsEmtpy() bool { return *c == Client{} } +// SetAppStatus sets appserver.AppDetailedStatus func (c *Client) SetAppStatus(status appserver.AppDetailedStatus) { err := c.appCl.SetDetailedStatus(string(status)) if err != nil { @@ -104,6 +113,7 @@ func (c *Client) SetAppStatus(status appserver.AppDetailedStatus) { } } +// SetAppError sets the appErr.Error func (c *Client) SetAppError(appErr error) { err := c.appCl.SetError(appErr.Error()) if err != nil { diff --git a/cmd/apps/skychat/internal/domain/client/client_repository.go b/cmd/apps/skychat/internal/domain/client/client_repository.go index 3d7c89e15..56633f039 100644 --- a/cmd/apps/skychat/internal/domain/client/client_repository.go +++ b/cmd/apps/skychat/internal/domain/client/client_repository.go @@ -1,6 +1,7 @@ package client -type ClientRepository interface { +// Repository defines the interface to the client repository +type Repository interface { New() (Client, error) GetClient() (*Client, error) SetClient(c Client) error diff --git a/cmd/apps/skychat/internal/domain/info/info.go b/cmd/apps/skychat/internal/domain/info/info.go index 56cd9bc66..689991fdb 100644 --- a/cmd/apps/skychat/internal/domain/info/info.go +++ b/cmd/apps/skychat/internal/domain/info/info.go @@ -27,7 +27,7 @@ func (i Info) GetDescription() string { return i.Desc } -// GetDescription returns the Img string +// GetImg returns the Img string func (i Info) GetImg() string { return i.Img } diff --git a/cmd/apps/skychat/internal/domain/message/message.go b/cmd/apps/skychat/internal/domain/message/message.go index efc5edce3..1c9df04b8 100644 --- a/cmd/apps/skychat/internal/domain/message/message.go +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -31,6 +31,7 @@ const ( MsgStatusReceived ) +// Message defines a message type Message struct { ID int64 //an identifier for p2p chats and groups, Id is set by the receiver/server Origin cipher.PubKey //the originator of the Message @@ -43,6 +44,7 @@ type Message struct { Seen bool //flag to save whether the Message was read or not by the receiver (only for local notifications) -> online feedback will be implemented in future versions } +// JSONMessage defines a json message type JSONMessage struct { ID int64 `json:"Id"` Origin cipher.PubKey `json:"Origin"` @@ -55,6 +57,7 @@ type JSONMessage struct { Seen bool `json:"Seen"` } +// NewJSONMessage return a JSONMessage from a message func NewJSONMessage(m Message) JSONMessage { return JSONMessage{ m.ID, @@ -69,6 +72,7 @@ func NewJSONMessage(m Message) JSONMessage { } } +// NewMessage returns a message from a JSONMessage func NewMessage(m JSONMessage) Message { return Message{ m.ID, @@ -83,10 +87,12 @@ func NewMessage(m JSONMessage) Message { } } +// MarshalJSON returns marshaled json message and error func (m Message) MarshalJSON() ([]byte, error) { return json.Marshal(NewJSONMessage(m)) } +// NewTextMessage returns a Message func NewTextMessage(pk cipher.PubKey, msg []byte) Message { m := Message{} m.Origin = pk @@ -99,6 +105,7 @@ func NewTextMessage(pk cipher.PubKey, msg []byte) Message { return m } +// NewChatRequestMessage returns a request Message func NewChatRequestMessage(pk cipher.PubKey) Message { m := Message{} m.Origin = pk @@ -110,6 +117,7 @@ func NewChatRequestMessage(pk cipher.PubKey) Message { return m } +// NewChatAcceptMessage returns a chat accepted message func NewChatAcceptMessage(pk cipher.PubKey) Message { m := Message{} m.Origin = pk @@ -121,6 +129,7 @@ func NewChatAcceptMessage(pk cipher.PubKey) Message { return m } +// NewChatRejectMessage returns new chat rejected message func NewChatRejectMessage(pk cipher.PubKey) Message { m := Message{} m.Origin = pk @@ -132,6 +141,7 @@ func NewChatRejectMessage(pk cipher.PubKey) Message { return m } +// NewChatInfoMessage returns new chat info func NewChatInfoMessage(pk cipher.PubKey, info []byte) Message { m := Message{} m.Origin = pk @@ -143,38 +153,47 @@ func NewChatInfoMessage(pk cipher.PubKey, info []byte) Message { return m } -func (m *Message) GetId() int64 { +// GetID returns message ID +func (m *Message) GetID() int64 { return m.ID } +// GetOrigin returns origin public key func (m *Message) GetOrigin() cipher.PubKey { return m.Origin } +// GetTime returns time.Time of the message func (m *Message) GetTime() time.Time { return m.Time } +// GetSender returns the sender public key func (m *Message) GetSender() cipher.PubKey { return m.Sender } +// GetMessageType returns the message type integer func (m *Message) GetMessageType() int { return m.Msgtype } +// GetMessage returns the message in bytes func (m *Message) GetMessage() []byte { return m.Message } +// GetStatus returns the message status int func (m *Message) GetStatus() int { return m.Status } +// GetSeen returns the read status of the message func (m *Message) GetSeen() bool { return m.Seen } +// SetStatus sets the message status func (m *Message) SetStatus(status int) { m.Status = status } diff --git a/cmd/apps/skychat/internal/domain/peer/peer.go b/cmd/apps/skychat/internal/domain/peer/peer.go index e9e3802ff..608efc509 100644 --- a/cmd/apps/skychat/internal/domain/peer/peer.go +++ b/cmd/apps/skychat/internal/domain/peer/peer.go @@ -4,6 +4,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" ) +// Peer contains information about a peer type Peer struct { Info info.Info //TODO: make peerRepository so the user can give each Peer a Custom Alias diff --git a/cmd/apps/skychat/internal/domain/server/server.go b/cmd/apps/skychat/internal/domain/server/server.go index 74cac3c4d..da750d768 100644 --- a/cmd/apps/skychat/internal/domain/server/server.go +++ b/cmd/apps/skychat/internal/domain/server/server.go @@ -10,12 +10,13 @@ import ( "github.com/skycoin/skywire/pkg/app" ) +// Server defies the chat server type Server struct { - appCl *app.Client // Skywire app client - clientCh chan string // - conns map[cipher.PubKey]peer.Peer // peer connections - info info.Info // the public info of the server - msgs []message.Message // all messages send/received - blacklist []cipher.PubKey // Blacklist to block inocming connections - connsMu sync.Mutex // + appCl *app.Client // Skywire app client //nolint + clientCh chan string //nolint + conns map[cipher.PubKey]peer.Peer // peer connections //nolint + info info.Info // the public info of the server //nolint + msgs []message.Message // all messages send/received //nolint + blacklist []cipher.PubKey // Blacklist to block inocming connections //nolint + connsMu sync.Mutex //nolint } diff --git a/cmd/apps/skychat/internal/domain/settings/settings.go b/cmd/apps/skychat/internal/domain/settings/settings.go index 47064cdfe..e2ec134b6 100644 --- a/cmd/apps/skychat/internal/domain/settings/settings.go +++ b/cmd/apps/skychat/internal/domain/settings/settings.go @@ -4,21 +4,22 @@ import ( "github.com/skycoin/skywire-utilities/pkg/cipher" ) +// Settings defines chat setting type Settings struct { blacklist []cipher.PubKey // Blacklist to block inocming connections } -//Getter +// GetBlacklist returns the blacklist func (s Settings) GetBlacklist() []cipher.PubKey { return s.blacklist } -//Setter +// SetBlacklist sets the blacklist func (s *Settings) SetBlacklist(bl []cipher.PubKey) { s.blacklist = bl } -//Methods +// InBlacklist checks blacklist for a public key func (s Settings) InBlacklist(pk cipher.PubKey) bool { for _, b := range s.blacklist { if b == pk { @@ -28,19 +29,21 @@ func (s Settings) InBlacklist(pk cipher.PubKey) bool { return false } -//Constructor for default settings +// NewDefaultSettings Constructor for default settings func NewDefaultSettings() Settings { s := Settings{} s.blacklist = []cipher.PubKey{} return s } +// NewSettings blacklists a public key func NewSettings(blacklist []cipher.PubKey) Settings { s := Settings{} s.blacklist = blacklist return s } +// IsEmpty checks if the blacklist is empty func (s *Settings) IsEmpty() bool { return len(s.blacklist) <= 0 } diff --git a/cmd/apps/skychat/internal/domain/user/user.go b/cmd/apps/skychat/internal/domain/user/user.go index df9e8a02d..3424736c9 100644 --- a/cmd/apps/skychat/internal/domain/user/user.go +++ b/cmd/apps/skychat/internal/domain/user/user.go @@ -7,30 +7,33 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/settings" ) +// User defines the user type User struct { info info.Info // the info of the local user settings settings.Settings // the settings of the local user } -//Getter +//GetInfo gets the user info func (u *User) GetInfo() *info.Info { return &u.info } +// GetSettings returns *settings.Settings func (u *User) GetSettings() *settings.Settings { return &u.settings } -//Setter +//SetInfo sets the chat info func (u *User) SetInfo(i info.Info) { u.info = i } +// SetSettings applies settings func (u *User) SetSettings(s settings.Settings) { u.settings = s } -// +//NewDefaultUser returns *User func NewDefaultUser() *User { fmt.Println("user - NewDefaultUser") u := User{} @@ -42,11 +45,10 @@ func NewDefaultUser() *User { return &u } +// IsEmpty checks if the user is empty func (u *User) IsEmpty() bool { - if u.info.IsEmpty() && u.settings.IsEmpty() { return true - } else { - return false } + return false } diff --git a/cmd/apps/skychat/internal/domain/user/user_repository.go b/cmd/apps/skychat/internal/domain/user/user_repository.go index 40aef9793..e36906150 100644 --- a/cmd/apps/skychat/internal/domain/user/user_repository.go +++ b/cmd/apps/skychat/internal/domain/user/user_repository.go @@ -1,6 +1,7 @@ package user -type UserRepository interface { +// Repository is the interface to the user repository +type Repository interface { NewUser() (User, error) GetUser() (*User, error) SetUser(u *User) error diff --git a/cmd/apps/skychat/internal/inputports/http/chat/handler.go b/cmd/apps/skychat/internal/inputports/http/chat/handler.go index 1fe55d760..1b068f0cf 100644 --- a/cmd/apps/skychat/internal/inputports/http/chat/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/chat/handler.go @@ -19,7 +19,7 @@ type Handler struct { chatServices chatservices.ChatServices } -//NewHandler Constructor +// NewHandler Constructor returns *Handler func NewHandler(cs chatservices.ChatServices) *Handler { return &Handler{chatServices: cs} } @@ -81,7 +81,7 @@ type AddChatRequestModel struct { Pk string `json:"pk"` } -//AddChat adds the provided pk +//Add adds the provided pk func (c Handler) Add(w http.ResponseWriter, r *http.Request) { //fmt.Println(formatRequest(r)) var chatToAdd AddChatRequestModel @@ -191,7 +191,7 @@ func formatRequest(r *http.Request) string { } // If this is a POST, add post data if r.Method == "POST" { - r.ParseForm() + r.ParseForm() //nolint request = append(request, "\n") request = append(request, r.Form.Encode()) } // Return the request as a string diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index 542530844..85afecd4e 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -22,13 +22,13 @@ import ( type MessengerService struct { ctx context.Context ns notification.Service - cliRepo client.ClientRepository - usrRepo user.UserRepository - chatRepo chat.ChatRepository + cliRepo client.Repository + usrRepo user.Repository + chatRepo chat.Repository } // NewMessengerService constructor for MessengerService -func NewMessengerService(ns notification.Service, cR client.ClientRepository, uR user.UserRepository, chR chat.ChatRepository) *MessengerService { +func NewMessengerService(ns notification.Service, cR client.Repository, uR user.Repository, chR chat.Repository) *MessengerService { ms := MessengerService{} /*ctx, cancel := context.WithCancel(context.Background()) @@ -50,7 +50,7 @@ func (ms MessengerService) Handle(pk cipher.PubKey) error { c, err := ms.chatRepo.GetByPK(pk) if err != nil { ch := chat.NewUndefinedChat(pk) - ms.chatRepo.Add(ch) + ms.chatRepo.Add(ch) //nolint:errcheck c = &ch fmt.Printf("New skychat added: %s\n", pk) } diff --git a/cmd/apps/skychat/internal/interfaceadapters/services.go b/cmd/apps/skychat/internal/interfaceadapters/services.go index 0705e1d40..10c07888f 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/services.go +++ b/cmd/apps/skychat/internal/interfaceadapters/services.go @@ -13,9 +13,9 @@ import ( //Services contains the exposed services of interface adapters type Services struct { - ClientRepository client.ClientRepository - UserRepository user.UserRepository - ChatRepository chat.ChatRepository + ClientRepository client.Repository + UserRepository user.Repository + ChatRepository chat.Repository MessengerService messenger.Service NotificationService notification.Service } @@ -23,7 +23,7 @@ type Services struct { //NewServices Instantiates the interface adapter services func NewServices() Services { cliRepo := memory.NewClientRepo() - cli, _ := cliRepo.GetClient() + cli, _ := cliRepo.GetClient() //nolint usrRepo := memory.NewUserRepo(cli.GetAppClient().Config().VisorPK) chtRepo := memory.NewChatRepo() //memory.NewDummyChatRepo(cli.GetAppClient().Config().VisorPK) ns := channel.NewNotificationService() diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go index 23bf873b0..776e5938a 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go @@ -6,8 +6,6 @@ import ( "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" ) //ChatRepo Implements the Repository Interface to provide an in-memory storage provider @@ -85,6 +83,7 @@ func (r *ChatRepo) Delete(pk cipher.PubKey) error { return nil } +/* func NewDummyChatRepo(pk cipher.PubKey) *ChatRepo { cR := ChatRepo{} @@ -116,3 +115,4 @@ func NewDummyChatRepo(pk cipher.PubKey) *ChatRepo { return &cR } +*/ diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go index e8120df2c..86ee714ce 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go @@ -17,7 +17,7 @@ type ClientRepo struct { func NewClientRepo() *ClientRepo { cR := ClientRepo{} - cR.client, _ = cR.New() + cR.client, _ = cR.New() //nolint return &cR } diff --git a/go.mod b/go.mod index 2611c899d..ea8ae58a1 100644 --- a/go.mod +++ b/go.mod @@ -45,6 +45,7 @@ require ( github.com/bitfield/script v0.19.0 github.com/blang/semver/v4 v4.0.0 github.com/go-chi/chi/v5 v5.0.8-0.20220103230436-7dbe9a0bd10f + github.com/gorilla/mux v1.8.0 github.com/ivanpirog/coloredcobra v1.0.0 github.com/james-barrow/golang-ipc v0.0.0-20210227130457-95e7cc81f5e2 github.com/skycoin/skywire-utilities v0.0.0-20220712142443-abafa30105ce diff --git a/go.sum b/go.sum index 9a25709f0..c5fa23909 100644 --- a/go.sum +++ b/go.sum @@ -265,6 +265,8 @@ github.com/googleapis/gax-go/v2 v2.1.0/go.mod h1:Q3nei7sK6ybPYH7twZdmQpAd1MKb7pf github.com/googleapis/gax-go/v2 v2.1.1/go.mod h1:hddJymUZASv3XPyGkUpKj8pPO47Rmb0eJc8R6ouapiM= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM= diff --git a/vendor/modules.txt b/vendor/modules.txt index c3d5f3a24..79deba932 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -64,6 +64,9 @@ github.com/google/uuid # github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 ## explicit github.com/gopherjs/gopherjs/js +# github.com/gorilla/mux v1.8.0 +## explicit; go 1.12 +github.com/gorilla/mux # github.com/gorilla/securecookie v1.1.1 ## explicit github.com/gorilla/securecookie From 298a4cddfd9b3b8a56d30b25e015ddc084c0314b Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 16:48:30 +0530 Subject: [PATCH 03/72] Fix linting and naming in package notification --- .../internal/app/notification/notification.go | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/cmd/apps/skychat/internal/app/notification/notification.go b/cmd/apps/skychat/internal/app/notification/notification.go index 851c982a9..97ca4e9c4 100644 --- a/cmd/apps/skychat/internal/app/notification/notification.go +++ b/cmd/apps/skychat/internal/app/notification/notification.go @@ -9,13 +9,17 @@ import ( ) const ( - // ErrNotifType notify about errors - ErrNotifType = iota - NewAddChatNotifType //notify about an added chat by the user - NewChatNotifType //notify about a new chat initiated by a peer - NewMsgNotifType //notify about new message - //DeleteChatNotifType //notify about a deleted chat - //TODO: add SentMsgnNotifType + // ErrNotifyType notifies about errors + ErrNotifyType = iota + //NewAddChatNotifyType notifies about an added chat by the user + NewAddChatNotifyType + //NewChatNotifyType notifies about a new chat initiated by a peer + NewChatNotifyType + //NewMsgNotifyType notifies about new message + NewMsgNotifyType + //DeleteChatNotifyType notifies about a deleted chat + //DeleteChatNotifyType + //TODO: add SentMsgNotifyType ) // Notification provides a struct to send messages via the Service @@ -36,7 +40,7 @@ func NewMsgNotification(pk cipher.PubKey, msg message.Message) Notification { fmt.Printf("Failed to marshal json: %v", err) } return Notification{ - Type: NewMsgNotifType, + Type: NewMsgNotifyType, Message: string(clientMsg), } } @@ -48,7 +52,7 @@ func NewAddChatNotification(pk cipher.PubKey) Notification { fmt.Printf("Failed to marshal json: %v", err) } return Notification{ - Type: NewAddChatNotifType, + Type: NewAddChatNotifyType, Message: string(clientMsg), } } @@ -60,7 +64,7 @@ func NewChatNotification(pk cipher.PubKey) Notification { fmt.Printf("Failed to marshal json: %v", err) } return Notification{ - Type: NewChatNotifType, + Type: NewChatNotifyType, Message: string(clientMsg), } } From 235fdd2432e07a2fa99ba75f678952c4ee83dbc0 Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 16:51:29 +0530 Subject: [PATCH 04/72] comment unused server package --- .../skychat/internal/domain/server/server.go | 28 ++++++------------- 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/cmd/apps/skychat/internal/domain/server/server.go b/cmd/apps/skychat/internal/domain/server/server.go index da750d768..a711b6c91 100644 --- a/cmd/apps/skychat/internal/domain/server/server.go +++ b/cmd/apps/skychat/internal/domain/server/server.go @@ -1,22 +1,12 @@ package server -import ( - "sync" - - "github.com/skycoin/skywire-utilities/pkg/cipher" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" - "github.com/skycoin/skywire/pkg/app" -) - // Server defies the chat server -type Server struct { - appCl *app.Client // Skywire app client //nolint - clientCh chan string //nolint - conns map[cipher.PubKey]peer.Peer // peer connections //nolint - info info.Info // the public info of the server //nolint - msgs []message.Message // all messages send/received //nolint - blacklist []cipher.PubKey // Blacklist to block inocming connections //nolint - connsMu sync.Mutex //nolint -} +// type Server struct { +// appCl *app.Client // Skywire app client //nolint +// clientCh chan string //nolint +// conns map[cipher.PubKey]peer.Peer // peer connections //nolint +// info info.Info // the public info of the server //nolint +// msgs []message.Message // all messages send/received //nolint +// blacklist []cipher.PubKey // Blacklist to block inocming connections //nolint +// connsMu sync.Mutex //nolint +// } From 650a2f9208b2380d4e1545f4b55176e21c3909f8 Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 16:54:00 +0530 Subject: [PATCH 05/72] Fix Fprint linting --- cmd/apps/skychat/internal/inputports/http/user/handler.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cmd/apps/skychat/internal/inputports/http/user/handler.go b/cmd/apps/skychat/internal/inputports/http/user/handler.go index 9e5e23fe8..4e7809e1e 100644 --- a/cmd/apps/skychat/internal/inputports/http/user/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/user/handler.go @@ -100,7 +100,7 @@ func (c Handler) SetInfo(w http.ResponseWriter, r *http.Request) { err := c.userServices.Commands.SetInfoHandler.Handle(infoUpdateCommand) if err != nil { w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintf(w, err.Error()) + fmt.Fprint(w, err.Error()) } w.WriteHeader(http.StatusOK) } @@ -128,7 +128,7 @@ func (c Handler) SetSettings(w http.ResponseWriter, r *http.Request) { err := keys.Set(reqSettingsToSet.Blacklist) if err != nil { w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintf(w, err.Error()) + fmt.Fprint(w, err.Error()) } else { setSettingsCommand := commands.SetSettingsRequest{ Blacklist: keys, @@ -137,7 +137,7 @@ func (c Handler) SetSettings(w http.ResponseWriter, r *http.Request) { err = c.userServices.Commands.SetSettingsHandler.Handle(setSettingsCommand) if err != nil { w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintf(w, err.Error()) + fmt.Fprint(w, err.Error()) } } w.WriteHeader(http.StatusOK) From d9008ee707a983b4de7436d5bb46e68ce9354890 Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 16:56:06 +0530 Subject: [PATCH 06/72] Fix return error lint and add todo --- cmd/apps/skychat/internal/app/user/commands/set_settings.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cmd/apps/skychat/internal/app/user/commands/set_settings.go b/cmd/apps/skychat/internal/app/user/commands/set_settings.go index e055d0b78..dc75a0b9c 100644 --- a/cmd/apps/skychat/internal/app/user/commands/set_settings.go +++ b/cmd/apps/skychat/internal/app/user/commands/set_settings.go @@ -31,6 +31,8 @@ func (h setSettingsRequestHandler) Handle(req SetSettingsRequest) error { pUsr, err := h.usrRepo.GetUser() if err != nil { //TODO: implement error + //TODO:(ersonp) check if something else needs to be done/closed on returning an error + return err } s := settings.NewSettings(req.Blacklist) From 3f175615f8c7336dccb87b927c5463e044917e4b Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 16:58:03 +0530 Subject: [PATCH 07/72] Fix error check linting in New() of ClientRepo --- .../interfaceadapters/storage/memory/client_repo.go | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go index 86ee714ce..da78dd646 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go @@ -27,10 +27,13 @@ func NewClientRepo() *ClientRepo { func (r *ClientRepo) New() (client.Client, error) { if !r.client.IsEmtpy() { return r.client, fmt.Errorf("client already defined") - } else { - r.SetClient(*client.NewClient()) - return r.client, nil } + err := r.SetClient(*client.NewClient()) + if err != nil { + return client.Client{}, err + } + return r.client, nil + } //Get Returns the client From 4fc12282c59c4931d54c2c32f1176a82ff9d7a83 Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 16:58:54 +0530 Subject: [PATCH 08/72] Fix Global comments in package memory --- .../interfaceadapters/storage/memory/client_repo.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go index da78dd646..1c3897fc8 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go @@ -13,7 +13,7 @@ type ClientRepo struct { cliMu sync.Mutex } -//NewRepo Constructor +//NewClientRepo Constructor func NewClientRepo() *ClientRepo { cR := ClientRepo{} @@ -36,7 +36,7 @@ func (r *ClientRepo) New() (client.Client, error) { } -//Get Returns the client +//GetClient Returns the client func (r *ClientRepo) GetClient() (*client.Client, error) { r.cliMu.Lock() defer r.cliMu.Unlock() @@ -48,7 +48,7 @@ func (r *ClientRepo) GetClient() (*client.Client, error) { } } -//Update the provided client +//SetClient updates the provided client func (r *ClientRepo) SetClient(client client.Client) error { r.cliMu.Lock() defer r.cliMu.Unlock() From 8a7efab71a6a1eeb62accf74a2386db0be670a18 Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 16:59:10 +0530 Subject: [PATCH 09/72] Minor fix --- .../internal/interfaceadapters/storage/memory/client_repo.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go index 1c3897fc8..9e5b811a6 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go @@ -43,9 +43,9 @@ func (r *ClientRepo) GetClient() (*client.Client, error) { if r.client.IsEmtpy() { return nil, fmt.Errorf("client not found") - } else { - return &r.client, nil } + return &r.client, nil + } //SetClient updates the provided client From 756606e84081e5dae27fd59ae932187b2dba869d Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 17:00:02 +0530 Subject: [PATCH 10/72] Fix spelling of method IsEmtpy of Client --- cmd/apps/skychat/internal/domain/client/client.go | 4 ++-- .../internal/interfaceadapters/storage/memory/client_repo.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cmd/apps/skychat/internal/domain/client/client.go b/cmd/apps/skychat/internal/domain/client/client.go index 26d070317..9e9f7a66d 100644 --- a/cmd/apps/skychat/internal/domain/client/client.go +++ b/cmd/apps/skychat/internal/domain/client/client.go @@ -100,8 +100,8 @@ func NewClient() *Client { return &c } -// IsEmtpy checks if the cient is empty -func (c *Client) IsEmtpy() bool { +// IsEmpty checks if the client is empty +func (c *Client) IsEmpty() bool { return *c == Client{} } diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go index 9e5b811a6..f34a1e28d 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go @@ -25,7 +25,7 @@ func NewClientRepo() *ClientRepo { //New fills repo with a new client, if none has been set //also returns a client when a client has been set already func (r *ClientRepo) New() (client.Client, error) { - if !r.client.IsEmtpy() { + if !r.client.IsEmpty() { return r.client, fmt.Errorf("client already defined") } err := r.SetClient(*client.NewClient()) @@ -41,7 +41,7 @@ func (r *ClientRepo) GetClient() (*client.Client, error) { r.cliMu.Lock() defer r.cliMu.Unlock() - if r.client.IsEmtpy() { + if r.client.IsEmpty() { return nil, fmt.Errorf("client not found") } return &r.client, nil From 74711799a61346ba8ebb3f19eff0b723efe283c3 Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 17:03:23 +0530 Subject: [PATCH 11/72] Cleanup package memory --- .../storage/memory/chat_repo.go | 12 ++++----- .../storage/memory/user_repo.go | 25 ++++++++++--------- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go index 776e5938a..e18c60da5 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go @@ -14,7 +14,7 @@ type ChatRepo struct { chatsMu sync.Mutex } -//NewRepo Constructor +//NewChatRepo Constructor func NewChatRepo() *ChatRepo { cR := ChatRepo{} cR.chats = make(map[cipher.PubKey]chat.Chat) @@ -37,12 +37,12 @@ func (r *ChatRepo) GetByPK(pk cipher.PubKey) (*chat.Chat, error) { func (r *ChatRepo) GetAll() ([]chat.Chat, error) { r.chatsMu.Lock() defer r.chatsMu.Unlock() + // TODO(ersonp): code is unused; check for usage + // keys := make([]cipher.PubKey, 0) - keys := make([]cipher.PubKey, 0) - - for key := range r.chats { - keys = append(keys, key) - } + // for key := range r.chats { + // keys = append(keys, key) + // } var values []chat.Chat for _, value := range r.chats { diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go index 5d0bd0bcf..e3624be51 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go @@ -12,7 +12,7 @@ type UserRepo struct { user user.User } -//NewRepo Constructor +//NewUserRepo Constructor func NewUserRepo(pk cipher.PubKey) *UserRepo { uR := UserRepo{} @@ -26,30 +26,31 @@ func NewUserRepo(pk cipher.PubKey) *UserRepo { return &uR } -//New fills repo with a new user, if none has been set +//NewUser fills repo with a new user, if none has been set //also returns a user when a user has been set already func (r *UserRepo) NewUser() (user.User, error) { if !r.user.IsEmpty() { return r.user, fmt.Errorf("user already defined") - } else { - r.SetUser(user.NewDefaultUser()) - fmt.Printf("New DefaultUser at %p\n", &r.user) - return r.user, nil } + err := r.SetUser(user.NewDefaultUser()) + if err != nil { + return user.User{}, err + } + fmt.Printf("New DefaultUser at %p\n", &r.user) + return r.user, nil } -//Get Returns the user +//GetUser returns the user func (r *UserRepo) GetUser() (*user.User, error) { - fmt.Printf("user-repo adress %p\n", r) + fmt.Printf("user-repo address %p", r) if r.user.IsEmpty() { return nil, fmt.Errorf("user not found") - } else { - fmt.Printf("Get User at %p", &r.user) - return &r.user, nil } + fmt.Printf("Get User at %p", &r.user) + return &r.user, nil } -//Update the provided user +//SetUser updates the provided user func (r *UserRepo) SetUser(user *user.User) error { r.user = *user return nil From be791222ab1e7644adf4bedf4aaefbf0c3c35e8c Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 17:13:12 +0530 Subject: [PATCH 12/72] Remove unnecessary print line --- cmd/apps/skychat/internal/domain/user/user.go | 1 - 1 file changed, 1 deletion(-) diff --git a/cmd/apps/skychat/internal/domain/user/user.go b/cmd/apps/skychat/internal/domain/user/user.go index 3424736c9..f05fe465b 100644 --- a/cmd/apps/skychat/internal/domain/user/user.go +++ b/cmd/apps/skychat/internal/domain/user/user.go @@ -40,7 +40,6 @@ func NewDefaultUser() *User { u.info = info.NewDefaultInfo() u.settings = settings.NewDefaultSettings() - fmt.Println(u) return &u } From 77dddba1f45034637688a2cfdb169e26d80ef108 Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 19:02:07 +0530 Subject: [PATCH 13/72] Add package-comments and fix global comments --- .../internal/app/chat/commands/add_chat.go | 9 ++++---- .../internal/app/chat/commands/delete_chat.go | 9 ++++---- .../app/chat/commands/send_text_message.go | 9 ++++---- .../app/chat/queries/get_all_chats.go | 7 +++--- .../queries/get_all_messages_from_chat.go | 9 ++++---- .../app/chat/queries/get_chat_by_pk.go | 9 ++++---- .../skychat/internal/app/chat/services.go | 7 +++--- .../internal/app/messenger/messenger.go | 1 + .../internal/app/notification/notification.go | 1 + cmd/apps/skychat/internal/app/services.go | 1 + .../internal/app/user/commands/set_info.go | 9 ++++---- .../app/user/commands/set_settings.go | 9 ++++---- .../internal/app/user/queries/get_info.go | 7 +++--- .../internal/app/user/queries/get_settings.go | 7 +++--- .../skychat/internal/app/user/services.go | 7 +++--- cmd/apps/skychat/internal/domain/chat/chat.go | 1 + .../internal/domain/chat/chat_repository.go | 1 + .../skychat/internal/domain/client/client.go | 3 ++- .../domain/client/client_repository.go | 1 + cmd/apps/skychat/internal/domain/info/info.go | 1 + .../internal/domain/message/message.go | 1 + cmd/apps/skychat/internal/domain/peer/peer.go | 1 + .../skychat/internal/domain/server/server.go | 1 + .../internal/domain/settings/settings.go | 1 + cmd/apps/skychat/internal/domain/user/user.go | 7 +++--- .../internal/domain/user/user_repository.go | 1 + .../internal/inputports/http/chat/handler.go | 23 ++++++++++--------- .../http/notification.go/handler.go | 7 +++--- .../internal/inputports/http/server.go | 7 +++--- .../internal/inputports/http/user/handler.go | 17 +++++++------- .../skychat/internal/inputports/services.go | 5 ++-- .../messenger/netcon/messenger_service.go | 17 +++++++------- .../notification/http/notification_service.go | 1 + .../internal/interfaceadapters/services.go | 5 ++-- .../storage/memory/chat_repo.go | 15 ++++++------ .../storage/memory/client_repo.go | 13 ++++++----- .../storage/memory/user_repo.go | 13 ++++++----- 37 files changed, 140 insertions(+), 103 deletions(-) diff --git a/cmd/apps/skychat/internal/app/chat/commands/add_chat.go b/cmd/apps/skychat/internal/app/chat/commands/add_chat.go index 51ebe52e5..731daec4a 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/add_chat.go +++ b/cmd/apps/skychat/internal/app/chat/commands/add_chat.go @@ -1,3 +1,4 @@ +// Package commands contains commands to add chat package commands import ( @@ -8,12 +9,12 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" ) -//AddChatRequest of AddChatRequestHandler +// AddChatRequest of AddChatRequestHandler type AddChatRequest struct { Pk cipher.PubKey } -//AddChatRequestHandler struct that allows handling AddChatRequest +// AddChatRequestHandler struct that allows handling AddChatRequest type AddChatRequestHandler interface { Handle(command AddChatRequest) error } @@ -23,12 +24,12 @@ type addChatRequestHandler struct { chatRepo chat.Repository } -//NewAddChatRequestHandler Initializes an AddCommandHandler +// NewAddChatRequestHandler Initializes an AddCommandHandler func NewAddChatRequestHandler(chatRepo chat.Repository, messengerService messenger.Service) AddChatRequestHandler { return addChatRequestHandler{chatRepo: chatRepo, messengerService: messengerService} } -//Handle Handles the AddChatRequest +// Handle Handles the AddChatRequest func (h addChatRequestHandler) Handle(req AddChatRequest) error { fmt.Println("AddChatHandler - Request: " + req.Pk.Hex()) //1. check if the pubkey is already in chats diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_chat.go b/cmd/apps/skychat/internal/app/chat/commands/delete_chat.go index 36b66d60b..d5bf81ff7 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/delete_chat.go +++ b/cmd/apps/skychat/internal/app/chat/commands/delete_chat.go @@ -1,3 +1,4 @@ +// Package commands contains commands to delete chat package commands import ( @@ -8,12 +9,12 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" ) -//DeleteChatRequest Command Model +// DeleteChatRequest Command Model type DeleteChatRequest struct { Pk cipher.PubKey } -//DeleteChatRequestHandler Handler Struct with Dependencies +// DeleteChatRequestHandler Handler Struct with Dependencies type DeleteChatRequestHandler interface { Handle(command DeleteChatRequest) error } @@ -23,12 +24,12 @@ type deleteChatRequestHandler struct { chatRepo chat.Repository } -//NewDeleteChatRequestHandler Handler constructor +// NewDeleteChatRequestHandler Handler constructor func NewDeleteChatRequestHandler(cliRepo client.Repository, chatRepo chat.Repository) DeleteChatRequestHandler { return deleteChatRequestHandler{cliRepo: cliRepo, chatRepo: chatRepo} } -//Handle Handles the DeleteChatRequest request +// Handle Handles the DeleteChatRequest request func (h deleteChatRequestHandler) Handle(command DeleteChatRequest) error { _, err := h.chatRepo.GetByPK(command.Pk) if err != nil { diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go index 8b13ed210..49539fe76 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go +++ b/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go @@ -1,3 +1,4 @@ +// Package commands contains commands to send text message package commands import ( @@ -5,13 +6,13 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" ) -//SendTextMessageRequest of SendTextMessageRequestHandler +// SendTextMessageRequest of SendTextMessageRequestHandler type SendTextMessageRequest struct { Pk cipher.PubKey Msg []byte } -//SendTextMessageRequestHandler struct that allows handling SendTextMessageRequest +// SendTextMessageRequestHandler struct that allows handling SendTextMessageRequest type SendTextMessageRequestHandler interface { Handle(command SendTextMessageRequest) error } @@ -20,12 +21,12 @@ type sendTextMessageRequestHandler struct { messengerService messenger.Service } -//NewSendTextMessageRequestHandler Initializes an AddCommandHandler +// NewSendTextMessageRequestHandler Initializes an AddCommandHandler func NewSendTextMessageRequestHandler(messengerService messenger.Service) SendTextMessageRequestHandler { return sendTextMessageRequestHandler{messengerService: messengerService} } -//Handle Handles the AddCragRequest +// Handle Handles the AddCragRequest func (h sendTextMessageRequestHandler) Handle(req SendTextMessageRequest) error { err := h.messengerService.SendTextMessage(req.Pk, req.Msg) diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go b/cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go index 30c94c32b..8bcb01124 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go @@ -1,3 +1,4 @@ +// Package queries contains queries to get all chats package queries import ( @@ -17,7 +18,7 @@ type GetAllChatsResult struct { Peers []peer.Peer } -//GetAllChatsRequestHandler Contains the dependencies of the Handler +// GetAllChatsRequestHandler Contains the dependencies of the Handler type GetAllChatsRequestHandler interface { Handle() ([]GetAllChatsResult, error) } @@ -26,12 +27,12 @@ type getAllChatsRequestHandler struct { repo chat.Repository } -//NewGetAllChatsRequestHandler Handler constructor +// NewGetAllChatsRequestHandler Handler constructor func NewGetAllChatsRequestHandler(repo chat.Repository) GetAllChatsRequestHandler { return getAllChatsRequestHandler{repo: repo} } -//Handle Handles the query +// Handle Handles the query func (h getAllChatsRequestHandler) Handle() ([]GetAllChatsResult, error) { res, err := h.repo.GetAll() diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go b/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go index dd5520314..0345bbb07 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go @@ -1,3 +1,4 @@ +// Package queries contains queries to get all messages from a chat package queries import ( @@ -6,7 +7,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" ) -//GetAllMessagesFromChatRequest Model of the Handler +// GetAllMessagesFromChatRequest Model of the Handler type GetAllMessagesFromChatRequest struct { pk cipher.PubKey } @@ -16,7 +17,7 @@ type GetAllMessagesFromChatResult struct { messages []message.Message } -//GetAllMessagesFromChatRequestHandler provides an interfaces to handle a GetAllMessagesFromChatRequest and return a *GetAllMessagesFromChatResult +// GetAllMessagesFromChatRequestHandler provides an interfaces to handle a GetAllMessagesFromChatRequest and return a *GetAllMessagesFromChatResult type GetAllMessagesFromChatRequestHandler interface { Handle(query GetAllMessagesFromChatRequest) (GetAllMessagesFromChatResult, error) } @@ -25,12 +26,12 @@ type getAllMessagesFromChatRequestHandler struct { repo chat.Repository } -//NewGetAllMessagesFromChatRequestHandler Handler Constructor +// NewGetAllMessagesFromChatRequestHandler Handler Constructor func NewGetAllMessagesFromChatRequestHandler(repo chat.Repository) GetAllMessagesFromChatRequestHandler { return getAllMessagesFromChatRequestHandler{repo: repo} } -//Handle Handlers the GetAllMessagesFromChatRequest query +// Handle Handlers the GetAllMessagesFromChatRequest query func (h getAllMessagesFromChatRequestHandler) Handle(query GetAllMessagesFromChatRequest) (GetAllMessagesFromChatResult, error) { var result GetAllMessagesFromChatResult diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go b/cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go index a522f8b64..78fdbe667 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go @@ -1,3 +1,4 @@ +// Package queries contains queries to get chat by pk package queries import ( @@ -10,7 +11,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" ) -//GetChatByPKRequest Model of the Handler +// GetChatByPKRequest Model of the Handler type GetChatByPKRequest struct { Pk cipher.PubKey } @@ -25,7 +26,7 @@ type GetChatByPKResult struct { Peers []peer.Peer } -//GetChatByPKRequestHandler Contains the dependencies of the Handler +// GetChatByPKRequestHandler Contains the dependencies of the Handler type GetChatByPKRequestHandler interface { Handle(query GetChatByPKRequest) (GetChatByPKResult, error) } @@ -34,12 +35,12 @@ type getChatByPKRequestHandler struct { repo chat.Repository } -//NewGetChatByPKRequestHandler Handler constructor +// NewGetChatByPKRequestHandler Handler constructor func NewGetChatByPKRequestHandler(repo chat.Repository) GetChatByPKRequestHandler { return getChatByPKRequestHandler{repo: repo} } -//Handle Handles the query +// Handle Handles the query func (h getChatByPKRequestHandler) Handle(query GetChatByPKRequest) (GetChatByPKResult, error) { res, err := h.repo.GetByPK(query.Pk) diff --git a/cmd/apps/skychat/internal/app/chat/services.go b/cmd/apps/skychat/internal/app/chat/services.go index fa48cebc3..6dc1b337a 100644 --- a/cmd/apps/skychat/internal/app/chat/services.go +++ b/cmd/apps/skychat/internal/app/chat/services.go @@ -1,3 +1,4 @@ +// Package chatservices contains services required by the chat app package chatservices import ( @@ -8,21 +9,21 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" ) -//Queries Contains all available query handlers of this app +// Queries Contains all available query handlers of this app type Queries struct { GetAllChatsHandler queries.GetAllChatsRequestHandler GetChatByPKHandler queries.GetChatByPKRequestHandler GetAllMessagesFromChatHandler queries.GetAllMessagesFromChatRequestHandler } -//Commands Contains all available command handlers of this app +// Commands Contains all available command handlers of this app type Commands struct { AddChatHandler commands.AddChatRequestHandler DeleteChatHandler commands.DeleteChatRequestHandler SendTextHandler commands.SendTextMessageRequestHandler } -//ChatServices Contains the grouped queries and commands of the app layer +// ChatServices Contains the grouped queries and commands of the app layer type ChatServices struct { Queries Queries Commands Commands diff --git a/cmd/apps/skychat/internal/app/messenger/messenger.go b/cmd/apps/skychat/internal/app/messenger/messenger.go index b0c864bad..32a03c991 100644 --- a/cmd/apps/skychat/internal/app/messenger/messenger.go +++ b/cmd/apps/skychat/internal/app/messenger/messenger.go @@ -1,3 +1,4 @@ +// Package messenger contains the interface Service required by the chat app package messenger import ( diff --git a/cmd/apps/skychat/internal/app/notification/notification.go b/cmd/apps/skychat/internal/app/notification/notification.go index 97ca4e9c4..a520544be 100644 --- a/cmd/apps/skychat/internal/app/notification/notification.go +++ b/cmd/apps/skychat/internal/app/notification/notification.go @@ -1,3 +1,4 @@ +// Package notification contains notification related code package notification import ( diff --git a/cmd/apps/skychat/internal/app/services.go b/cmd/apps/skychat/internal/app/services.go index a05c1132a..313d9e2fb 100644 --- a/cmd/apps/skychat/internal/app/services.go +++ b/cmd/apps/skychat/internal/app/services.go @@ -1,3 +1,4 @@ +// Package app contains the Services struct for the app package app import ( diff --git a/cmd/apps/skychat/internal/app/user/commands/set_info.go b/cmd/apps/skychat/internal/app/user/commands/set_info.go index 52703103c..04f711f38 100644 --- a/cmd/apps/skychat/internal/app/user/commands/set_info.go +++ b/cmd/apps/skychat/internal/app/user/commands/set_info.go @@ -1,3 +1,4 @@ +// Package commands contains commands to set info of a user package commands import ( @@ -7,14 +8,14 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) -//SetInfoRequest of SetInfoRequestHandler +// SetInfoRequest of SetInfoRequestHandler type SetInfoRequest struct { Alias string Desc string Img string } -//SetInfoRequestHandler struct that allows handling SetInfoRequest +// SetInfoRequestHandler struct that allows handling SetInfoRequest type SetInfoRequestHandler interface { Handle(command SetInfoRequest) error } @@ -23,12 +24,12 @@ type setInfoRequestHandler struct { usrRepo user.Repository } -//NewSetInfoRequestHandler Initializes an SetInfoHandler +// NewSetInfoRequestHandler Initializes an SetInfoHandler func NewSetInfoRequestHandler(usrRepo user.Repository) SetInfoRequestHandler { return setInfoRequestHandler{usrRepo: usrRepo} } -//Handle Handles the SetInfoRequest +// Handle Handles the SetInfoRequest func (h setInfoRequestHandler) Handle(req SetInfoRequest) error { pUsr, err := h.usrRepo.GetUser() diff --git a/cmd/apps/skychat/internal/app/user/commands/set_settings.go b/cmd/apps/skychat/internal/app/user/commands/set_settings.go index dc75a0b9c..fbf5c4acc 100644 --- a/cmd/apps/skychat/internal/app/user/commands/set_settings.go +++ b/cmd/apps/skychat/internal/app/user/commands/set_settings.go @@ -1,3 +1,4 @@ +// Package commands contains commands to set settings of a user package commands import ( @@ -6,12 +7,12 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) -//SetSettingsRequest of SetSettingsRequestHandler +// SetSettingsRequest of SetSettingsRequestHandler type SetSettingsRequest struct { Blacklist []cipher.PubKey } -//SetSettingsRequestHandler struct that allows handling SetSettingsRequest +// SetSettingsRequestHandler struct that allows handling SetSettingsRequest type SetSettingsRequestHandler interface { Handle(command SetSettingsRequest) error } @@ -20,12 +21,12 @@ type setSettingsRequestHandler struct { usrRepo user.Repository } -//NewSetSettingsRequestHandler Initializes an SetSettingsRequestHandler +// NewSetSettingsRequestHandler Initializes an SetSettingsRequestHandler func NewSetSettingsRequestHandler(usrRepo user.Repository) SetSettingsRequestHandler { return setSettingsRequestHandler{usrRepo: usrRepo} } -//Handle Handles the SetSettingsRequest +// Handle Handles the SetSettingsRequest func (h setSettingsRequestHandler) Handle(req SetSettingsRequest) error { pUsr, err := h.usrRepo.GetUser() diff --git a/cmd/apps/skychat/internal/app/user/queries/get_info.go b/cmd/apps/skychat/internal/app/user/queries/get_info.go index ace76c5fe..d8e6e4905 100644 --- a/cmd/apps/skychat/internal/app/user/queries/get_info.go +++ b/cmd/apps/skychat/internal/app/user/queries/get_info.go @@ -1,3 +1,4 @@ +// Package queries contains queries to get info of a user package queries import ( @@ -12,7 +13,7 @@ type GetUserInfoResult struct { Img string } -//GetUserInfoRequestHandler Contains the dependencies of the Handler +// GetUserInfoRequestHandler Contains the dependencies of the Handler type GetUserInfoRequestHandler interface { Handle() (*GetUserInfoResult, error) } @@ -21,12 +22,12 @@ type getUserInfoRequestHandler struct { usrRepo user.Repository } -//NewGetUserInfoRequestHandler Handler constructor +// NewGetUserInfoRequestHandler Handler constructor func NewGetUserInfoRequestHandler(usrRepo user.Repository) GetUserInfoRequestHandler { return getUserInfoRequestHandler{usrRepo: usrRepo} } -//Handle Handles the query +// Handle Handles the query func (h getUserInfoRequestHandler) Handle() (*GetUserInfoResult, error) { usr, err := h.usrRepo.GetUser() var result *GetUserInfoResult diff --git a/cmd/apps/skychat/internal/app/user/queries/get_settings.go b/cmd/apps/skychat/internal/app/user/queries/get_settings.go index 8ea80edaa..e121632d9 100644 --- a/cmd/apps/skychat/internal/app/user/queries/get_settings.go +++ b/cmd/apps/skychat/internal/app/user/queries/get_settings.go @@ -1,3 +1,4 @@ +// Package queries contains queries to get settings of a user package queries import ( @@ -9,7 +10,7 @@ type GetUserSettingsResult struct { Blacklist []string } -//GetUserSettingsRequestHandler Contains the dependencies of the Handler +// GetUserSettingsRequestHandler Contains the dependencies of the Handler type GetUserSettingsRequestHandler interface { Handle() (*GetUserSettingsResult, error) } @@ -18,12 +19,12 @@ type getUserSettingsRequestHandler struct { usrRepo user.Repository } -//NewGetUserSettingsRequestHandler Handler constructor +// NewGetUserSettingsRequestHandler Handler constructor func NewGetUserSettingsRequestHandler(usrRepo user.Repository) GetUserSettingsRequestHandler { return getUserSettingsRequestHandler{usrRepo: usrRepo} } -//Handle Handles the query +// Handle Handles the query func (h getUserSettingsRequestHandler) Handle() (*GetUserSettingsResult, error) { usr, err := h.usrRepo.GetUser() var result *GetUserSettingsResult diff --git a/cmd/apps/skychat/internal/app/user/services.go b/cmd/apps/skychat/internal/app/user/services.go index 764abdc0d..600bb7847 100644 --- a/cmd/apps/skychat/internal/app/user/services.go +++ b/cmd/apps/skychat/internal/app/user/services.go @@ -1,3 +1,4 @@ +// Package userservices contains structs for the user package userservices import ( @@ -7,19 +8,19 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) -//Queries Contains all available query handlers of this app +// Queries Contains all available query handlers of this app type Queries struct { GetUserInfoHandler queries.GetUserInfoRequestHandler GetUserSettingsHandler queries.GetUserSettingsRequestHandler } -//Commands Contains all available command handlers of this app +// Commands Contains all available command handlers of this app type Commands struct { SetInfoHandler commands.SetInfoRequestHandler SetSettingsHandler commands.SetSettingsRequestHandler } -//UserServices Contains the grouped queries and commands of the app layer +// UserServices Contains the grouped queries and commands of the app layer type UserServices struct { Queries Queries Commands Commands diff --git a/cmd/apps/skychat/internal/domain/chat/chat.go b/cmd/apps/skychat/internal/domain/chat/chat.go index 24492eb67..8d1bccc39 100644 --- a/cmd/apps/skychat/internal/domain/chat/chat.go +++ b/cmd/apps/skychat/internal/domain/chat/chat.go @@ -1,3 +1,4 @@ +// Package chat contains chat realated code for domain package chat import ( diff --git a/cmd/apps/skychat/internal/domain/chat/chat_repository.go b/cmd/apps/skychat/internal/domain/chat/chat_repository.go index b4fcb3726..5308d3a6c 100644 --- a/cmd/apps/skychat/internal/domain/chat/chat_repository.go +++ b/cmd/apps/skychat/internal/domain/chat/chat_repository.go @@ -1,3 +1,4 @@ +// Package chat contains the interface Repository for domain package chat import ( diff --git a/cmd/apps/skychat/internal/domain/client/client.go b/cmd/apps/skychat/internal/domain/client/client.go index 9e9f7a66d..29cc4359e 100644 --- a/cmd/apps/skychat/internal/domain/client/client.go +++ b/cmd/apps/skychat/internal/domain/client/client.go @@ -1,3 +1,4 @@ +// Package client contains client related code for domain package client import ( @@ -49,7 +50,7 @@ func (c *Client) GetLog() *logging.Logger { return c.log } -// GetChannel returns chan string +// GetChannel returns chan string func (c *Client) GetChannel() chan string { return c.clientCh } diff --git a/cmd/apps/skychat/internal/domain/client/client_repository.go b/cmd/apps/skychat/internal/domain/client/client_repository.go index 56633f039..bb22da306 100644 --- a/cmd/apps/skychat/internal/domain/client/client_repository.go +++ b/cmd/apps/skychat/internal/domain/client/client_repository.go @@ -1,3 +1,4 @@ +// Package client contains the struct Repository code for domain package client // Repository defines the interface to the client repository diff --git a/cmd/apps/skychat/internal/domain/info/info.go b/cmd/apps/skychat/internal/domain/info/info.go index 689991fdb..fce99a50a 100644 --- a/cmd/apps/skychat/internal/domain/info/info.go +++ b/cmd/apps/skychat/internal/domain/info/info.go @@ -1,3 +1,4 @@ +// Package info contains the info required by the chat app package info import ( diff --git a/cmd/apps/skychat/internal/domain/message/message.go b/cmd/apps/skychat/internal/domain/message/message.go index 1c9df04b8..d558ace47 100644 --- a/cmd/apps/skychat/internal/domain/message/message.go +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -1,3 +1,4 @@ +// Package message contains the code required by the chat app package message import ( diff --git a/cmd/apps/skychat/internal/domain/peer/peer.go b/cmd/apps/skychat/internal/domain/peer/peer.go index 608efc509..31c2990a7 100644 --- a/cmd/apps/skychat/internal/domain/peer/peer.go +++ b/cmd/apps/skychat/internal/domain/peer/peer.go @@ -1,3 +1,4 @@ +// Package peer contains the code required by the chat app for peering package peer import ( diff --git a/cmd/apps/skychat/internal/domain/server/server.go b/cmd/apps/skychat/internal/domain/server/server.go index a711b6c91..1854608b0 100644 --- a/cmd/apps/skychat/internal/domain/server/server.go +++ b/cmd/apps/skychat/internal/domain/server/server.go @@ -1,3 +1,4 @@ +// Package server contains the code required by the chat app for peering package server // Server defies the chat server diff --git a/cmd/apps/skychat/internal/domain/settings/settings.go b/cmd/apps/skychat/internal/domain/settings/settings.go index e2ec134b6..b7d490af7 100644 --- a/cmd/apps/skychat/internal/domain/settings/settings.go +++ b/cmd/apps/skychat/internal/domain/settings/settings.go @@ -1,3 +1,4 @@ +// Package settings contains the code required by settings of the chat app package settings import ( diff --git a/cmd/apps/skychat/internal/domain/user/user.go b/cmd/apps/skychat/internal/domain/user/user.go index f05fe465b..dbf358562 100644 --- a/cmd/apps/skychat/internal/domain/user/user.go +++ b/cmd/apps/skychat/internal/domain/user/user.go @@ -1,3 +1,4 @@ +// Package user contains the code required by user of the chat app package user import ( @@ -13,7 +14,7 @@ type User struct { settings settings.Settings // the settings of the local user } -//GetInfo gets the user info +// GetInfo gets the user info func (u *User) GetInfo() *info.Info { return &u.info } @@ -23,7 +24,7 @@ func (u *User) GetSettings() *settings.Settings { return &u.settings } -//SetInfo sets the chat info +// SetInfo sets the chat info func (u *User) SetInfo(i info.Info) { u.info = i } @@ -33,7 +34,7 @@ func (u *User) SetSettings(s settings.Settings) { u.settings = s } -//NewDefaultUser returns *User +// NewDefaultUser returns *User func NewDefaultUser() *User { fmt.Println("user - NewDefaultUser") u := User{} diff --git a/cmd/apps/skychat/internal/domain/user/user_repository.go b/cmd/apps/skychat/internal/domain/user/user_repository.go index e36906150..861edbe42 100644 --- a/cmd/apps/skychat/internal/domain/user/user_repository.go +++ b/cmd/apps/skychat/internal/domain/user/user_repository.go @@ -1,3 +1,4 @@ +// Package user contains the code required by user of the chat app package user // Repository is the interface to the user repository diff --git a/cmd/apps/skychat/internal/inputports/http/chat/handler.go b/cmd/apps/skychat/internal/inputports/http/chat/handler.go index 1b068f0cf..719cf873b 100644 --- a/cmd/apps/skychat/internal/inputports/http/chat/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/chat/handler.go @@ -1,3 +1,4 @@ +// Package chat is the http handler for inputports package chat import ( @@ -14,7 +15,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/chat/queries" ) -//Handler Chat http request handler +// Handler Chat http request handler type Handler struct { chatServices chatservices.ChatServices } @@ -24,13 +25,13 @@ func NewHandler(cs chatservices.ChatServices) *Handler { return &Handler{chatServices: cs} } -//GetAll Returns all available chats +// GetAll Returns all available chats func (c Handler) GetAll(w http.ResponseWriter, r *http.Request) { fmt.Println(formatRequest(r)) chats, err := c.chatServices.Queries.GetAllChatsHandler.Handle() if err != nil { w.WriteHeader(http.StatusInternalServerError) - fmt.Fprintf(w, err.Error()) + fmt.Fprint(w, err.Error()) return } @@ -43,7 +44,7 @@ func (c Handler) GetAll(w http.ResponseWriter, r *http.Request) { // GetChatPKURLParam contains the parameter identifier to be parsed by the handler const GetChatPKURLParam = "chatPK" -//GetByPK Returns the chat with the provided pk +// GetByPK Returns the chat with the provided pk func (c Handler) GetByPK(w http.ResponseWriter, r *http.Request) { fmt.Println(formatRequest(r)) vars := mux.Vars(r) @@ -76,12 +77,12 @@ func (c Handler) GetByPK(w http.ResponseWriter, r *http.Request) { } } -//AddChatRequestModel represents the request model expected for Add request +// AddChatRequestModel represents the request model expected for Add request type AddChatRequestModel struct { Pk string `json:"pk"` } -//Add adds the provided pk +// Add adds the provided pk func (c Handler) Add(w http.ResponseWriter, r *http.Request) { //fmt.Println(formatRequest(r)) var chatToAdd AddChatRequestModel @@ -112,10 +113,10 @@ func (c Handler) Add(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -//DeleteChatPKURLParam contains the parameter identifier to be parsed by the handler +// DeleteChatPKURLParam contains the parameter identifier to be parsed by the handler const DeleteChatPKURLParam = "delete" -//Delete Deletes the crag with the provided id +// Delete Deletes the crag with the provided id func (c Handler) Delete(w http.ResponseWriter, r *http.Request) { fmt.Println(formatRequest(r)) vars := mux.Vars(r) @@ -135,16 +136,16 @@ func (c Handler) Delete(w http.ResponseWriter, r *http.Request) { } -//SendTextMessagePKURLParam contains the parameter identifier to be parsed by the handler +// SendTextMessagePKURLParam contains the parameter identifier to be parsed by the handler const SendTextMessagePKURLParam = "sendTxtMsg" -//SendTextMessageRequestModel represents the request model expected for Add request +// SendTextMessageRequestModel represents the request model expected for Add request type SendTextMessageRequestModel struct { Pk string `json:"pk"` Msg string `json:"message"` } -//SendTextMessage sends a message to the provided pk +// SendTextMessage sends a message to the provided pk func (c Handler) SendTextMessage(w http.ResponseWriter, r *http.Request) { fmt.Println(formatRequest(r)) var msgToSend SendTextMessageRequestModel diff --git a/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go b/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go index 208756ed2..a72137974 100644 --- a/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go @@ -1,3 +1,4 @@ +// Package notification is the http handler for inputports package notification import ( @@ -7,17 +8,17 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" ) -//Handler Chat http request handler +// Handler Chat http request handler type Handler struct { ns notification.Service } -//NewHandler Constructor +// NewHandler Constructor func NewHandler(ns notification.Service) *Handler { return &Handler{ns: ns} } -//SubscribeNotifications sends all received msgs from channel to http +// SubscribeNotifications sends all received msgs from channel to http func (c Handler) SubscribeNotifications(w http.ResponseWriter, r *http.Request) { f, ok := w.(http.Flusher) diff --git a/cmd/apps/skychat/internal/inputports/http/server.go b/cmd/apps/skychat/internal/inputports/http/server.go index 90e27ffd3..1a8849d42 100644 --- a/cmd/apps/skychat/internal/inputports/http/server.go +++ b/cmd/apps/skychat/internal/inputports/http/server.go @@ -1,3 +1,4 @@ +// Package http is the server handler for inputports package http import ( @@ -26,7 +27,7 @@ type Server struct { router *mux.Router } -//NewServer HTTP Server constructor +// NewServer HTTP Server constructor func NewServer(appServices app.Services) *Server { httpServer := &Server{appServices: appServices} httpServer.router = mux.NewRouter() @@ -74,14 +75,14 @@ func (httpServer *Server) AddNotificationHTTPRoutes() { httpServer.router.HandleFunc(notificationHTTPRoutePath, notification.NewHandler(httpServer.appServices.NotificationService).SubscribeNotifications).Methods("GET") } -//ListenAndServe Starts listening for requests +// ListenAndServe Starts listening for requests func (httpServer *Server) ListenAndServe(addr *string) { fmt.Println("Serving HTTP on", *addr) log.Fatal(http.ListenAndServe(*addr, nil)) } -//get index file +// getFileSystem gets index file func getFileSystem() http.FileSystem { fsys, err := fs.Sub(embededFiles, "static") if err != nil { diff --git a/cmd/apps/skychat/internal/inputports/http/user/handler.go b/cmd/apps/skychat/internal/inputports/http/user/handler.go index 4e7809e1e..d56433f22 100644 --- a/cmd/apps/skychat/internal/inputports/http/user/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/user/handler.go @@ -1,3 +1,4 @@ +// Package user is the http handler for inputports package user import ( @@ -10,12 +11,12 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/user/commands" ) -//Handler User http request handler +// Handler User http request handler type Handler struct { userServices userservices.UserServices } -//NewHandler Constructor +// NewHandler Constructor func NewHandler(app userservices.UserServices) *Handler { return &Handler{userServices: app} } @@ -23,7 +24,7 @@ func NewHandler(app userservices.UserServices) *Handler { // GetSettingsURLParam contains the parameter identifier to be parsed by the handler const GetSettingsURLParam = "settings" -//GetSettings Returns the settings of the user +// GetSettings Returns the settings of the user func (c Handler) GetSettings(w http.ResponseWriter, r *http.Request) { settings, err := c.userServices.Queries.GetUserSettingsHandler.Handle() if err == nil && settings == nil { @@ -48,7 +49,7 @@ func (c Handler) GetSettings(w http.ResponseWriter, r *http.Request) { // GetInfoURLParam contains the parameter identifier to be parsed by the handler const GetInfoURLParam = "info" -//GetInfo Returns the info of the user +// GetInfo Returns the info of the user func (c Handler) GetInfo(w http.ResponseWriter, r *http.Request) { info, err := c.userServices.Queries.GetUserInfoHandler.Handle() if err == nil && info == nil { @@ -73,14 +74,14 @@ func (c Handler) GetInfo(w http.ResponseWriter, r *http.Request) { // SetInfoURLParam contains the parameter identifier to be parsed by the handler const SetInfoURLParam = "info" -//SetInfoRequestModel represents the request model of Update +// SetInfoRequestModel represents the request model of Update type SetInfoRequestModel struct { Alias string `json:"alias"` Desc string `json:"desc"` Img string `json:"img"` } -//SetInfo Updates the user's info with the provided data +// SetInfo Updates the user's info with the provided data func (c Handler) SetInfo(w http.ResponseWriter, r *http.Request) { var reqInfoToUpdate SetInfoRequestModel @@ -108,12 +109,12 @@ func (c Handler) SetInfo(w http.ResponseWriter, r *http.Request) { // SetSettingsURLParam contains the parameter identifier to be parsed by the handler const SetSettingsURLParam = "settings" -//SetSettingsRequestModel represents the request model of SetSettings +// SetSettingsRequestModel represents the request model of SetSettings type SetSettingsRequestModel struct { Blacklist string `json:"blacklist"` } -//SetSettings sets the user's settings with the provided data +// SetSettings sets the user's settings with the provided data func (c Handler) SetSettings(w http.ResponseWriter, r *http.Request) { var reqSettingsToSet SetSettingsRequestModel diff --git a/cmd/apps/skychat/internal/inputports/services.go b/cmd/apps/skychat/internal/inputports/services.go index 6402ca403..33b0be196 100644 --- a/cmd/apps/skychat/internal/inputports/services.go +++ b/cmd/apps/skychat/internal/inputports/services.go @@ -1,3 +1,4 @@ +// Package inputports contains Services struct package inputports import ( @@ -5,12 +6,12 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/http" ) -//Services contains the ports services +// Services contains the ports services type Services struct { Server *http.Server } -//NewServices instantiates the services of input ports +// NewServices instantiates the services of input ports func NewServices(appServices app.Services) Services { return Services{Server: http.NewServer(appServices)} } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index 85afecd4e..b71469c3c 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -1,3 +1,4 @@ +// Package netcon contains code of the messenger of interfaceadapters package netcon import ( @@ -143,8 +144,8 @@ func (ms MessengerService) Handle(pk cipher.PubKey) error { } } -//Handles an incoming connection message and either accepts it and sends back the own info as message -//or if the public key is in the blacklist rejects the chat request. +// handleConnMsgType handles an incoming connection message and either accepts it and sends back the own info as message +// or if the public key is in the blacklist rejects the chat request. func (ms MessengerService) handleConnMsgType(m message.Message) error { usr, err := ms.usrRepo.GetUser() if err != nil { @@ -270,7 +271,7 @@ func (ms MessengerService) Dial(pk cipher.PubKey) (net.Conn, error) { return conn, nil } -//sendMessage sends a message to the given chat +// sendMessage sends a message to the given chat func (ms MessengerService) sendMessage(pk cipher.PubKey, m message.Message) error { c, err := ms.chatRepo.GetByPK(pk) if err != nil { @@ -305,7 +306,7 @@ func (ms MessengerService) sendMessage(pk cipher.PubKey, m message.Message) erro return nil } -//SendChatRequestMessage sends a chat request message to request a chat +// SendChatRequestMessage sends a chat request message to request a chat func (ms MessengerService) SendChatRequestMessage(pk cipher.PubKey) error { usr, err := ms.usrRepo.GetUser() @@ -321,7 +322,7 @@ func (ms MessengerService) SendChatRequestMessage(pk cipher.PubKey) error { return err } - //TODO: think about putting this notification in add_chat usecase + //TODO: think about putting this notification in add_chat use case //notify about the added chat an := notification.NewAddChatNotification(pk) ms.ns.Notify(an) @@ -333,7 +334,7 @@ func (ms MessengerService) SendChatRequestMessage(pk cipher.PubKey) error { return nil } -//SendTextMessage sends a text message to the given chat +// SendTextMessage sends a text message to the given chat func (ms MessengerService) SendTextMessage(pk cipher.PubKey, msg []byte) error { fmt.Println("MessengerService - SendTextMessage") @@ -357,7 +358,7 @@ func (ms MessengerService) SendTextMessage(pk cipher.PubKey, msg []byte) error { return nil } -//SendInfoMessage sends a info message to the given chat +// SendInfoMessage sends a info message to the given chat func (ms MessengerService) SendInfoMessage(pk cipher.PubKey, info info.Info) error { fmt.Println("MessengerService - SendInfoMessage") @@ -386,7 +387,7 @@ func (ms MessengerService) SendInfoMessage(pk cipher.PubKey, info info.Info) err return nil } -//used to listen for new incoming chats and pass them to the connection_handle routine +// Listen is used to listen for new incoming chats and pass them to the connection_handle routine func (ms MessengerService) Listen() { pCli, err := ms.cliRepo.GetClient() if err != nil { diff --git a/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go b/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go index e67e7e71e..a089727d5 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go @@ -1,3 +1,4 @@ +// Package channel contains code of the notification service of interfaceadapters package channel import ( diff --git a/cmd/apps/skychat/internal/interfaceadapters/services.go b/cmd/apps/skychat/internal/interfaceadapters/services.go index 10c07888f..05a337b3c 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/services.go +++ b/cmd/apps/skychat/internal/interfaceadapters/services.go @@ -1,3 +1,4 @@ +// Package interfaceadapters contains the struct Services package interfaceadapters import ( @@ -11,7 +12,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/storage/memory" ) -//Services contains the exposed services of interface adapters +// Services contains the exposed services of interface adapters type Services struct { ClientRepository client.Repository UserRepository user.Repository @@ -20,7 +21,7 @@ type Services struct { NotificationService notification.Service } -//NewServices Instantiates the interface adapter services +// NewServices Instantiates the interface adapter services func NewServices() Services { cliRepo := memory.NewClientRepo() cli, _ := cliRepo.GetClient() //nolint diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go index e18c60da5..dffd903ae 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go @@ -1,3 +1,4 @@ +// Package memory contains code of the chat repo of interfaceadapters package memory import ( @@ -8,20 +9,20 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" ) -//ChatRepo Implements the Repository Interface to provide an in-memory storage provider +// ChatRepo Implements the Repository Interface to provide an in-memory storage provider type ChatRepo struct { chats map[cipher.PubKey]chat.Chat chatsMu sync.Mutex } -//NewChatRepo Constructor +// NewChatRepo Constructor func NewChatRepo() *ChatRepo { cR := ChatRepo{} cR.chats = make(map[cipher.PubKey]chat.Chat) return &cR } -//GetByPK Returns the chat with the provided pk +// GetByPK Returns the chat with the provided pk func (r *ChatRepo) GetByPK(pk cipher.PubKey) (*chat.Chat, error) { r.chatsMu.Lock() defer r.chatsMu.Unlock() @@ -33,7 +34,7 @@ func (r *ChatRepo) GetByPK(pk cipher.PubKey) (*chat.Chat, error) { return &chat, nil } -//GetAll Returns all stored chats +// GetAll Returns all stored chats func (r *ChatRepo) GetAll() ([]chat.Chat, error) { r.chatsMu.Lock() defer r.chatsMu.Unlock() @@ -52,7 +53,7 @@ func (r *ChatRepo) GetAll() ([]chat.Chat, error) { return values, nil } -//Add the provided chat +// Add the provided chat func (r *ChatRepo) Add(chat chat.Chat) error { r.chatsMu.Lock() defer r.chatsMu.Unlock() @@ -61,7 +62,7 @@ func (r *ChatRepo) Add(chat chat.Chat) error { return nil } -//Update the provided chat +// Update the provided chat func (r *ChatRepo) Update(chat chat.Chat) error { r.chatsMu.Lock() defer r.chatsMu.Unlock() @@ -70,7 +71,7 @@ func (r *ChatRepo) Update(chat chat.Chat) error { return nil } -//Delete the chat with the provided pk +// Delete the chat with the provided pk func (r *ChatRepo) Delete(pk cipher.PubKey) error { r.chatsMu.Lock() defer r.chatsMu.Unlock() diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go index f34a1e28d..105460dd0 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go @@ -1,3 +1,4 @@ +// Package memory contains code of the client repo of interfaceadapters package memory import ( @@ -7,13 +8,13 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" ) -//ClientRepo Implements the Repository Interface to provide an in-memory storage provider +// ClientRepo Implements the Repository Interface to provide an in-memory storage provider type ClientRepo struct { client client.Client cliMu sync.Mutex } -//NewClientRepo Constructor +// NewClientRepo Constructor func NewClientRepo() *ClientRepo { cR := ClientRepo{} @@ -22,8 +23,8 @@ func NewClientRepo() *ClientRepo { return &cR } -//New fills repo with a new client, if none has been set -//also returns a client when a client has been set already +// New fills repo with a new client, if none has been set +// also returns a client when a client has been set already func (r *ClientRepo) New() (client.Client, error) { if !r.client.IsEmpty() { return r.client, fmt.Errorf("client already defined") @@ -36,7 +37,7 @@ func (r *ClientRepo) New() (client.Client, error) { } -//GetClient Returns the client +// GetClient Returns the client func (r *ClientRepo) GetClient() (*client.Client, error) { r.cliMu.Lock() defer r.cliMu.Unlock() @@ -48,7 +49,7 @@ func (r *ClientRepo) GetClient() (*client.Client, error) { } -//SetClient updates the provided client +// SetClient updates the provided client func (r *ClientRepo) SetClient(client client.Client) error { r.cliMu.Lock() defer r.cliMu.Unlock() diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go index e3624be51..f9669f6bf 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go @@ -1,3 +1,4 @@ +// Package memory contains code of the user repo of interfaceadapters package memory import ( @@ -7,12 +8,12 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) -//UserRepo Implements the Repository Interface to provide an in-memory storage provider +// UserRepo Implements the Repository Interface to provide an in-memory storage provider type UserRepo struct { user user.User } -//NewUserRepo Constructor +// NewUserRepo Constructor func NewUserRepo(pk cipher.PubKey) *UserRepo { uR := UserRepo{} @@ -26,8 +27,8 @@ func NewUserRepo(pk cipher.PubKey) *UserRepo { return &uR } -//NewUser fills repo with a new user, if none has been set -//also returns a user when a user has been set already +// NewUser fills repo with a new user, if none has been set +// also returns a user when a user has been set already func (r *UserRepo) NewUser() (user.User, error) { if !r.user.IsEmpty() { return r.user, fmt.Errorf("user already defined") @@ -40,7 +41,7 @@ func (r *UserRepo) NewUser() (user.User, error) { return r.user, nil } -//GetUser returns the user +// GetUser returns the user func (r *UserRepo) GetUser() (*user.User, error) { fmt.Printf("user-repo address %p", r) if r.user.IsEmpty() { @@ -50,7 +51,7 @@ func (r *UserRepo) GetUser() (*user.User, error) { return &r.user, nil } -//SetUser updates the provided user +// SetUser updates the provided user func (r *UserRepo) SetUser(user *user.User) error { r.user = *user return nil From 278aa437419832fb64c4eb85bf5ed7eecfa8de5a Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 19:06:10 +0530 Subject: [PATCH 14/72] Minor fix --- cmd/apps/skychat/internal/domain/chat/chat.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/apps/skychat/internal/domain/chat/chat.go b/cmd/apps/skychat/internal/domain/chat/chat.go index 8d1bccc39..34072919a 100644 --- a/cmd/apps/skychat/internal/domain/chat/chat.go +++ b/cmd/apps/skychat/internal/domain/chat/chat.go @@ -1,4 +1,4 @@ -// Package chat contains chat realated code for domain +// Package chat contains chat related code for domain package chat import ( From 59867a92647ed85ed51f08c763dd256ee96cddf0 Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 19:06:37 +0530 Subject: [PATCH 15/72] Fix linting in cli commands --- cmd/skywire-cli/commands/visor/route.go | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/cmd/skywire-cli/commands/visor/route.go b/cmd/skywire-cli/commands/visor/route.go index 6cadff2c6..2a9d4b7cc 100644 --- a/cmd/skywire-cli/commands/visor/route.go +++ b/cmd/skywire-cli/commands/visor/route.go @@ -23,7 +23,7 @@ import ( var routeCmd = &cobra.Command{ Use: "route", Short: "View and set rules", - Long: "\n View and set routing rules", + Long: "\n View and set routing rules", } func init() { @@ -39,7 +39,7 @@ func init() { var lsRulesCmd = &cobra.Command{ Use: "ls-rules", Short: "List routing rules", - Long: "\n List routing rules", + Long: "\n List routing rules", Run: func(cmd *cobra.Command, _ []string) { rules, err := clirpc.Client(cmd.Flags()).RoutingRules() internal.Catch(cmd.Flags(), err) @@ -51,8 +51,8 @@ var lsRulesCmd = &cobra.Command{ var ruleCmd = &cobra.Command{ Use: "rule ", Short: "Return routing rule by route ID key", - Long: "\n Return routing rule by route ID key", - Args: cobra.MinimumNArgs(1), + Long: "\n Return routing rule by route ID key", + Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { id, err := strconv.ParseUint(args[0], 10, 32) internal.Catch(cmd.Flags(), err) @@ -71,7 +71,7 @@ func init() { var rmRuleCmd = &cobra.Command{ Use: "rm-rule ", Short: "Remove routing rule", - Long: "\n Remove routing rule", + Long: "\n Remove routing rule", //Args: cobra.MinimumNArgs(1), Run: func(cmd *cobra.Command, args []string) { //TODO @@ -91,7 +91,7 @@ var rmRuleCmd = &cobra.Command{ var addRuleCmd = &cobra.Command{ Use: "add-rule ( app | fwd | intfwd )", Short: "Add routing rule", - Long: "\n Add routing rule", + Long: "\n Add routing rule", } var keepAlive time.Duration @@ -122,9 +122,9 @@ func init() { } var addAppRuleCmd = &cobra.Command{ - Use: "app \\\n \\\n \\\n \\\n \\\n \\\n || ", + Use: "app \\\n \\\n \\\n \\\n \\\n \\\n || ", Short: "Add app/consume routing rule", - Long: "\n Add app/consume routing rule", + Long: "\n Add app/consume routing rule", Args: func(_ *cobra.Command, args []string) error { if rID == "" && lPK == "" && lPt == "" && rPK == "" && rPt == "" { if len(args) > 0 { @@ -233,9 +233,9 @@ func init() { } var addFwdRuleCmd = &cobra.Command{ - Use: "fwd \\\n \\\n \\\n \\\n \\\n \\\n \\\n \\\n || ", + Use: "fwd \\\n \\\n \\\n \\\n \\\n \\\n \\\n \\\n || ", Short: "Add forward routing rule", - Long: "\n Add forward routing rule", + Long: "\n Add forward routing rule", Args: func(_ *cobra.Command, args []string) error { if len(args) > 0 { if len(args[1:]) == 6 { @@ -287,9 +287,9 @@ func init() { } var addIntFwdRuleCmd = &cobra.Command{ - Use: "intfwd \\\n \\\n \\\n \\\n || ", + Use: "intfwd \\\n \\\n \\\n \\\n || ", Short: "Add intermediary forward routing rule", - Long: "\n Add intermediary forward routing rule", + Long: "\n Add intermediary forward routing rule", Args: func(_ *cobra.Command, args []string) error { if len(args) > 0 { if len(args[0:]) == 3 { From 032718d91f52a9f5c22947b047b70c84b986d5e1 Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 20:50:31 +0530 Subject: [PATCH 16/72] Fix linting in cli visor tp --- cmd/skywire-cli/commands/visor/transports.go | 32 ++++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/cmd/skywire-cli/commands/visor/transports.go b/cmd/skywire-cli/commands/visor/transports.go index 233e17494..0b8a7a61d 100644 --- a/cmd/skywire-cli/commands/visor/transports.go +++ b/cmd/skywire-cli/commands/visor/transports.go @@ -56,9 +56,9 @@ var tpCmd = &cobra.Command{ } var lsTypesCmd = &cobra.Command{ - Use: "type", - Short: "Transport types used by the local visor", - Long: "\n Transport types used by the local visor", + Use: "type", + Short: "Transport types used by the local visor", + Long: "\n Transport types used by the local visor", DisableFlagsInUseLine: true, Run: func(cmd *cobra.Command, _ []string) { types, err := clirpc.Client(cmd.Flags()).TransportTypes() @@ -76,7 +76,7 @@ func init() { var lsTpCmd = &cobra.Command{ Use: "ls", Short: "Available transports", - Long: "\n Available transports\n\n displays transports of the local visor", + Long: "\n Available transports\n\n displays transports of the local visor", Run: func(cmd *cobra.Command, _ []string) { var pks cipher.PubKeys if filterPubKeys != nil { @@ -93,9 +93,9 @@ func init() { } var idCmd = &cobra.Command{ - Use: "id (-i) ", - Short: "Transport summary by id", - Long: "\n Transport summary by id", + Use: "id (-i) ", + Short: "Transport summary by id", + Long: "\n Transport summary by id", DisableFlagsInUseLine: true, Run: func(cmd *cobra.Command, args []string) { @@ -119,9 +119,9 @@ func init() { } var addTpCmd = &cobra.Command{ - Use: "add (-p) ", - Short: "Add a transport", - Long: "\n Add a transport\n \n If the transport type is unspecified,\n the visor will attempt to establish a transport\n in the following order: skywire-tcp, stcpr, sudph, dmsg", + Use: "add (-p) ", + Short: "Add a transport", + Long: "\n Add a transport\n \n If the transport type is unspecified,\n the visor will attempt to establish a transport\n in the following order: skywire-tcp, stcpr, sudph, dmsg", Args: cobra.MinimumNArgs(1), DisableFlagsInUseLine: true, Run: func(cmd *cobra.Command, args []string) { @@ -176,9 +176,9 @@ func init() { } var rmTpCmd = &cobra.Command{ - Use: "rm ( -a || -i ) ", - Short: "Remove transport(s) by id", - Long: "\n Remove transport(s) by id", + Use: "rm ( -a || -i ) ", + Short: "Remove transport(s) by id", + Long: "\n Remove transport(s) by id", DisableFlagsInUseLine: true, Run: func(cmd *cobra.Command, args []string) { //TODO @@ -257,9 +257,9 @@ func init() { } var discTpCmd = &cobra.Command{ - Use: "disc (--id= || --pk=)", - Short: "Discover remote transport(s)", - Long: "\n Discover remote transport(s) by ID or public key", + Use: "disc (--id= || --pk=)", + Short: "Discover remote transport(s)", + Long: "\n Discover remote transport(s) by ID or public key", DisableFlagsInUseLine: true, Args: func(_ *cobra.Command, _ []string) error { if tpID == "" && tpPK == "" { From 1ed4a520807e4a0134e5ae69ceb7f09f184d3d60 Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 21:03:32 +0530 Subject: [PATCH 17/72] Fixed and added comments in message package of domain --- .../internal/domain/message/message.go | 28 +++++++++++++------ 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/cmd/apps/skychat/internal/domain/message/message.go b/cmd/apps/skychat/internal/domain/message/message.go index d558ace47..7ea347bbc 100644 --- a/cmd/apps/skychat/internal/domain/message/message.go +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -8,27 +8,39 @@ import ( "github.com/skycoin/skywire-utilities/pkg/cipher" ) -//types of messages +// types of messages const ( - ErrMsgType = iota - ConnMsgType //used to handle connections - TxtMsgType //the txt peers send to each other or within groups - InfoMsgType //used to send and ask for info like what type of chat is the pk (group/peer), get all msgs, member infos etc. - CmdMsgType //used to control a server (e.g. send ban-peer or delete-msg commands) + // ErrMsgType is used to handle message errors types + ErrMsgType = iota + // ConnMsgType is used to handle message connections + ConnMsgType + // TxtMsgType is used to txt peers send to each other or within groups + TxtMsgType + // InfoMsgType is used to send and ask for info like what type of chat is the pk (group/peer), get all msgs, member infos etc. + InfoMsgType + // CmdMsgType is used to control a server (e.g. send ban-peer or delete-msg commands) + CmdMsgType ) -//subtypes of connMsgType +// subtypes of connMsgType const ( + // ErrConnMsg is used to handle connection errors message ErrConnMsg = iota + // ConnMsgTypeRequest is used handle connection message of type Request ConnMsgTypeRequest + // ConnMsgTypeAccept is used handle connection message of type Accept ConnMsgTypeAccept + // ConnMsgTypeReject is used handle connection message of type Reject ConnMsgTypeReject ) -//types of messageStatus +// types of messageStatus const ( + // MsgStatusInitial is used handle message status Initial MsgStatusInitial = iota + // ConnMsgTypeRequest is used handle message status Sent MsgStatusSent + // ConnMsgTypeRequest is used handle message status Received MsgStatusReceived ) From 4795c3584dd47e9845bde526c6ac05c813db60a5 Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 21:04:44 +0530 Subject: [PATCH 18/72] Minor Fix --- .../internal/domain/message/message.go | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/cmd/apps/skychat/internal/domain/message/message.go b/cmd/apps/skychat/internal/domain/message/message.go index 7ea347bbc..f5593368b 100644 --- a/cmd/apps/skychat/internal/domain/message/message.go +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -50,8 +50,8 @@ type Message struct { Origin cipher.PubKey //the originator of the Message Time time.Time //the utc+0 timestamp of the Message Sender cipher.PubKey //from who the Message was received (e.g. peer/group) - Msgtype int //see const above - MsgSubtype int //see consts above + MsgType int //see const above + MsgSubtype int //see const above Message []byte //the actual Message Status int //"Sent" or "Received" Seen bool //flag to save whether the Message was read or not by the receiver (only for local notifications) -> online feedback will be implemented in future versions @@ -63,7 +63,7 @@ type JSONMessage struct { Origin cipher.PubKey `json:"Origin"` Time time.Time `json:"Time"` Sender cipher.PubKey `json:"Sender"` - Msgtype int `json:"Msgtype"` + MsgType int `json:"Msgtype"` MsgSubtype int `json:"MsgSubtype"` Message string `json:"Message"` Status int `json:"Status"` @@ -77,7 +77,7 @@ func NewJSONMessage(m Message) JSONMessage { m.Origin, m.Time, m.Sender, - m.Msgtype, + m.MsgType, m.MsgSubtype, string(m.Message), m.Status, @@ -92,7 +92,7 @@ func NewMessage(m JSONMessage) Message { m.Origin, m.Time, m.Sender, - m.Msgtype, + m.MsgType, m.MsgSubtype, []byte(m.Message), m.Status, @@ -110,7 +110,7 @@ func NewTextMessage(pk cipher.PubKey, msg []byte) Message { m := Message{} m.Origin = pk m.Sender = pk - m.Msgtype = TxtMsgType + m.MsgType = TxtMsgType m.MsgSubtype = 0 m.Message = msg m.Status = MsgStatusInitial @@ -123,7 +123,7 @@ func NewChatRequestMessage(pk cipher.PubKey) Message { m := Message{} m.Origin = pk m.Sender = pk - m.Msgtype = ConnMsgType + m.MsgType = ConnMsgType m.MsgSubtype = ConnMsgTypeRequest m.Status = MsgStatusInitial m.Time = time.Now() @@ -135,7 +135,7 @@ func NewChatAcceptMessage(pk cipher.PubKey) Message { m := Message{} m.Origin = pk m.Sender = pk - m.Msgtype = ConnMsgType + m.MsgType = ConnMsgType m.MsgSubtype = ConnMsgTypeAccept m.Status = MsgStatusInitial m.Time = time.Now() @@ -147,7 +147,7 @@ func NewChatRejectMessage(pk cipher.PubKey) Message { m := Message{} m.Origin = pk m.Sender = pk - m.Msgtype = ConnMsgType + m.MsgType = ConnMsgType m.MsgSubtype = ConnMsgTypeReject m.Status = MsgStatusInitial m.Time = time.Now() @@ -159,7 +159,7 @@ func NewChatInfoMessage(pk cipher.PubKey, info []byte) Message { m := Message{} m.Origin = pk m.Sender = pk - m.Msgtype = InfoMsgType + m.MsgType = InfoMsgType m.Message = info m.Status = MsgStatusInitial m.Time = time.Now() @@ -188,7 +188,7 @@ func (m *Message) GetSender() cipher.PubKey { // GetMessageType returns the message type integer func (m *Message) GetMessageType() int { - return m.Msgtype + return m.MsgType } // GetMessage returns the message in bytes From 04f96d5db284d232f814df338254db1c4a8b1200 Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 21:50:48 +0530 Subject: [PATCH 19/72] Fix linting --- cmd/apps/skychat/internal/app/services.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/apps/skychat/internal/app/services.go b/cmd/apps/skychat/internal/app/services.go index 313d9e2fb..653de1af8 100644 --- a/cmd/apps/skychat/internal/app/services.go +++ b/cmd/apps/skychat/internal/app/services.go @@ -11,7 +11,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) -//Services contains all exposed services of the application layer +// Services contains all exposed services of the application layer type Services struct { NotificationService notification.Service ChatServices chatservices.ChatServices From c36b4cbe91ce48af030da89f53c145c3c113d902 Mon Sep 17 00:00:00 2001 From: ersonp Date: Thu, 27 Oct 2022 21:51:08 +0530 Subject: [PATCH 20/72] Minor update --- cmd/apps/skychat/internal/app/services.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cmd/apps/skychat/internal/app/services.go b/cmd/apps/skychat/internal/app/services.go index 653de1af8..0a59ad80d 100644 --- a/cmd/apps/skychat/internal/app/services.go +++ b/cmd/apps/skychat/internal/app/services.go @@ -19,9 +19,9 @@ type Services struct { } // NewServices Bootstraps Application Layer dependencies -func NewServices(cliRepo client.Repository, usrRepo user.Repository, chatRepo chat.Repository, notifService notification.Service, ms messenger.Service) Services { +func NewServices(cliRepo client.Repository, usrRepo user.Repository, chatRepo chat.Repository, notifyService notification.Service, ms messenger.Service) Services { return Services{ - NotificationService: notifService, + NotificationService: notifyService, ChatServices: chatservices.NewServices(cliRepo, chatRepo, ms), UserServices: userservices.NewServices(usrRepo, chatRepo)} } From 1cfd25342d7967aada4d0989ab882e360663a317 Mon Sep 17 00:00:00 2001 From: Moses Narrow <36607567+0pcom@users.noreply.github.com> Date: Sun, 6 Nov 2022 16:51:41 -0600 Subject: [PATCH 21/72] handle some errors in a temporary fashion --- .../messenger/netcon/messenger_service.go | 130 ++++++++++++++---- 1 file changed, 100 insertions(+), 30 deletions(-) diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index b71469c3c..26e7bf332 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -99,13 +99,19 @@ func (ms MessengerService) Handle(pk cipher.PubKey) error { //! Can also be a message of the remote that the own send message has been received //get the current chat so when updating nothing gets overwritten - c, _ := ms.chatRepo.GetByPK(pk) + c, err := ms.chatRepo.GetByPK(pk) + if err != nil { + fmt.Printf("Failed to update chat: %v", err) + } switch m.GetMessageType() { case message.ConnMsgType: c.AddMessage(m) - ms.chatRepo.Update(*c) - err := ms.handleConnMsgType(m) + err := ms.chatRepo.Update(*c) + if err != nil { + fmt.Printf("Failed at ms.chatRepo.Update(*c): %v", err) + } + err = ms.handleConnMsgType(m) if err != nil { fmt.Println(err) } @@ -117,7 +123,10 @@ func (ms MessengerService) Handle(pk cipher.PubKey) error { } m = message.NewMessage(jm) c.AddMessage(m) - ms.chatRepo.Update(*c) + err = ms.chatRepo.Update(*c) + if err != nil { + fmt.Printf("Failed at ms.chatRepo.Update(*c): %v", err) + } err = ms.handleInfoMsgType(c, m) if err != nil { @@ -131,7 +140,10 @@ func (ms MessengerService) Handle(pk cipher.PubKey) error { } m = message.NewMessage(jm) c.AddMessage(m) - ms.chatRepo.Update(*c) + err = ms.chatRepo.Update(*c) + if err != nil { + fmt.Printf("Failed at ms.chatRepo.Update(*c): %v", err) + } err := ms.handleTextMsgType(c, m) if err != nil { fmt.Println(err) @@ -159,31 +171,50 @@ func (ms MessengerService) handleConnMsgType(m message.Message) error { if !usr.GetSettings().InBlacklist(m.Sender) { //notify about the new chat initiated by the user an := notification.NewChatNotification(m.Sender) - ms.ns.Notify(an) + err = ms.ns.Notify(an) + if err != nil { + fmt.Printf("Failed at ms.ns.Notify(n): %v", err) + } msg := message.NewChatAcceptMessage(usr.GetInfo().GetPK()) - ms.sendMessage(m.Sender, msg) - - ms.SendInfoMessage(m.Sender, *usr.GetInfo()) + err = ms.sendMessage(m.Sender, msg) + if err != nil { + fmt.Printf("Failed at ms.sendMessage(m.Sender, msg): %v", err) + } + err = ms.SendInfoMessage(m.Sender, *usr.GetInfo()) + if err != nil { + fmt.Printf("Failed at ms.SendInfoMessage(m.Sender, *usr.GetInfo()): %v", err) + } //n := notification.NewMsgNotification(m.Sender, m) //ms.ns.Notify(n) } else { msg := message.NewChatRejectMessage(usr.GetInfo().GetPK()) - ms.sendMessage(m.Sender, msg) - ms.chatRepo.Delete(m.Sender) + err = ms.sendMessage(m.Sender, msg) + if err != nil { + fmt.Printf("Failed at ms.sendMessage(m.Sender, msg): %v", err) + } + err = ms.chatRepo.Delete(m.Sender) + if err != nil { + fmt.Printf("Failed at ms.chatRepo.Delete(m.Sender): %v", err) + } //TODO: notify about a rejected chat request cause of blacklist return fmt.Errorf("pk in blacklist") } case message.ConnMsgTypeAccept: - ms.SendInfoMessage(m.Sender, *usr.GetInfo()) - + err = ms.SendInfoMessage(m.Sender, *usr.GetInfo()) + if err != nil { + fmt.Printf("Failed at ms.SendInfoMessage(m.Sender, *usr.GetInfo()): %v", err) + } case message.ConnMsgTypeReject: //ms.chatRepo.Delete(m.Sender) n := notification.NewMsgNotification(m.Sender, m) - ms.ns.Notify(n) + err = ms.ns.Notify(n) + if err != nil { + fmt.Printf("Failed at ms.ns.Notify(n): %v", err) + } return fmt.Errorf("peer rejected chat") } @@ -191,7 +222,7 @@ func (ms MessengerService) handleConnMsgType(m message.Message) error { return nil } -//TODO: document what function does +// TODO: document what function does func (ms MessengerService) handleInfoMsgType(c *chat.Chat, m message.Message) error { //save info in chat info //unmarshal the received message bytes to info.Info @@ -201,20 +232,29 @@ func (ms MessengerService) handleInfoMsgType(c *chat.Chat, m message.Message) er fmt.Printf("Failed to unmarshal json message: %v", err) } c.Info = i - ms.chatRepo.Update(*c) + err = ms.chatRepo.Update(*c) + if err != nil { + fmt.Printf("Failed at ms.chatRepo.Update(*c): %v", err) + } //notify about new info message n := notification.NewMsgNotification(c.GetPK(), m) - ms.ns.Notify(n) + err = ms.ns.Notify(n) + if err != nil { + fmt.Printf("Failed at ms.ns.Notify(n): %v", err) + } return nil } -//TODO: document what function does +// TODO: document what function does func (ms MessengerService) handleTextMsgType(c *chat.Chat, m message.Message) error { n := notification.NewMsgNotification(c.GetPK(), message.NewTextMessage(m.Sender, m.Message)) - ms.ns.Notify(n) + err := ms.ns.Notify(n) + if err != nil { + fmt.Printf("Failed at ms.ns.Notify(n): %v", err) + } return nil } @@ -258,7 +298,7 @@ func (ms MessengerService) Dial(pk cipher.PubKey) (net.Conn, error) { //TODO: notify that dialing is happening? conn, err = pCli.GetAppClient().Dial(addr) //could not find a valid connection to a chat, so delete it. - ms.chatRepo.Delete(c.PK) + err = ms.chatRepo.Delete(c.PK) return err }) @@ -267,7 +307,10 @@ func (ms MessengerService) Dial(pk cipher.PubKey) (net.Conn, error) { } c.SetConnection(conn) - ms.chatRepo.Update(*c) + err = ms.chatRepo.Update(*c) + if err != nil { + fmt.Printf("Failed at ms.chatRepo.Update(*c): %v", err) + } return conn, nil } @@ -276,7 +319,10 @@ func (ms MessengerService) sendMessage(pk cipher.PubKey, m message.Message) erro c, err := ms.chatRepo.GetByPK(pk) if err != nil { ch := chat.NewUndefinedChat(pk) - ms.chatRepo.Add(ch) + err = ms.chatRepo.Add(ch) + if err != nil { + fmt.Printf("Failed at ms.chatRepo.Add(ch): %v", err) + } c = &ch fmt.Printf("New skychat added: %s\n", pk) } @@ -299,9 +345,15 @@ func (ms MessengerService) sendMessage(pk cipher.PubKey, m message.Message) erro return err } - c, _ = ms.chatRepo.GetByPK(pk) + c, err = ms.chatRepo.GetByPK(pk) + if err != nil { + fmt.Printf("Failed to update chat: %v", err) + } c.AddMessage(m) - ms.chatRepo.Update(*c) + err = ms.chatRepo.Update(*c) + if err != nil { + fmt.Printf("Failed at ms.chatRepo.Update(*c): %v", err) + } return nil } @@ -325,11 +377,17 @@ func (ms MessengerService) SendChatRequestMessage(pk cipher.PubKey) error { //TODO: think about putting this notification in add_chat use case //notify about the added chat an := notification.NewAddChatNotification(pk) - ms.ns.Notify(an) + err = ms.ns.Notify(an) + if err != nil { + fmt.Printf("Failed at ms.ns.Notify(an): %v", err) + } //notify about sent chat request message n := notification.NewMsgNotification(pk, m) - ms.ns.Notify(n) + err = ms.ns.Notify(n) + if err != nil { + fmt.Printf("Failed at ms.ns.Notify(n): %v", err) + } return nil } @@ -353,7 +411,10 @@ func (ms MessengerService) SendTextMessage(pk cipher.PubKey, msg []byte) error { //notify about sent text message n := notification.NewMsgNotification(pk, m) - ms.ns.Notify(n) + err = ms.ns.Notify(n) + if err != nil { + fmt.Printf("Failed at ms.ns.Notify(n): %v", err) + } return nil } @@ -382,7 +443,10 @@ func (ms MessengerService) SendInfoMessage(pk cipher.PubKey, info info.Info) err //notify about sent info message n := notification.NewMsgNotification(pk, m) - ms.ns.Notify(n) + err = ms.ns.Notify(n) + if err != nil { + fmt.Printf("Failed at ms.ns.Notify(n): %v", err) + } return nil } @@ -416,12 +480,18 @@ func (ms MessengerService) Listen() { c, err := ms.chatRepo.GetByPK(raddr.PubKey) if err != nil { ch := chat.NewUndefinedChat(raddr.PubKey) - ms.chatRepo.Add(ch) + err = ms.chatRepo.Add(ch) + if err != nil { + fmt.Printf("Failed at ms.chatRepo.Add(ch): %v", err) + } c = &ch fmt.Printf("New skychat added: %s\n", raddr.PubKey) } c.SetConnection(conn) - ms.chatRepo.Update(*c) + err = ms.chatRepo.Update(*c) + if err != nil { + fmt.Printf("Failed at ms.chatRepo.Update(*c): %v", err) + } go ms.Handle(raddr.PubKey) } From 2cb302217debd450b0eb19e4a514c2bdf865d43f Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Fri, 16 Dec 2022 23:05:48 +0100 Subject: [PATCH 22/72] commit commit to merge develop into branch --- Makefile | 2 +- .../internal/app/chat/commands/add_chat.go | 49 - .../app/chat/commands/add_local_room.go | 94 ++ .../app/chat/commands/add_local_server.go | 102 ++ .../app/chat/commands/add_remote_route.go | 56 + .../internal/app/chat/commands/delete_chat.go | 50 - .../commands/delete_local_room_by_route.go | 62 + .../commands/delete_local_server._by_route.go | 51 + .../commands/delete_remote_visor_by_pk.go | 53 + .../commands/leave_remote_room_by_route.go | 66 + .../commands/leave_remote_server_by_route.go | 54 + .../app/chat/commands/send_text_message.go | 13 +- .../app/chat/queries/get_all_chats.go | 47 - .../queries/get_all_messages_from_chat.go | 49 - .../get_all_messages_from_room_by_route.go | 66 + .../app/chat/queries/get_all_visors.go | 46 + .../app/chat/queries/get_chat_by_pk.go | 55 - .../app/chat/queries/get_room_by_route.go | 73 + .../app/chat/queries/get_server_by_route.go | 62 + .../app/chat/queries/get_visor_by_pk.go | 53 + .../skychat/internal/app/chat/services.go | 44 +- .../internal/app/messenger/messenger.go | 9 +- .../internal/app/notification/notification.go | 19 +- cmd/apps/skychat/internal/app/services.go | 6 +- .../internal/app/user/commands/add_peer.go | 41 + .../internal/app/user/commands/delete_peer.go | 40 + .../internal/app/user/commands/set_info.go | 10 +- .../internal/app/user/commands/set_peer.go | 40 + .../app/user/commands/set_settings.go | 1 - .../internal/app/user/queries/get_peerbook.go | 39 + .../internal/app/user/queries/get_settings.go | 13 +- .../skychat/internal/app/user/services.go | 20 +- cmd/apps/skychat/internal/domain/chat/chat.go | 101 -- cmd/apps/skychat/internal/domain/chat/room.go | 309 ++++ .../skychat/internal/domain/chat/server.go | 344 ++++ .../skychat/internal/domain/chat/visor.go | 178 +++ ...chat_repository.go => visor_repository.go} | 8 +- .../skychat/internal/domain/client/client.go | 46 +- cmd/apps/skychat/internal/domain/info/info.go | 5 +- .../internal/domain/message/message.go | 75 +- cmd/apps/skychat/internal/domain/peer/peer.go | 39 +- .../skychat/internal/domain/peer/peerbook.go | 37 + .../skychat/internal/domain/server/server.go | 13 - cmd/apps/skychat/internal/domain/user/user.go | 14 +- .../skychat/internal/domain/util/pkroute.go | 78 + .../skychat/internal/inputports/cli/cli.go | 4 + .../internal/inputports/http/chat/handler.go | 679 +++++++- .../http/notification.go/handler.go | 8 +- .../internal/inputports/http/server.go | 39 +- .../inputports/http/static/index.html | 1419 +---------------- .../internal/inputports/http/static/index.js | 1319 +++++++++++++++ .../inputports/http/static/stylesheet.css | 464 ++++++ .../internal/inputports/http/user/handler.go | 202 ++- .../messenger/netcon/messenger_service.go | 428 ++--- .../netcon/messenger_service_local_server.go | 271 ++++ .../messenger/netcon/messenger_service_p2p.go | 218 +++ .../netcon/messenger_service_remote_server.go | 189 +++ .../notification/http/notification_service.go | 17 +- .../internal/interfaceadapters/services.go | 9 +- .../storage/memory/chat_repo.go | 119 -- .../storage/memory/client_repo.go | 6 +- .../storage/memory/user_repo.go | 8 +- .../storage/memory/visor_repo.go | 85 + cmd/apps/skychat/skychat.go | 2 +- .../ActiveState/termtest/conpty/term_other.go | 1 + .../termtest/conpty/term_windows.go | 1 + .../Azure/go-ansiterm/winterm/ansi.go | 1 + .../Azure/go-ansiterm/winterm/api.go | 1 + .../go-ansiterm/winterm/attr_translation.go | 1 + .../go-ansiterm/winterm/cursor_helpers.go | 1 + .../go-ansiterm/winterm/erase_helpers.go | 1 + .../go-ansiterm/winterm/scroll_helper.go | 1 + .../Azure/go-ansiterm/winterm/utilities.go | 1 + .../go-ansiterm/winterm/win_event_handler.go | 1 + .../github.com/Microsoft/go-winio/backup.go | 1 + vendor/github.com/Microsoft/go-winio/file.go | 1 + .../github.com/Microsoft/go-winio/fileinfo.go | 1 + vendor/github.com/Microsoft/go-winio/pipe.go | 1 + .../Microsoft/go-winio/privilege.go | 1 + vendor/github.com/Microsoft/go-winio/sd.go | 1 + .../StackExchange/wmi/swbemservices.go | 1 + vendor/github.com/StackExchange/wmi/wmi.go | 1 + .../metrics/process_metrics_other.go | 1 + vendor/github.com/creack/pty/ioctl.go | 2 +- vendor/github.com/creack/pty/ioctl_bsd.go | 4 +- vendor/github.com/creack/pty/ioctl_solaris.go | 2 +- vendor/github.com/creack/pty/pty_darwin.go | 2 +- vendor/github.com/creack/pty/pty_dragonfly.go | 2 +- vendor/github.com/creack/pty/pty_freebsd.go | 2 +- vendor/github.com/creack/pty/pty_linux.go | 2 +- vendor/github.com/creack/pty/pty_netbsd.go | 2 +- vendor/github.com/creack/pty/pty_openbsd.go | 2 +- vendor/github.com/creack/pty/pty_solaris.go | 2 +- .../github.com/creack/pty/pty_unsupported.go | 2 +- vendor/github.com/creack/pty/run.go | 2 +- vendor/github.com/creack/pty/winsize_unix.go | 2 +- .../creack/pty/winsize_unsupported.go | 2 +- vendor/github.com/creack/pty/ztypes_386.go | 2 +- vendor/github.com/creack/pty/ztypes_amd64.go | 2 +- vendor/github.com/creack/pty/ztypes_arm.go | 2 +- vendor/github.com/creack/pty/ztypes_arm64.go | 2 +- .../creack/pty/ztypes_dragonfly_amd64.go | 2 +- .../creack/pty/ztypes_freebsd_386.go | 2 +- .../creack/pty/ztypes_freebsd_amd64.go | 2 +- .../creack/pty/ztypes_freebsd_arm.go | 2 +- .../creack/pty/ztypes_freebsd_arm64.go | 2 +- .../creack/pty/ztypes_loongarchx.go | 4 +- vendor/github.com/creack/pty/ztypes_mipsx.go | 4 +- .../creack/pty/ztypes_netbsd_32bit_int.go | 4 +- .../creack/pty/ztypes_openbsd_32bit_int.go | 4 +- vendor/github.com/creack/pty/ztypes_ppc64.go | 2 +- .../github.com/creack/pty/ztypes_ppc64le.go | 2 +- vendor/github.com/creack/pty/ztypes_riscvx.go | 2 +- vendor/github.com/creack/pty/ztypes_s390x.go | 2 +- .../github.com/davecgh/go-spew/spew/bypass.go | 1 + .../davecgh/go-spew/spew/bypasssafe.go | 1 + .../github.com/gen2brain/dlgs/color_darwin.go | 1 + vendor/github.com/gen2brain/dlgs/color_js.go | 1 + .../github.com/gen2brain/dlgs/color_linux.go | 1 + .../gen2brain/dlgs/color_unsupported.go | 1 + .../gen2brain/dlgs/color_windows.go | 1 + .../github.com/gen2brain/dlgs/date_darwin.go | 1 + vendor/github.com/gen2brain/dlgs/date_js.go | 1 + .../github.com/gen2brain/dlgs/date_linux.go | 1 + .../gen2brain/dlgs/date_unsupported.go | 1 + .../github.com/gen2brain/dlgs/date_windows.go | 1 + .../github.com/gen2brain/dlgs/dlgs_darwin.go | 1 + .../github.com/gen2brain/dlgs/dlgs_linux.go | 1 + .../github.com/gen2brain/dlgs/dlgs_windows.go | 1 + .../github.com/gen2brain/dlgs/entry_darwin.go | 1 + vendor/github.com/gen2brain/dlgs/entry_js.go | 1 + .../github.com/gen2brain/dlgs/entry_linux.go | 1 + .../gen2brain/dlgs/entry_unsupported.go | 1 + .../gen2brain/dlgs/entry_windows.go | 1 + .../github.com/gen2brain/dlgs/file_darwin.go | 1 + vendor/github.com/gen2brain/dlgs/file_js.go | 3 +- .../github.com/gen2brain/dlgs/file_linux.go | 11 +- .../gen2brain/dlgs/file_unsupported.go | 1 + .../github.com/gen2brain/dlgs/file_windows.go | 1 + .../github.com/gen2brain/dlgs/list_darwin.go | 1 + vendor/github.com/gen2brain/dlgs/list_js.go | 3 +- .../github.com/gen2brain/dlgs/list_linux.go | 1 + .../gen2brain/dlgs/list_unsupported.go | 1 + .../github.com/gen2brain/dlgs/list_windows.go | 1 + .../gen2brain/dlgs/message_darwin.go | 1 + .../github.com/gen2brain/dlgs/message_js.go | 1 + .../gen2brain/dlgs/message_linux.go | 1 + .../gen2brain/dlgs/message_unsupported.go | 1 + .../gen2brain/dlgs/message_windows.go | 1 + .../gen2brain/dlgs/password_darwin.go | 1 + .../github.com/gen2brain/dlgs/password_js.go | 1 + .../gen2brain/dlgs/password_linux.go | 1 + .../gen2brain/dlgs/password_unsupported.go | 1 + .../gen2brain/dlgs/password_windows.go | 1 + vendor/github.com/go-ole/go-ole/com.go | 1 + vendor/github.com/go-ole/go-ole/com_func.go | 1 + vendor/github.com/go-ole/go-ole/error_func.go | 1 + .../github.com/go-ole/go-ole/error_windows.go | 1 + .../go-ole/go-ole/iconnectionpoint_func.go | 1 + .../go-ole/go-ole/iconnectionpoint_windows.go | 1 + .../go-ole/iconnectionpointcontainer_func.go | 1 + .../iconnectionpointcontainer_windows.go | 1 + .../go-ole/go-ole/idispatch_func.go | 1 + .../go-ole/go-ole/idispatch_windows.go | 1 + .../go-ole/go-ole/ienumvariant_func.go | 1 + .../go-ole/go-ole/ienumvariant_windows.go | 1 + .../go-ole/go-ole/iinspectable_func.go | 1 + .../go-ole/go-ole/iinspectable_windows.go | 1 + .../go-ole/go-ole/iprovideclassinfo_func.go | 1 + .../go-ole/iprovideclassinfo_windows.go | 1 + .../go-ole/go-ole/itypeinfo_func.go | 1 + .../go-ole/go-ole/itypeinfo_windows.go | 1 + .../github.com/go-ole/go-ole/iunknown_func.go | 1 + .../go-ole/go-ole/iunknown_windows.go | 1 + .../go-ole/go-ole/oleutil/connection.go | 1 + .../go-ole/go-ole/oleutil/connection_func.go | 1 + .../go-ole/oleutil/connection_windows.go | 1 + .../go-ole/go-ole/oleutil/go-get.go | 1 + .../go-ole/go-ole/safearray_func.go | 1 + .../go-ole/go-ole/safearray_windows.go | 1 + .../go-ole/go-ole/safearrayconversion.go | 2 +- .../go-ole/go-ole/safearrayslices.go | 1 + vendor/github.com/go-ole/go-ole/variables.go | 1 + .../github.com/go-ole/go-ole/variant_386.go | 1 + .../github.com/go-ole/go-ole/variant_amd64.go | 1 + .../github.com/go-ole/go-ole/variant_arm.go | 1 + .../go-ole/go-ole/variant_date_386.go | 1 + .../go-ole/go-ole/variant_date_amd64.go | 1 + .../go-ole/go-ole/variant_date_arm.go | 1 + .../go-ole/go-ole/variant_ppc64le.go | 1 + .../github.com/go-ole/go-ole/variant_s390x.go | 1 + vendor/github.com/go-ole/go-ole/winrt.go | 1 + vendor/github.com/go-ole/go-ole/winrt_doc.go | 1 + .../github.com/godbus/dbus/v5/conn_other.go | 1 + vendor/github.com/godbus/dbus/v5/conn_unix.go | 3 +- .../github.com/godbus/dbus/v5/conn_windows.go | 3 +- .../godbus/dbus/v5/sequential_handler.go | 2 +- .../godbus/dbus/v5/transport_nonce_tcp.go | 3 +- .../godbus/dbus/v5/transport_unix.go | 3 +- vendor/github.com/google/uuid/node_js.go | 1 + vendor/github.com/google/uuid/node_net.go | 1 + .../github.com/gorilla/securecookie/fuzz.go | 1 + .../inconshreveable/mousetrap/trap_others.go | 1 + .../inconshreveable/mousetrap/trap_windows.go | 4 +- .../mousetrap/trap_windows_1.4.go | 4 +- .../james-barrow/golang-ipc/connect_other.go | 1 + vendor/github.com/json-iterator/go/any.go | 3 +- .../json-iterator/go/iter_skip_sloppy.go | 3 +- .../json-iterator/go/iter_skip_strict.go | 3 +- .../json-iterator/go/reflect_array.go | 3 +- .../json-iterator/go/reflect_dynamic.go | 3 +- .../json-iterator/go/reflect_extension.go | 3 +- .../json-iterator/go/reflect_json_number.go | 3 +- .../go/reflect_json_raw_message.go | 3 +- .../json-iterator/go/reflect_map.go | 3 +- .../json-iterator/go/reflect_optional.go | 3 +- .../json-iterator/go/reflect_slice.go | 3 +- .../go/reflect_struct_encoder.go | 3 +- .../klauspost/compress/flate/gen_inflate.go | 1 + .../klauspost/compress/flate/regmask_other.go | 3 +- .../klauspost/cpuid/detect_intel.go | 1 + .../github.com/klauspost/cpuid/detect_ref.go | 1 + .../reedsolomon/galoisAvx512_amd64.go | 5 +- .../klauspost/reedsolomon/galois_amd64.go | 5 +- .../klauspost/reedsolomon/galois_arm64.go | 5 +- .../klauspost/reedsolomon/galois_gen_amd64.go | 6 +- .../klauspost/reedsolomon/galois_gen_none.go | 3 +- .../reedsolomon/galois_gen_switch_amd64.go | 6 +- .../klauspost/reedsolomon/galois_noasm.go | 7 +- .../klauspost/reedsolomon/galois_notamd64.go | 3 +- .../klauspost/reedsolomon/galois_ppc64le.go | 5 +- .../github.com/klauspost/reedsolomon/gen.go | 3 +- .../sequences.go | 1 + .../sequences_dummy.go | 1 + .../modern-go/concurrent/go_above_19.go | 3 +- .../modern-go/concurrent/go_below_19.go | 3 +- vendor/github.com/modern-go/concurrent/log.go | 6 +- .../concurrent/unbounded_executor.go | 2 +- .../modern-go/reflect2/go_above_118.go | 5 +- .../modern-go/reflect2/go_above_19.go | 3 +- .../modern-go/reflect2/go_below_118.go | 5 +- .../github.com/modern-go/reflect2/type_map.go | 1 + vendor/github.com/pkg/errors/go113.go | 1 + .../shirou/gopsutil/v3/cpu/cpu_darwin.go | 1 + .../shirou/gopsutil/v3/cpu/cpu_darwin_cgo.go | 4 +- .../gopsutil/v3/cpu/cpu_darwin_nocgo.go | 4 +- .../shirou/gopsutil/v3/cpu/cpu_fallback.go | 1 + .../shirou/gopsutil/v3/cpu/cpu_linux.go | 1 + .../shirou/gopsutil/v3/cpu/cpu_openbsd.go | 1 + .../shirou/gopsutil/v3/cpu/cpu_windows.go | 1 + .../v3/internal/common/common_darwin.go | 1 + .../v3/internal/common/common_freebsd.go | 1 + .../v3/internal/common/common_linux.go | 1 + .../v3/internal/common/common_openbsd.go | 1 + .../v3/internal/common/common_unix.go | 1 + .../v3/internal/common/common_windows.go | 1 + .../github.com/shirou/gopsutil/v3/mem/mem.go | 2 +- .../shirou/gopsutil/v3/mem/mem_darwin.go | 1 + .../shirou/gopsutil/v3/mem/mem_darwin_cgo.go | 4 +- .../gopsutil/v3/mem/mem_darwin_nocgo.go | 4 +- .../shirou/gopsutil/v3/mem/mem_fallback.go | 1 + .../shirou/gopsutil/v3/mem/mem_freebsd.go | 1 + .../shirou/gopsutil/v3/mem/mem_linux.go | 1 + .../shirou/gopsutil/v3/mem/mem_openbsd.go | 1 + .../shirou/gopsutil/v3/mem/mem_openbsd_386.go | 5 +- .../gopsutil/v3/mem/mem_openbsd_arm64.go | 5 +- .../shirou/gopsutil/v3/mem/mem_windows.go | 1 + .../shirou/gopsutil/v3/net/net_aix.go | 1 + .../shirou/gopsutil/v3/net/net_darwin.go | 4 +- .../shirou/gopsutil/v3/net/net_fallback.go | 1 + .../shirou/gopsutil/v3/net/net_freebsd.go | 1 + .../shirou/gopsutil/v3/net/net_linux.go | 1 + .../shirou/gopsutil/v3/net/net_openbsd.go | 1 + .../shirou/gopsutil/v3/net/net_unix.go | 1 + .../shirou/gopsutil/v3/net/net_windows.go | 2 +- .../shirou/gopsutil/v3/process/process_bsd.go | 2 +- .../gopsutil/v3/process/process_darwin.go | 1 + .../v3/process/process_darwin_arm64.go | 5 +- .../gopsutil/v3/process/process_darwin_cgo.go | 4 +- .../v3/process/process_darwin_nocgo.go | 4 +- .../gopsutil/v3/process/process_fallback.go | 1 + .../gopsutil/v3/process/process_freebsd.go | 1 + .../v3/process/process_freebsd_arm64.go | 323 ++-- .../gopsutil/v3/process/process_linux.go | 1 + .../gopsutil/v3/process/process_openbsd.go | 1 + .../v3/process/process_openbsd_386.go | 5 +- .../v3/process/process_openbsd_arm64.go | 5 +- .../gopsutil/v3/process/process_posix.go | 1 + .../gopsutil/v3/process/process_windows.go | 1 + .../v3/process/process_windows_386.go | 5 +- .../v3/process/process_windows_amd64.go | 1 + .../sirupsen/logrus/hooks/syslog/syslog.go | 1 + .../logrus/terminal_check_appengine.go | 1 + .../sirupsen/logrus/terminal_check_bsd.go | 1 + .../sirupsen/logrus/terminal_check_js.go | 1 + .../logrus/terminal_check_no_terminal.go | 1 + .../logrus/terminal_check_notappengine.go | 1 + .../sirupsen/logrus/terminal_check_unix.go | 1 + .../sirupsen/logrus/terminal_check_windows.go | 1 + .../servermetrics/victoria_metrics.go | 1 + .../skycoin/dmsg/pkg/disc/client.go | 1 + .../skycoin/dmsg/pkg/dmsg/client_session.go | 3 +- .../skycoin/dmsg/pkg/dmsg/entity_common.go | 1 + .../skycoin/dmsg/pkg/dmsg/server.go | 1 + .../skycoin/dmsg/pkg/dmsg/server_session.go | 3 +- .../skycoin/dmsg/pkg/dmsg/session_common.go | 3 +- .../skycoin/dmsg/pkg/dmsg/stream.go | 3 +- .../skycoin/dmsg/pkg/dmsgget/dmsgget.go | 1 + .../skycoin/dmsg/pkg/dmsgpty/cli.go | 1 + .../skycoin/dmsg/pkg/dmsgpty/host.go | 1 + .../skycoin/dmsg/pkg/dmsgpty/pty_client.go | 1 + .../github.com/skycoin/dmsg/pkg/dmsgpty/ui.go | 3 +- .../skycoin/dmsg/pkg/dmsgpty/whitelist.go | 1 + .../skycoin/dmsg/pkg/dmsgtest/env.go | 3 +- .../github.com/skycoin/dmsg/pkg/noise/net.go | 1 + .../skycoin/dmsg/pkg/noise/noise.go | 1 + vendor/github.com/skycoin/noise/patterns.go | 2 +- .../secp256k1-go/secp256k1-go2/secp256k1.go | 4 +- .../pkg/cmdutil/service_flags.go | 3 +- .../pkg/cmdutil/sysloghook_unix.go | 1 + .../pkg/cmdutil/sysloghook_windows.go | 1 + .../skycoin/skywire-utilities/pkg/geo/geo.go | 1 + .../pkg/httputil/httputil.go | 1 + .../github.com/songgao/water/params_others.go | 1 + .../songgao/water/syscalls_darwin_go1.11.go | 1 + .../songgao/water/syscalls_darwin_legacy.go | 1 + .../songgao/water/syscalls_linux_go1.11.go | 1 + .../songgao/water/syscalls_linux_legacy.go | 1 + .../songgao/water/syscalls_other.go | 1 + .../stretchr/testify/require/require.go | 3 +- .../testify/require/require_forward.go | 3 +- .../capability/capability_noop.go | 1 + .../github.com/templexxx/cpufeat/cpu_x86.go | 1 + vendor/github.com/templexxx/xor/xor_other.go | 1 + vendor/github.com/tjfoc/gmsm/sm4/sm4.go | 4 - vendor/github.com/tjfoc/gmsm/sm4/sm4_gcm.go | 384 +++-- .../tklauser/go-sysconf/sysconf_bsd.go | 1 + .../tklauser/go-sysconf/sysconf_generic.go | 1 + .../tklauser/go-sysconf/sysconf_posix.go | 1 + .../go-sysconf/sysconf_unsupported.go | 1 + .../tklauser/numcpus/numcpus_bsd.go | 1 + .../tklauser/numcpus/numcpus_solaris.go | 1 + .../tklauser/numcpus/numcpus_unsupported.go | 1 + .../xtaci/kcp-go/readloop_generic.go | 1 + .../github.com/xtaci/kcp-go/readloop_linux.go | 1 + vendor/github.com/xtaci/kcp-go/tx_generic.go | 1 + vendor/github.com/xtaci/kcp-go/tx_linux.go | 1 + vendor/go.etcd.io/bbolt/bolt_arm64.go | 1 + vendor/go.etcd.io/bbolt/bolt_mips64x.go | 1 + vendor/go.etcd.io/bbolt/bolt_mipsx.go | 1 + vendor/go.etcd.io/bbolt/bolt_ppc.go | 1 + vendor/go.etcd.io/bbolt/bolt_ppc64.go | 1 + vendor/go.etcd.io/bbolt/bolt_ppc64le.go | 1 + vendor/go.etcd.io/bbolt/bolt_riscv64.go | 1 + vendor/go.etcd.io/bbolt/bolt_s390x.go | 1 + vendor/go.etcd.io/bbolt/bolt_unix.go | 1 + vendor/go.etcd.io/bbolt/bolt_unix_aix.go | 1 + vendor/go.etcd.io/bbolt/boltsync_unix.go | 1 + vendor/go.etcd.io/bbolt/mlock_unix.go | 1 + .../curve25519/internal/field/fe_amd64.go | 1 + .../x/net/internal/socket/zsys_linux_ppc.go | 32 +- 361 files changed, 6585 insertions(+), 2794 deletions(-) delete mode 100644 cmd/apps/skychat/internal/app/chat/commands/add_chat.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/add_local_room.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/add_local_server.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/add_remote_route.go delete mode 100644 cmd/apps/skychat/internal/app/chat/commands/delete_chat.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/delete_local_room_by_route.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/delete_local_server._by_route.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/delete_remote_visor_by_pk.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/leave_remote_room_by_route.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/leave_remote_server_by_route.go delete mode 100644 cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go delete mode 100644 cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go create mode 100644 cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_room_by_route.go create mode 100644 cmd/apps/skychat/internal/app/chat/queries/get_all_visors.go delete mode 100644 cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go create mode 100644 cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go create mode 100644 cmd/apps/skychat/internal/app/chat/queries/get_server_by_route.go create mode 100644 cmd/apps/skychat/internal/app/chat/queries/get_visor_by_pk.go create mode 100644 cmd/apps/skychat/internal/app/user/commands/add_peer.go create mode 100644 cmd/apps/skychat/internal/app/user/commands/delete_peer.go create mode 100644 cmd/apps/skychat/internal/app/user/commands/set_peer.go create mode 100644 cmd/apps/skychat/internal/app/user/queries/get_peerbook.go delete mode 100644 cmd/apps/skychat/internal/domain/chat/chat.go create mode 100644 cmd/apps/skychat/internal/domain/chat/room.go create mode 100644 cmd/apps/skychat/internal/domain/chat/server.go create mode 100644 cmd/apps/skychat/internal/domain/chat/visor.go rename cmd/apps/skychat/internal/domain/chat/{chat_repository.go => visor_repository.go} (69%) create mode 100644 cmd/apps/skychat/internal/domain/peer/peerbook.go delete mode 100644 cmd/apps/skychat/internal/domain/server/server.go create mode 100644 cmd/apps/skychat/internal/domain/util/pkroute.go create mode 100644 cmd/apps/skychat/internal/inputports/cli/cli.go create mode 100644 cmd/apps/skychat/internal/inputports/http/static/index.js create mode 100644 cmd/apps/skychat/internal/inputports/http/static/stylesheet.css create mode 100644 cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go create mode 100644 cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go create mode 100644 cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go delete mode 100644 cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go create mode 100644 cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go diff --git a/Makefile b/Makefile index 4316ade83..3340bf1e7 100644 --- a/Makefile +++ b/Makefile @@ -178,7 +178,7 @@ format: tidy ## Formats the code. Must have goimports and goimports-reviser inst ${OPTS} goimports -w -local ${PROJECT_BASE} ./pkg ${OPTS} goimports -w -local ${PROJECT_BASE} ./cmd ${OPTS} goimports -w -local ${PROJECT_BASE} ./internal - find . -type f -name '*.go' -not -path "./.git/*" -not -path "./vendor/*" -exec goimports-reviser -project-name ${PROJECT_BASE} {} \; + find . -type f -name '*.go' -not -path "./.git/*" -not -path "./vendor/*" -exec goimports-reviser -project-name ${PROJECT_BASE} \; format-windows: tidy ## Formats the code. Must have goimports and goimports-reviser installed (use make install-linters). powershell 'Get-ChildItem -Directory | where Name -NotMatch vendor | % { Get-ChildItem $$_ -Recurse -Include *.go } | % {goimports -w -local ${PROJECT_BASE} $$_ }' diff --git a/cmd/apps/skychat/internal/app/chat/commands/add_chat.go b/cmd/apps/skychat/internal/app/chat/commands/add_chat.go deleted file mode 100644 index 731daec4a..000000000 --- a/cmd/apps/skychat/internal/app/chat/commands/add_chat.go +++ /dev/null @@ -1,49 +0,0 @@ -// Package commands contains commands to add chat -package commands - -import ( - "fmt" - - "github.com/skycoin/skywire-utilities/pkg/cipher" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" -) - -// AddChatRequest of AddChatRequestHandler -type AddChatRequest struct { - Pk cipher.PubKey -} - -// AddChatRequestHandler struct that allows handling AddChatRequest -type AddChatRequestHandler interface { - Handle(command AddChatRequest) error -} - -type addChatRequestHandler struct { - messengerService messenger.Service - chatRepo chat.Repository -} - -// NewAddChatRequestHandler Initializes an AddCommandHandler -func NewAddChatRequestHandler(chatRepo chat.Repository, messengerService messenger.Service) AddChatRequestHandler { - return addChatRequestHandler{chatRepo: chatRepo, messengerService: messengerService} -} - -// Handle Handles the AddChatRequest -func (h addChatRequestHandler) Handle(req AddChatRequest) error { - fmt.Println("AddChatHandler - Request: " + req.Pk.Hex()) - //1. check if the pubkey is already in chats - _, err := h.chatRepo.GetByPK(req.Pk) - if err == nil { - return fmt.Errorf("chat %s already added", req.Pk.Hex()) - } - - err = h.messengerService.SendChatRequestMessage(req.Pk) - if err != nil { - return err - } - - go h.messengerService.Handle(req.Pk) //nolint:errcheck - - return nil -} diff --git a/cmd/apps/skychat/internal/app/chat/commands/add_local_room.go b/cmd/apps/skychat/internal/app/chat/commands/add_local_room.go new file mode 100644 index 000000000..6d937913d --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/add_local_room.go @@ -0,0 +1,94 @@ +// Package commands contains commands to add a local room +package commands + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// AddLocalRoomRequest of AddLocalRoomRequestHandler +type AddLocalRoomRequest struct { + Route util.PKRoute + Info info.Info + Type int64 +} + +// AddLocalRoomRequestHandler struct that allows handling AddLocalRoomRequest +type AddLocalRoomRequestHandler interface { + Handle(command AddLocalRoomRequest) error +} + +type addLocalRoomRequestHandler struct { + visorRepo chat.Repository + userRepo user.Repository + ns notification.Service +} + +// NewAddLocalRoomRequestHandler Initializes an AddCommandHandler +func NewAddLocalRoomRequestHandler(visorRepo chat.Repository, userRepo user.Repository, ns notification.Service) AddLocalRoomRequestHandler { + return addLocalRoomRequestHandler{visorRepo: visorRepo, userRepo: userRepo, ns: ns} +} + +// Handle Handles the AddLocalRoomRequest +func (h addLocalRoomRequestHandler) Handle(command AddLocalRoomRequest) error { + //Get user + usr, err := h.userRepo.GetUser() + if err != nil { + return err + } + + // Check if visor exists + visor, err := h.visorRepo.GetByPK(command.Route.Visor) + if err != nil { + return err + } + // Check if server exists + server, err := visor.GetServerByPK(command.Route.Server) + if err != nil { + return err + } + + // make a new route + rr := util.NewLocalRoomRoute(command.Route.Visor, command.Route.Server, server.GetAllRoomsBoolMap()) + + // setup room for repository + r := chat.NewLocalRoom(rr, command.Info, command.Type) + + //setup user as peer for room membership + p := peer.NewPeer(*usr.GetInfo(), usr.GetInfo().Alias) + //Add user as member + err = r.AddMember(*p) + if err != nil { + return err + } + + //[]: if room is visible/public also add messengerService and send 'Room-Added' Message to Members of server + + // add room to server, update visor and then update repository + err = server.AddRoom(r) + if err != nil { + return err + } + err = visor.SetServer(*server) + if err != nil { + return err + } + + err = h.visorRepo.Set(*visor) + if err != nil { + return err + } + + //notify about sent chat request message + n := notification.NewAddRouteNotification(rr) + err = h.ns.Notify(n) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go b/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go new file mode 100644 index 000000000..5edbc85be --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go @@ -0,0 +1,102 @@ +// Package commands contains commands to add a local server +package commands + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// AddLocalServerRequest of AddLocalServerRequestHandler +type AddLocalServerRequest struct { + Route util.PKRoute + Info info.Info +} + +// AddLocalServerRequestHandler struct that allows handling AddLocalServerRequest +type AddLocalServerRequestHandler interface { + Handle(command AddLocalServerRequest) error +} + +type addLocalServerRequestHandler struct { + visorRepo chat.Repository + userRepo user.Repository + ns notification.Service +} + +// NewAddLocalServerRequestHandler Initializes an AddCommandHandler +func NewAddLocalServerRequestHandler(visorRepo chat.Repository, userRepo user.Repository, ns notification.Service) AddLocalServerRequestHandler { + return addLocalServerRequestHandler{visorRepo: visorRepo, userRepo: userRepo, ns: ns} +} + +// Handle Handles the AddLocalServerRequest +func (h addLocalServerRequestHandler) Handle(command AddLocalServerRequest) error { + //Get user + usr, err := h.userRepo.GetUser() + if err != nil { + return err + } + + //TODO: Rewrite so the local visor pk must not be known from requester (-> use userRepo) + // Check if local visor exists, if not add the default local visor + visor := chat.Visor{} + pVisor, err := h.visorRepo.GetByPK(command.Route.Visor) + if err != nil { + visor = chat.NewUndefinedVisor(command.Route.Visor) + err = h.visorRepo.Add(visor) + if err != nil { + return err + } + } else { + visor = *pVisor + } + + visorBoolMap := visor.GetAllServerBoolMap() + + route := util.NewLocalServerRoute(visor.GetPK(), visorBoolMap) + server, err := chat.NewLocalServer(route, command.Info) + if err != nil { + return err + } + + //setup room + roomBoolMap := server.GetAllRoomsBoolMap() + roomRoute := util.NewLocalRoomRoute(server.PKRoute.Visor, server.PKRoute.Server, roomBoolMap) + r := chat.NewLocalRoom(roomRoute, command.Info, chat.DefaultRoomType) + + //setup user as peer for room membership + p := peer.NewPeer(*usr.GetInfo(), usr.GetInfo().Alias) + //Add user as member + err = r.AddMember(*p) + if err != nil { + return err + } + + //Add room to server + err = server.AddRoom(r) + if err != nil { + return err + } + + // Add server to visor and then update repository + err = visor.AddServer(*server) + if err != nil { + return err + } + err = h.visorRepo.Set(visor) + if err != nil { + return err + } + + //notify about sent chat request message + n := notification.NewAddRouteNotification(roomRoute) + err = h.ns.Notify(n) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/add_remote_route.go b/cmd/apps/skychat/internal/app/chat/commands/add_remote_route.go new file mode 100644 index 000000000..d00901bc2 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/add_remote_route.go @@ -0,0 +1,56 @@ +// Package commands contains commands to add a remote route (this can be a visor, a server, or a room) +package commands + +import ( + "fmt" + + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// AddRemoteRouteRequest of AddRemoteRouteRequestHandler +type AddRemoteRouteRequest struct { + Route util.PKRoute +} + +// AddRemoteRouteRequestHandler struct that allows handling AddRemoteRouteRequest +type AddRemoteRouteRequestHandler interface { + Handle(command AddRemoteRouteRequest) error +} + +type addRemoteRouteRequestHandler struct { + messengerService messenger.Service + visorRepo chat.Repository +} + +// NewAddRemoteRouteRequestHandler Initializes an AddCommandHandler +func NewAddRemoteRouteRequestHandler(visorRepo chat.Repository, messengerService messenger.Service) AddRemoteRouteRequestHandler { + return addRemoteRouteRequestHandler{visorRepo: visorRepo, messengerService: messengerService} +} + +// Handle Handles the AddRemoteRouteRequest +func (h addRemoteRouteRequestHandler) Handle(command AddRemoteRouteRequest) error { + fmt.Println("AddRemoteRouteHandler - Request: " + command.Route.String()) + //1. check if the requested route is already in visor repo + visor, err := h.visorRepo.GetByPK(command.Route.Visor) + if err == nil { + server, err := visor.GetServerByPK(command.Route.Server) + if err == nil { + _, err := server.GetRoomByPK(command.Route.Room) + if err == nil { + return fmt.Errorf("room %s already added", command.Route.String()) + } + } + + } + + err = h.messengerService.SendRouteRequestMessage(command.Route) + if err != nil { + return err + } + + go h.messengerService.Handle(command.Route.Visor) //nolint:errcheck + + return nil +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_chat.go b/cmd/apps/skychat/internal/app/chat/commands/delete_chat.go deleted file mode 100644 index d5bf81ff7..000000000 --- a/cmd/apps/skychat/internal/app/chat/commands/delete_chat.go +++ /dev/null @@ -1,50 +0,0 @@ -// Package commands contains commands to delete chat -package commands - -import ( - "fmt" - - "github.com/skycoin/skywire-utilities/pkg/cipher" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" -) - -// DeleteChatRequest Command Model -type DeleteChatRequest struct { - Pk cipher.PubKey -} - -// DeleteChatRequestHandler Handler Struct with Dependencies -type DeleteChatRequestHandler interface { - Handle(command DeleteChatRequest) error -} - -type deleteChatRequestHandler struct { - cliRepo client.Repository - chatRepo chat.Repository -} - -// NewDeleteChatRequestHandler Handler constructor -func NewDeleteChatRequestHandler(cliRepo client.Repository, chatRepo chat.Repository) DeleteChatRequestHandler { - return deleteChatRequestHandler{cliRepo: cliRepo, chatRepo: chatRepo} -} - -// Handle Handles the DeleteChatRequest request -func (h deleteChatRequestHandler) Handle(command DeleteChatRequest) error { - _, err := h.chatRepo.GetByPK(command.Pk) - if err != nil { - return err - } - - pCli, err := h.cliRepo.GetClient() - if err != nil { - fmt.Printf("Error Getting client") - return err - } - - //close all routes - //TODO:this does not work as expected --> shouldnt only the routes be closed? - pCli.GetAppClient().Close() - - return h.chatRepo.Delete(command.Pk) -} diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_local_room_by_route.go b/cmd/apps/skychat/internal/app/chat/commands/delete_local_room_by_route.go new file mode 100644 index 000000000..025450744 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/delete_local_room_by_route.go @@ -0,0 +1,62 @@ +package commands + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// DeleteLocalRoomRequest of DeleteLocalRoomRequestHandler +type DeleteLocalRoomRequest struct { + Route util.PKRoute +} + +// DeleteLocalRoomRequestHandler struct that allows handling DeleteLocalRoomRequest +type DeleteLocalRoomRequestHandler interface { + Handle(command DeleteLocalRoomRequest) error +} + +type deleteLocalRoomRequestHandler struct { + messengerService messenger.Service + visorRepo chat.Repository +} + +// NewDeleteLocalRoomRequestHandler Initializes an AddCommandHandler +func NewDeleteLocalRoomRequestHandler(messengerService messenger.Service, visorRepo chat.Repository) DeleteLocalRoomRequestHandler { + return deleteLocalRoomRequestHandler{messengerService: messengerService, visorRepo: visorRepo} +} + +// Handle Handles the DeleteLocalRoomRequest +func (h deleteLocalRoomRequestHandler) Handle(command DeleteLocalRoomRequest) error { + // Check if visor exists + visor, err := h.visorRepo.GetByPK(command.Route.Visor) + if err != nil { + return err + } + // Check if server exists + server, err := visor.GetServerByPK(command.Route.Server) + if err != nil { + return err + } + // Check if room exists + _, err = server.GetRoomByPK(command.Route.Room) + if err != nil { + return err + } + + // Delete room from server + err = server.DeleteRoom(command.Route.Room) + if err != nil { + return err + } + + //[]: Send 'Room-Deleted-Message' to room members (and to server members if room is public) + + // Update visor, and repository with changed server + err = visor.SetServer(*server) + if err != nil { + return err + } + + return h.visorRepo.Set(*visor) +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_local_server._by_route.go b/cmd/apps/skychat/internal/app/chat/commands/delete_local_server._by_route.go new file mode 100644 index 000000000..cbdbb08b6 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/delete_local_server._by_route.go @@ -0,0 +1,51 @@ +package commands + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// DeleteLocalServerRequest of DeleteLocalServerRequestHandler +type DeleteLocalServerRequest struct { + Route util.PKRoute +} + +// DeleteLocalServerRequestHandler struct that allows handling DeleteLocalServerRequest +type DeleteLocalServerRequestHandler interface { + Handle(command DeleteLocalServerRequest) error +} + +type deleteLocalServerRequestHandler struct { + messengerService messenger.Service + visorRepo chat.Repository +} + +// NewDeleteLocalServerRequestHandler Initializes an AddCommandHandler +func NewDeleteLocalServerRequestHandler(messengerService messenger.Service, visorRepo chat.Repository) DeleteLocalServerRequestHandler { + return deleteLocalServerRequestHandler{messengerService: messengerService, visorRepo: visorRepo} +} + +// Handle Handles the DeleteLocalServerRequest +func (h deleteLocalServerRequestHandler) Handle(command DeleteLocalServerRequest) error { + // Check if visor exists + visor, err := h.visorRepo.GetByPK(command.Route.Visor) + if err != nil { + return err + } + // Check if server exists + _, err = visor.GetServerByPK(command.Route.Server) + if err != nil { + return err + } + + //[]: Send 'Server-Deleted-Message' to Server members + + // Delete server from visor and update repo + err = visor.DeleteServer(command.Route.Server) + if err != nil { + return err + } + + return h.visorRepo.Set(*visor) +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_remote_visor_by_pk.go b/cmd/apps/skychat/internal/app/chat/commands/delete_remote_visor_by_pk.go new file mode 100644 index 000000000..e7e49e2a4 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/delete_remote_visor_by_pk.go @@ -0,0 +1,53 @@ +// Package commands contains commands to delete a remote visor +package commands + +import ( + "fmt" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" +) + +// DeleteRemoteVisorRequest Command Model +type DeleteRemoteVisorRequest struct { + Pk cipher.PubKey +} + +// DeleteRemoteVisorRequestHandler Handler Struct with Dependencies +type DeleteRemoteVisorRequestHandler interface { + Handle(command DeleteRemoteVisorRequest) error +} + +type deleteRemoteVisorRequestHandler struct { + cliRepo client.Repository + visorRepo chat.Repository +} + +// NewDeleteRemoteVisorRequestHandler Handler constructor +func NewDeleteRemoteVisorRequestHandler(cliRepo client.Repository, visorRepo chat.Repository) DeleteRemoteVisorRequestHandler { + return deleteRemoteVisorRequestHandler{cliRepo: cliRepo, visorRepo: visorRepo} +} + +// Handle Handles the DeleteRemoteVisorRequest request +func (h deleteRemoteVisorRequestHandler) Handle(command DeleteRemoteVisorRequest) error { + // Check if visor exists + _, err := h.visorRepo.GetByPK(command.Pk) + if err != nil { + return err + } + + pCli, err := h.cliRepo.GetClient() + if err != nil { + fmt.Printf("Error Getting client") + return err + } + + //[]: Send 'Delete-Visor-Message' to remote visor so it can be notified about the deletion?? + + //close all routes + //TODO:this does not work as expected --> shouldnt only the routes be closed? + pCli.GetAppClient().Close() + + return h.visorRepo.Delete(command.Pk) +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_room_by_route.go b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_room_by_route.go new file mode 100644 index 000000000..393ed987d --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_room_by_route.go @@ -0,0 +1,66 @@ +// Package commands contains commands to leave remote room +package commands + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// LeaveRemoteRoomRequest Command Model +type LeaveRemoteRoomRequest struct { + Route util.PKRoute +} + +// LeaveRemoteRoomRequestHandler Handler Struct with Dependencies +type LeaveRemoteRoomRequestHandler interface { + Handle(command LeaveRemoteRoomRequest) error +} + +type leaveRemoteRoomRequestHandler struct { + messengerService messenger.Service + visorRepo chat.Repository +} + +// NewLeaveRemoteRoomRequestHandler Handler constructor +func NewLeaveRemoteRoomRequestHandler(messengerService messenger.Service, visorRepo chat.Repository) LeaveRemoteRoomRequestHandler { + return leaveRemoteRoomRequestHandler{messengerService: messengerService, visorRepo: visorRepo} +} + +// Handle Handles the LeaveRemoteRoomRequest request +func (h leaveRemoteRoomRequestHandler) Handle(command LeaveRemoteRoomRequest) error { + // Check if visor exists + visor, err := h.visorRepo.GetByPK(command.Route.Visor) + if err != nil { + return err + } + // Check if server exists + server, err := visor.GetServerByPK(command.Route.Server) + if err != nil { + return err + } + // Check if room exists + _, err = server.GetRoomByPK(command.Route.Room) + if err != nil { + return err + } + + //[]: send 'Leave-Room-Message' to remote server so membership of room can be removed + //?: this command is nearly the same as delete_local_room_by_route.go -> maybe remove one and add this part here with if visorpk=localvisor + //! -> When the 'Leave-Room-Message' does not get recognized from the room, all 'Room-Messages' still get send -> How to solve? + + //?if this is the last Room maybe also leave server? -> and do everything that is done when a server is left + + // Delete room from server + err = server.DeleteRoom(command.Route.Room) + if err != nil { + return err + } + // Update visor, and repository with changed server + err = visor.SetServer(*server) + if err != nil { + return err + } + + return h.visorRepo.Set(*visor) +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_server_by_route.go b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_server_by_route.go new file mode 100644 index 000000000..615da7412 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_server_by_route.go @@ -0,0 +1,54 @@ +// Package commands contains commands to leave remote room +package commands + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// LeaveRemoteServerRequest Command Model +type LeaveRemoteServerRequest struct { + Route util.PKRoute +} + +// LeaveRemoteServerRequestHandler Handler Struct with Dependencies +type LeaveRemoteServerRequestHandler interface { + Handle(command LeaveRemoteServerRequest) error +} + +type leaveRemoteServerRequestHandler struct { + messengerService messenger.Service + visorRepo chat.Repository +} + +// NewLeaveRemoteServerRequestHandler Handler constructor +func NewLeaveRemoteServerRequestHandler(messengerService messenger.Service, visorRepo chat.Repository) LeaveRemoteServerRequestHandler { + return leaveRemoteServerRequestHandler{messengerService: messengerService, visorRepo: visorRepo} +} + +// Handle Handles the LeaveRemoteServerRequest request +func (h leaveRemoteServerRequestHandler) Handle(command LeaveRemoteServerRequest) error { + // Check if visor exists + visor, err := h.visorRepo.GetByPK(command.Route.Visor) + if err != nil { + return err + } + // Check if server exists + _, err = visor.GetServerByPK(command.Route.Server) + if err != nil { + return err + } + + //[]: Send 'Leave-Server-Message' to remote server so membership of it can be removed + //? this command is nearly the same as delete_local_server_by_route.go -> maybe remove one and add this part here with if visorpk=localvisor + //! -> When the 'Leave-Server-Message' does not get recognized from the server, all 'Server-Messages' still get send -> How to solve? + + // Delete server from visor + err = visor.DeleteServer(command.Route.Server) + if err != nil { + return err + } + + return h.visorRepo.Set(*visor) +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go index 49539fe76..92ba5fded 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go +++ b/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go @@ -2,14 +2,16 @@ package commands import ( - "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) // SendTextMessageRequest of SendTextMessageRequestHandler +// To send a message as p2p message the route must fulfill: PubKey of visor = PubKey of server or only the visor PubKey is defined in route +// Else you have to define the complete route type SendTextMessageRequest struct { - Pk cipher.PubKey - Msg []byte + Route util.PKRoute + Msg []byte } // SendTextMessageRequestHandler struct that allows handling SendTextMessageRequest @@ -27,9 +29,8 @@ func NewSendTextMessageRequestHandler(messengerService messenger.Service) SendTe } // Handle Handles the AddCragRequest -func (h sendTextMessageRequestHandler) Handle(req SendTextMessageRequest) error { - - err := h.messengerService.SendTextMessage(req.Pk, req.Msg) +func (h sendTextMessageRequestHandler) Handle(command SendTextMessageRequest) error { + err := h.messengerService.SendTextMessage(command.Route, command.Msg) if err != nil { return err } diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go b/cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go deleted file mode 100644 index 8bcb01124..000000000 --- a/cmd/apps/skychat/internal/app/chat/queries/get_all_chats.go +++ /dev/null @@ -1,47 +0,0 @@ -// Package queries contains queries to get all chats -package queries - -import ( - "github.com/skycoin/skywire-utilities/pkg/cipher" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" -) - -// GetAllChatsResult is the result of the GetAllChatsRequest Query -type GetAllChatsResult struct { - Pk cipher.PubKey - CType int - Info info.Info - Msgs []message.Message - Peers []peer.Peer -} - -// GetAllChatsRequestHandler Contains the dependencies of the Handler -type GetAllChatsRequestHandler interface { - Handle() ([]GetAllChatsResult, error) -} - -type getAllChatsRequestHandler struct { - repo chat.Repository -} - -// NewGetAllChatsRequestHandler Handler constructor -func NewGetAllChatsRequestHandler(repo chat.Repository) GetAllChatsRequestHandler { - return getAllChatsRequestHandler{repo: repo} -} - -// Handle Handles the query -func (h getAllChatsRequestHandler) Handle() ([]GetAllChatsResult, error) { - - res, err := h.repo.GetAll() - if err != nil { - return nil, err - } - var result []GetAllChatsResult - for _, chat := range res { - result = append(result, GetAllChatsResult{Pk: chat.GetPK(), CType: chat.GetType(), Info: chat.GetInfo(), Msgs: chat.GetMessages(), Peers: chat.GetPeers()}) - } - return result, nil -} diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go b/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go deleted file mode 100644 index 0345bbb07..000000000 --- a/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_chat.go +++ /dev/null @@ -1,49 +0,0 @@ -// Package queries contains queries to get all messages from a chat -package queries - -import ( - "github.com/skycoin/skywire-utilities/pkg/cipher" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" -) - -// GetAllMessagesFromChatRequest Model of the Handler -type GetAllMessagesFromChatRequest struct { - pk cipher.PubKey -} - -// GetAllMessagesFromChatResult is the return model of Chat Query Handlers -type GetAllMessagesFromChatResult struct { - messages []message.Message -} - -// GetAllMessagesFromChatRequestHandler provides an interfaces to handle a GetAllMessagesFromChatRequest and return a *GetAllMessagesFromChatResult -type GetAllMessagesFromChatRequestHandler interface { - Handle(query GetAllMessagesFromChatRequest) (GetAllMessagesFromChatResult, error) -} - -type getAllMessagesFromChatRequestHandler struct { - repo chat.Repository -} - -// NewGetAllMessagesFromChatRequestHandler Handler Constructor -func NewGetAllMessagesFromChatRequestHandler(repo chat.Repository) GetAllMessagesFromChatRequestHandler { - return getAllMessagesFromChatRequestHandler{repo: repo} -} - -// Handle Handlers the GetAllMessagesFromChatRequest query -func (h getAllMessagesFromChatRequestHandler) Handle(query GetAllMessagesFromChatRequest) (GetAllMessagesFromChatResult, error) { - var result GetAllMessagesFromChatResult - - chat, err := h.repo.GetByPK(query.pk) - if err != nil { - return result, err - } - - msgs := chat.GetMessages() - - if msgs != nil { - result = GetAllMessagesFromChatResult{messages: msgs} - } - return result, err -} diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_room_by_route.go b/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_room_by_route.go new file mode 100644 index 000000000..1073f5f1d --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_room_by_route.go @@ -0,0 +1,66 @@ +// Package queries contains queries to get all messages from a room +package queries + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// GetAllMessagesFromRoomRequest Model of the Handler +type GetAllMessagesFromRoomRequest struct { + Route util.PKRoute +} + +// GetAllMessagesFromRoomResult is the return model of Chat Query Handlers +type GetAllMessagesFromRoomResult struct { + Messages []message.Message +} + +// GetAllMessagesFromRoomRequestHandler provides an interfaces to handle a GetAllMessagesFromRoomRequest and return a *GetAllMessagesFromRoomResult +type GetAllMessagesFromRoomRequestHandler interface { + Handle(query GetAllMessagesFromRoomRequest) (GetAllMessagesFromRoomResult, error) +} + +type getAllMessagesFromRoomRequestHandler struct { + visorRepo chat.Repository +} + +// NewGetAllMessagesFromRoomRequestHandler Handler Constructor +func NewGetAllMessagesFromRoomRequestHandler(visorRepo chat.Repository) GetAllMessagesFromRoomRequestHandler { + return getAllMessagesFromRoomRequestHandler{visorRepo: visorRepo} +} + +// Handle Handlers the GetAllMessagesFromRoomRequest query +func (h getAllMessagesFromRoomRequestHandler) Handle(query GetAllMessagesFromRoomRequest) (GetAllMessagesFromRoomResult, error) { + var result GetAllMessagesFromRoomResult + + visor, err := h.visorRepo.GetByPK(query.Route.Visor) + if err != nil { + return result, err + } + var msgs []message.Message + + if query.Route.Server == query.Route.Visor { + p2p, err := visor.GetP2P() + if err != nil { + return result, err + } + msgs = p2p.GetMessages() + } else { + server, err := visor.GetServerByPK(query.Route.Server) + if err != nil { + return result, err + } + room, err := server.GetRoomByPK(query.Route.Room) + if err != nil { + return result, err + } + msgs = room.GetMessages() + } + + if msgs != nil { + result = GetAllMessagesFromRoomResult{Messages: msgs} + } + return result, nil +} diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_all_visors.go b/cmd/apps/skychat/internal/app/chat/queries/get_all_visors.go new file mode 100644 index 000000000..a4104a5da --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/queries/get_all_visors.go @@ -0,0 +1,46 @@ +// Package queries contains queries to get all visors +package queries + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" +) + +// GetAllVisorsResult is the result of the GetAllVisorsRequest Query +type GetAllVisorsResult struct { + Pk cipher.PubKey + P2P chat.Room + Server map[cipher.PubKey]chat.Server +} + +// GetAllVisorsRequestHandler Contains the dependencies of the Handler +type GetAllVisorsRequestHandler interface { + Handle() ([]GetAllVisorsResult, error) +} + +type getAllVisorsRequestHandler struct { + visorRepo chat.Repository +} + +// NewGetAllVisorsRequestHandler Handler constructor +func NewGetAllVisorsRequestHandler(visorRepo chat.Repository) GetAllVisorsRequestHandler { + return getAllVisorsRequestHandler{visorRepo: visorRepo} +} + +// Handle Handles the query +func (h getAllVisorsRequestHandler) Handle() ([]GetAllVisorsResult, error) { + + res, err := h.visorRepo.GetAll() + if err != nil { + return nil, err + } + var result []GetAllVisorsResult + for _, visor := range res { + p2p, err := visor.GetP2P() + if err != nil { + return nil, err + } + result = append(result, GetAllVisorsResult{Pk: visor.GetPK(), P2P: p2p, Server: visor.GetAllServer()}) + } + return result, nil +} diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go b/cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go deleted file mode 100644 index 78fdbe667..000000000 --- a/cmd/apps/skychat/internal/app/chat/queries/get_chat_by_pk.go +++ /dev/null @@ -1,55 +0,0 @@ -// Package queries contains queries to get chat by pk -package queries - -import ( - "net" - - "github.com/skycoin/skywire-utilities/pkg/cipher" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" -) - -// GetChatByPKRequest Model of the Handler -type GetChatByPKRequest struct { - Pk cipher.PubKey -} - -// GetChatByPKResult is the result of the GetChatByPKRequest Query -type GetChatByPKResult struct { - Pk cipher.PubKey - CType int - Conn net.Conn - Info info.Info - Msgs []message.Message - Peers []peer.Peer -} - -// GetChatByPKRequestHandler Contains the dependencies of the Handler -type GetChatByPKRequestHandler interface { - Handle(query GetChatByPKRequest) (GetChatByPKResult, error) -} - -type getChatByPKRequestHandler struct { - repo chat.Repository -} - -// NewGetChatByPKRequestHandler Handler constructor -func NewGetChatByPKRequestHandler(repo chat.Repository) GetChatByPKRequestHandler { - return getChatByPKRequestHandler{repo: repo} -} - -// Handle Handles the query -func (h getChatByPKRequestHandler) Handle(query GetChatByPKRequest) (GetChatByPKResult, error) { - - res, err := h.repo.GetByPK(query.Pk) - var result GetChatByPKResult - - if err != nil { - return result, err - } - result = GetChatByPKResult{Pk: res.GetPK(), CType: res.GetType(), Conn: res.GetConnection(), Info: res.GetInfo(), Msgs: res.GetMessages(), Peers: res.GetPeers()} - - return result, nil -} diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go b/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go new file mode 100644 index 000000000..32fbd7ded --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go @@ -0,0 +1,73 @@ +// Package queries contains queries to get a server by pkRoute +package queries + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// GetRoomByRouteRequest Model of the Handler +type GetRoomByRouteRequest struct { + Route util.PKRoute +} + +// GetRoomByRouteResult is the result of the GetRoomByRouteRequest Query +type GetRoomByRouteResult struct { + PKRoute util.PKRoute // P2P: send // Server: only send when room isVisible + Info info.Info // P2P: send // Server: only send when room isVisible + Msgs []message.Message // P2P: send // Server: only send to members when room isVisible + + IsVisible bool //setting to make room visible for all server-members + Type int64 //roomType --> board,chat,voice + + Members map[cipher.PubKey]peer.Peer // all members + Mods map[cipher.PubKey]bool // all moderators (can mute and unmute members, can 'delete' messages, can add pks to blacklist) + Muted map[cipher.PubKey]bool // all muted members (messages get received but not sent to other members) + Blacklist map[cipher.PubKey]bool // blacklist to block incoming connections + Whitelist map[cipher.PubKey]bool // maybe also a whitelist, so only specific members can connect +} + +// GetRoomByRouteRequestHandler Contains the dependencies of the Handler +type GetRoomByRouteRequestHandler interface { + Handle(query GetRoomByRouteRequest) (GetRoomByRouteResult, error) +} + +type getRoomByRouteRequestHandler struct { + visorRepo chat.Repository +} + +// NewGetRoomByRouteRequestHandler Handler constructor +func NewGetRoomByRouteRequestHandler(visorRepo chat.Repository) GetRoomByRouteRequestHandler { + return getRoomByRouteRequestHandler{visorRepo: visorRepo} +} + +// Handle Handles the query +func (h getRoomByRouteRequestHandler) Handle(query GetRoomByRouteRequest) (GetRoomByRouteResult, error) { + + visor, err := h.visorRepo.GetByPK(query.Route.Visor) + var result GetRoomByRouteResult + + if err != nil { + return result, err + } + + server, err := visor.GetServerByPK(query.Route.Server) + + if err != nil { + return result, err + } + + room, err := server.GetRoomByPK(query.Route.Room) + + if err != nil { + return result, err + } + + result = GetRoomByRouteResult{PKRoute: room.PKRoute, Info: room.Info, Msgs: room.Msgs, IsVisible: room.IsVisible, Type: room.Type, Members: room.Members, Mods: room.Mods, Muted: room.Muted, Blacklist: server.Blacklist, Whitelist: server.Whitelist} + + return result, nil +} diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_server_by_route.go b/cmd/apps/skychat/internal/app/chat/queries/get_server_by_route.go new file mode 100644 index 000000000..27c0ca852 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/queries/get_server_by_route.go @@ -0,0 +1,62 @@ +// Package queries contains queries to get a server by pkRoute +package queries + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// GetServerByRouteRequest Model of the Handler +type GetServerByRouteRequest struct { + Route util.PKRoute +} + +// GetServerByRouteResult is the result of the GetServerByRouteRequest Query +type GetServerByRouteResult struct { + PKRoute util.PKRoute + Info info.Info // the public info of the server + Members map[cipher.PubKey]peer.Peer // all members + Admins map[cipher.PubKey]bool // all admins + Muted map[cipher.PubKey]bool // all members muted for all rooms + Blacklist map[cipher.PubKey]bool // Blacklist to block inocming connections + Whitelist map[cipher.PubKey]bool // maybe also a whitelist, so only specific members can connect + Rooms map[cipher.PubKey]chat.Room // all rooms of the server +} + +// GetServerByRouteRequestHandler Contains the dependencies of the Handler +type GetServerByRouteRequestHandler interface { + Handle(query GetServerByRouteRequest) (GetServerByRouteResult, error) +} + +type getServerByRouteRequestHandler struct { + visorRepo chat.Repository +} + +// NewGetServerByRouteRequestHandler Handler constructor +func NewGetServerByRouteRequestHandler(visorRepo chat.Repository) GetServerByRouteRequestHandler { + return getServerByRouteRequestHandler{visorRepo: visorRepo} +} + +// Handle Handles the query +func (h getServerByRouteRequestHandler) Handle(query GetServerByRouteRequest) (GetServerByRouteResult, error) { + + visor, err := h.visorRepo.GetByPK(query.Route.Visor) + var result GetServerByRouteResult + + if err != nil { + return result, err + } + + server, err := visor.GetServerByPK(query.Route.Server) + + if err != nil { + return result, err + } + + result = GetServerByRouteResult{PKRoute: server.PKRoute, Info: server.Info, Members: server.Members, Admins: server.Admins, Muted: server.Muted, Blacklist: server.Blacklist, Whitelist: server.Whitelist, Rooms: server.Rooms} + + return result, nil +} diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_visor_by_pk.go b/cmd/apps/skychat/internal/app/chat/queries/get_visor_by_pk.go new file mode 100644 index 000000000..40f8717d4 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/queries/get_visor_by_pk.go @@ -0,0 +1,53 @@ +// Package queries contains queries to get chat by pk +package queries + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" +) + +// GetVisorByPKRequest Model of the Handler +type GetVisorByPKRequest struct { + Pk cipher.PubKey +} + +// GetVisorByPKResult is the result of the GetVisorByPKRequest Query +type GetVisorByPKResult struct { + Pk cipher.PubKey + P2P chat.Room + Server map[cipher.PubKey]chat.Server +} + +// GetVisorByPKRequestHandler Contains the dependencies of the Handler +type GetVisorByPKRequestHandler interface { + Handle(query GetVisorByPKRequest) (GetVisorByPKResult, error) +} + +type getVisorByPKRequestHandler struct { + visorRepo chat.Repository +} + +// NewGetVisorByPKRequestHandler Handler constructor +func NewGetVisorByPKRequestHandler(visorRepo chat.Repository) GetVisorByPKRequestHandler { + return getVisorByPKRequestHandler{visorRepo: visorRepo} +} + +// Handle Handles the query +func (h getVisorByPKRequestHandler) Handle(query GetVisorByPKRequest) (GetVisorByPKResult, error) { + + var result GetVisorByPKResult + + visor, err := h.visorRepo.GetByPK(query.Pk) + if err != nil { + return result, err + } + + p2p, err := visor.GetP2P() + if err != nil { + return GetVisorByPKResult{}, err + } + + result = GetVisorByPKResult{Pk: visor.GetPK(), P2P: p2p, Server: visor.GetAllServer()} + + return result, nil +} diff --git a/cmd/apps/skychat/internal/app/chat/services.go b/cmd/apps/skychat/internal/app/chat/services.go index 6dc1b337a..e887520a5 100644 --- a/cmd/apps/skychat/internal/app/chat/services.go +++ b/cmd/apps/skychat/internal/app/chat/services.go @@ -5,22 +5,32 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/chat/commands" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/chat/queries" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) // Queries Contains all available query handlers of this app type Queries struct { - GetAllChatsHandler queries.GetAllChatsRequestHandler - GetChatByPKHandler queries.GetChatByPKRequestHandler - GetAllMessagesFromChatHandler queries.GetAllMessagesFromChatRequestHandler + GetRoomByRouteHandler queries.GetRoomByRouteRequestHandler + GetServerByRouteHandler queries.GetServerByRouteRequestHandler + GetAllVisorsHandler queries.GetAllVisorsRequestHandler + GetVisorByPKHandler queries.GetVisorByPKRequestHandler + GetAllMessagesFromRoomHandler queries.GetAllMessagesFromRoomRequestHandler } // Commands Contains all available command handlers of this app type Commands struct { - AddChatHandler commands.AddChatRequestHandler - DeleteChatHandler commands.DeleteChatRequestHandler - SendTextHandler commands.SendTextMessageRequestHandler + AddLocalRoomHandler commands.AddLocalRoomRequestHandler + AddLocalServerHandler commands.AddLocalServerRequestHandler + AddRemoteRouteHandler commands.AddRemoteRouteRequestHandler + DeleteLocalRoomHandler commands.DeleteLocalRoomRequestHandler + DeleteLocalServerHandler commands.DeleteLocalServerRequestHandler + LeaveRemoteRoomHandler commands.LeaveRemoteRoomRequestHandler + LeaveRemoteServerHandler commands.LeaveRemoteServerRequestHandler + DeleteRemoteVisorHandler commands.DeleteRemoteVisorRequestHandler + SendTextMessageHandler commands.SendTextMessageRequestHandler } // ChatServices Contains the grouped queries and commands of the app layer @@ -30,17 +40,25 @@ type ChatServices struct { } // NewServices Bootstraps Application Layer dependencies -func NewServices(cliRepo client.Repository, chatRepo chat.Repository, ms messenger.Service) ChatServices { +func NewServices(cliRepo client.Repository, visorRepo chat.Repository, userRepo user.Repository, ms messenger.Service, ns notification.Service) ChatServices { return ChatServices{ Queries: Queries{ - GetAllChatsHandler: queries.NewGetAllChatsRequestHandler(chatRepo), - GetChatByPKHandler: queries.NewGetChatByPKRequestHandler(chatRepo), - GetAllMessagesFromChatHandler: queries.NewGetAllMessagesFromChatRequestHandler(chatRepo), + GetRoomByRouteHandler: queries.NewGetRoomByRouteRequestHandler(visorRepo), + GetServerByRouteHandler: queries.NewGetServerByRouteRequestHandler(visorRepo), + GetAllVisorsHandler: queries.NewGetAllVisorsRequestHandler(visorRepo), + GetVisorByPKHandler: queries.NewGetVisorByPKRequestHandler(visorRepo), + GetAllMessagesFromRoomHandler: queries.NewGetAllMessagesFromRoomRequestHandler(visorRepo), }, Commands: Commands{ - AddChatHandler: commands.NewAddChatRequestHandler(chatRepo, ms), - DeleteChatHandler: commands.NewDeleteChatRequestHandler(cliRepo, chatRepo), - SendTextHandler: commands.NewSendTextMessageRequestHandler(ms), + AddLocalRoomHandler: commands.NewAddLocalRoomRequestHandler(visorRepo,userRepo, ns), + AddLocalServerHandler: commands.NewAddLocalServerRequestHandler(visorRepo, userRepo, ns), + AddRemoteRouteHandler: commands.NewAddRemoteRouteRequestHandler(visorRepo, ms), + DeleteLocalRoomHandler: commands.NewDeleteLocalRoomRequestHandler(ms, visorRepo), + DeleteLocalServerHandler: commands.NewDeleteLocalServerRequestHandler(ms, visorRepo), + LeaveRemoteRoomHandler: commands.NewLeaveRemoteRoomRequestHandler(ms, visorRepo), + LeaveRemoteServerHandler: commands.NewLeaveRemoteServerRequestHandler(ms, visorRepo), + DeleteRemoteVisorHandler: commands.NewDeleteRemoteVisorRequestHandler(cliRepo, visorRepo), + SendTextMessageHandler: commands.NewSendTextMessageRequestHandler(ms), }, } } diff --git a/cmd/apps/skychat/internal/app/messenger/messenger.go b/cmd/apps/skychat/internal/app/messenger/messenger.go index 32a03c991..1fa3e976b 100644 --- a/cmd/apps/skychat/internal/app/messenger/messenger.go +++ b/cmd/apps/skychat/internal/app/messenger/messenger.go @@ -4,13 +4,14 @@ package messenger import ( "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) // Service interface is the interface to the service type Service interface { - Handle(pk cipher.PubKey) error + Handle(pk cipher.PubKey) Listen() - SendTextMessage(pk cipher.PubKey, msg []byte) error - SendChatRequestMessage(pk cipher.PubKey) error - SendInfoMessage(pk cipher.PubKey, info info.Info) error + SendTextMessage(route util.PKRoute, msg []byte) error + SendRouteRequestMessage(route util.PKRoute) error + SendInfoMessage(root util.PKRoute, dest util.PKRoute, info info.Info) error } diff --git a/cmd/apps/skychat/internal/app/notification/notification.go b/cmd/apps/skychat/internal/app/notification/notification.go index a520544be..c7b487aec 100644 --- a/cmd/apps/skychat/internal/app/notification/notification.go +++ b/cmd/apps/skychat/internal/app/notification/notification.go @@ -7,13 +7,14 @@ import ( "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) const ( // ErrNotifyType notifies about errors ErrNotifyType = iota - //NewAddChatNotifyType notifies about an added chat by the user - NewAddChatNotifyType + //NewAddRouteNotifyType notifies about an added route by the user + NewAddRouteNotifyType //NewChatNotifyType notifies about a new chat initiated by a peer NewChatNotifyType //NewMsgNotifyType notifies about new message @@ -30,13 +31,13 @@ type Notification struct { } // NewMsgNotification notifies the user of a new message -func NewMsgNotification(pk cipher.PubKey, msg message.Message) Notification { +func NewMsgNotification(route util.PKRoute, msg message.Message) Notification { Msg, err := json.Marshal(message.NewJSONMessage(msg)) if err != nil { fmt.Printf("Failed to marshal json: %v", err) } - clientMsg, err := json.Marshal(map[string]string{"pk": pk.Hex(), "message": string(Msg)}) + clientMsg, err := json.Marshal(map[string]string{"visorpk": route.Visor.Hex(), "serverpk": route.Server.Hex(), "roompk": route.Room.Hex(), "message": string(Msg)}) if err != nil { fmt.Printf("Failed to marshal json: %v", err) } @@ -46,14 +47,14 @@ func NewMsgNotification(pk cipher.PubKey, msg message.Message) Notification { } } -// NewAddChatNotification notifies the user about add chat request -func NewAddChatNotification(pk cipher.PubKey) Notification { - clientMsg, err := json.Marshal(map[string]string{"pk": pk.Hex()}) +// NewAddRouteNotification notifies the user about added route +func NewAddRouteNotification(route util.PKRoute) Notification { + clientMsg, err := json.Marshal(map[string]string{"visorpk": route.Visor.Hex(), "serverpk": route.Server.Hex(), "roompk": route.Room.Hex()}) if err != nil { fmt.Printf("Failed to marshal json: %v", err) } return Notification{ - Type: NewAddChatNotifyType, + Type: NewAddRouteNotifyType, Message: string(clientMsg), } } @@ -72,6 +73,8 @@ func NewChatNotification(pk cipher.PubKey) Notification { // Service sends Notification type Service interface { + InitChannel() + DeferChannel() GetChannel() chan string Notify(notification Notification) error } diff --git a/cmd/apps/skychat/internal/app/services.go b/cmd/apps/skychat/internal/app/services.go index 0a59ad80d..080055286 100644 --- a/cmd/apps/skychat/internal/app/services.go +++ b/cmd/apps/skychat/internal/app/services.go @@ -19,9 +19,9 @@ type Services struct { } // NewServices Bootstraps Application Layer dependencies -func NewServices(cliRepo client.Repository, usrRepo user.Repository, chatRepo chat.Repository, notifyService notification.Service, ms messenger.Service) Services { +func NewServices(cliRepo client.Repository, usrRepo user.Repository, visorRepo chat.Repository, notifyService notification.Service, ms messenger.Service) Services { return Services{ NotificationService: notifyService, - ChatServices: chatservices.NewServices(cliRepo, chatRepo, ms), - UserServices: userservices.NewServices(usrRepo, chatRepo)} + ChatServices: chatservices.NewServices(cliRepo, visorRepo, usrRepo, ms, notifyService), + UserServices: userservices.NewServices(usrRepo, ms)} } diff --git a/cmd/apps/skychat/internal/app/user/commands/add_peer.go b/cmd/apps/skychat/internal/app/user/commands/add_peer.go new file mode 100644 index 000000000..df939499c --- /dev/null +++ b/cmd/apps/skychat/internal/app/user/commands/add_peer.go @@ -0,0 +1,41 @@ +// Package commands contains commands to add peers of a user +package commands + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" +) + +// AddPeerRequest of AddPeerRequestHandler +type AddPeerRequest struct { + Info info.Info + Alias string +} + +// AddPeerRequestHandler struct that allows handling AddPeerRequest +type AddPeerRequestHandler interface { + Handle(command AddPeerRequest) error +} + +type addPeerRequestHandler struct { + usrRepo user.Repository +} + +// NewAddPeerRequestHandler Initializes an AddPeerRequestHandler +func NewAddPeerRequestHandler(usrRepo user.Repository) AddPeerRequestHandler { + return addPeerRequestHandler{usrRepo: usrRepo} +} + +// Handle Handles the AddPeerRequest +func (h addPeerRequestHandler) Handle(req AddPeerRequest) error { + + pUsr, err := h.usrRepo.GetUser() + if err != nil { + return err + //TODO:(ersonp) check if something else needs to be done/closed on returning an error + } + + pUsr.GetPeerbook().AddPeer(req.Info, req.Alias) + + return h.usrRepo.SetUser(pUsr) +} diff --git a/cmd/apps/skychat/internal/app/user/commands/delete_peer.go b/cmd/apps/skychat/internal/app/user/commands/delete_peer.go new file mode 100644 index 000000000..656da869a --- /dev/null +++ b/cmd/apps/skychat/internal/app/user/commands/delete_peer.go @@ -0,0 +1,40 @@ +// Package commands contains commands to delete peers of a user +package commands + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" +) + +// DeletePeerRequest of DeletePeerRequestHandler +type DeletePeerRequest struct { + PK cipher.PubKey +} + +// DeletePeerRequestHandler struct that allows handling DeletePeerRequest +type DeletePeerRequestHandler interface { + Handle(command DeletePeerRequest) error +} + +type deletePeerRequestHandler struct { + usrRepo user.Repository +} + +// NewDeletePeerRequestHandler Initializes an DeletePeerRequestHandler +func NewDeletePeerRequestHandler(usrRepo user.Repository) DeletePeerRequestHandler { + return deletePeerRequestHandler{usrRepo: usrRepo} +} + +// Handle Handles the DeletePeerRequest +func (h deletePeerRequestHandler) Handle(req DeletePeerRequest) error { + + pUsr, err := h.usrRepo.GetUser() + if err != nil { + //TODO:(ersonp) check if something else needs to be done/closed on returning an error + return err + } + + pUsr.GetPeerbook().DeletePeer(req.PK) + + return h.usrRepo.SetUser(pUsr) +} diff --git a/cmd/apps/skychat/internal/app/user/commands/set_info.go b/cmd/apps/skychat/internal/app/user/commands/set_info.go index 04f711f38..b6572d6fe 100644 --- a/cmd/apps/skychat/internal/app/user/commands/set_info.go +++ b/cmd/apps/skychat/internal/app/user/commands/set_info.go @@ -4,6 +4,7 @@ package commands import ( "errors" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) @@ -21,12 +22,13 @@ type SetInfoRequestHandler interface { } type setInfoRequestHandler struct { - usrRepo user.Repository + messengerService messenger.Service + usrRepo user.Repository } // NewSetInfoRequestHandler Initializes an SetInfoHandler -func NewSetInfoRequestHandler(usrRepo user.Repository) SetInfoRequestHandler { - return setInfoRequestHandler{usrRepo: usrRepo} +func NewSetInfoRequestHandler(messengerService messenger.Service, usrRepo user.Repository) SetInfoRequestHandler { + return setInfoRequestHandler{messengerService: messengerService, usrRepo: usrRepo} } // Handle Handles the SetInfoRequest @@ -41,7 +43,7 @@ func (h setInfoRequestHandler) Handle(req SetInfoRequest) error { pUsr.SetInfo(i) - //TODO:Send info to peers that the info was updated + //TODO:Send info to peers and servers that the info was updated return h.usrRepo.SetUser(pUsr) } diff --git a/cmd/apps/skychat/internal/app/user/commands/set_peer.go b/cmd/apps/skychat/internal/app/user/commands/set_peer.go new file mode 100644 index 000000000..ba01ff636 --- /dev/null +++ b/cmd/apps/skychat/internal/app/user/commands/set_peer.go @@ -0,0 +1,40 @@ +// Package commands contains commands to set peers of a user +package commands + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" +) + +// SetPeerRequest of SetPeerRequestHandler +type SetPeerRequest struct { + Peer peer.Peer +} + +// SetPeerRequestHandler struct that allows handling SetPeerRequest +type SetPeerRequestHandler interface { + Handle(command SetPeerRequest) error +} + +type setPeerRequestHandler struct { + usrRepo user.Repository +} + +// NewSetPeerRequestHandler Initializes an SetPeerRequestHandler +func NewSetPeerRequestHandler(usrRepo user.Repository) SetPeerRequestHandler { + return setPeerRequestHandler{usrRepo: usrRepo} +} + +// Handle Handles the SetPeerRequest +func (h setPeerRequestHandler) Handle(req SetPeerRequest) error { + + pUsr, err := h.usrRepo.GetUser() + if err != nil { + //TODO:(ersonp) check if something else needs to be done/closed on returning an error + return err + } + + pUsr.GetPeerbook().SetPeer(req.Peer) + + return h.usrRepo.SetUser(pUsr) +} diff --git a/cmd/apps/skychat/internal/app/user/commands/set_settings.go b/cmd/apps/skychat/internal/app/user/commands/set_settings.go index fbf5c4acc..6b85e0032 100644 --- a/cmd/apps/skychat/internal/app/user/commands/set_settings.go +++ b/cmd/apps/skychat/internal/app/user/commands/set_settings.go @@ -31,7 +31,6 @@ func (h setSettingsRequestHandler) Handle(req SetSettingsRequest) error { pUsr, err := h.usrRepo.GetUser() if err != nil { - //TODO: implement error //TODO:(ersonp) check if something else needs to be done/closed on returning an error return err } diff --git a/cmd/apps/skychat/internal/app/user/queries/get_peerbook.go b/cmd/apps/skychat/internal/app/user/queries/get_peerbook.go new file mode 100644 index 000000000..2cb3c49d6 --- /dev/null +++ b/cmd/apps/skychat/internal/app/user/queries/get_peerbook.go @@ -0,0 +1,39 @@ +// Package queries contains queries to get peers of a user +package queries + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" +) + +// GetUserPeerbookResult is the result of the GetUserPeerbookRequest Query +type GetUserPeerbookResult struct { + Peerbook peer.Peerbook +} + +// GetUserPeerbookRequestHandler Contains the dependencies of the Handler +type GetUserPeerbookRequestHandler interface { + Handle() (*GetUserPeerbookResult, error) +} + +type getUserPeersRequestHandler struct { + usrRepo user.Repository +} + +// NewGetUserPeerbookRequestHandler Handler constructor +func NewGetUserPeerbookRequestHandler(usrRepo user.Repository) GetUserPeerbookRequestHandler { + return getUserPeersRequestHandler{usrRepo: usrRepo} +} + +// Handle Handles the query +func (h getUserPeersRequestHandler) Handle() (*GetUserPeerbookResult, error) { + usr, err := h.usrRepo.GetUser() + var result *GetUserPeerbookResult + + if usr != nil && err == nil { + + result = &GetUserPeerbookResult{Peerbook: *usr.GetPeerbook()} + } + + return result, nil +} diff --git a/cmd/apps/skychat/internal/app/user/queries/get_settings.go b/cmd/apps/skychat/internal/app/user/queries/get_settings.go index e121632d9..d902a0736 100644 --- a/cmd/apps/skychat/internal/app/user/queries/get_settings.go +++ b/cmd/apps/skychat/internal/app/user/queries/get_settings.go @@ -2,12 +2,13 @@ package queries import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) // GetUserSettingsResult is the result of the GetUserSettingsRequest Query type GetUserSettingsResult struct { - Blacklist []string + Blacklist []cipher.PubKey } // GetUserSettingsRequestHandler Contains the dependencies of the Handler @@ -32,15 +33,7 @@ func (h getUserSettingsRequestHandler) Handle() (*GetUserSettingsResult, error) if usr != nil && err == nil { s := usr.GetSettings() - var blacklist []string - for _, element := range s.GetBlacklist() { - blacklist = append(blacklist, element.Hex()) - } - if blacklist == nil { - blacklist = []string{""} - } - - result = &GetUserSettingsResult{Blacklist: blacklist} + result = &GetUserSettingsResult{Blacklist: s.GetBlacklist()} } return result, nil diff --git a/cmd/apps/skychat/internal/app/user/services.go b/cmd/apps/skychat/internal/app/user/services.go index 600bb7847..d2de74824 100644 --- a/cmd/apps/skychat/internal/app/user/services.go +++ b/cmd/apps/skychat/internal/app/user/services.go @@ -2,20 +2,24 @@ package userservices import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/user/commands" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/user/queries" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) // Queries Contains all available query handlers of this app type Queries struct { + GetUserPeerBookHandler queries.GetUserPeerbookRequestHandler GetUserInfoHandler queries.GetUserInfoRequestHandler GetUserSettingsHandler queries.GetUserSettingsRequestHandler } // Commands Contains all available command handlers of this app type Commands struct { + AddPeerHandler commands.AddPeerRequestHandler + DeletePeerHandler commands.DeletePeerRequestHandler + SetPeerHandler commands.SetPeerRequestHandler SetInfoHandler commands.SetInfoRequestHandler SetSettingsHandler commands.SetSettingsRequestHandler } @@ -27,15 +31,19 @@ type UserServices struct { } // NewServices Bootstraps Application Layer dependencies -func NewServices(cliRepo user.Repository, chatRepo chat.Repository) UserServices { +func NewServices(usrRepo user.Repository, ms messenger.Service) UserServices { return UserServices{ Queries: Queries{ - GetUserInfoHandler: queries.NewGetUserInfoRequestHandler(cliRepo), - GetUserSettingsHandler: queries.NewGetUserSettingsRequestHandler(cliRepo), + GetUserPeerBookHandler: queries.NewGetUserPeerbookRequestHandler(usrRepo), + GetUserInfoHandler: queries.NewGetUserInfoRequestHandler(usrRepo), + GetUserSettingsHandler: queries.NewGetUserSettingsRequestHandler(usrRepo), }, Commands: Commands{ - SetInfoHandler: commands.NewSetInfoRequestHandler(cliRepo), - SetSettingsHandler: commands.NewSetSettingsRequestHandler(cliRepo), + AddPeerHandler: commands.NewAddPeerRequestHandler(usrRepo), + DeletePeerHandler: commands.NewDeletePeerRequestHandler(usrRepo), + SetPeerHandler: commands.NewSetPeerRequestHandler(usrRepo), + SetInfoHandler: commands.NewSetInfoRequestHandler(ms, usrRepo), + SetSettingsHandler: commands.NewSetSettingsRequestHandler(usrRepo), }, } } diff --git a/cmd/apps/skychat/internal/domain/chat/chat.go b/cmd/apps/skychat/internal/domain/chat/chat.go deleted file mode 100644 index 34072919a..000000000 --- a/cmd/apps/skychat/internal/domain/chat/chat.go +++ /dev/null @@ -1,101 +0,0 @@ -// Package chat contains chat related code for domain -package chat - -import ( - "net" - - "github.com/skycoin/skywire-utilities/pkg/cipher" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" -) - -const ( - errChatType = iota - // GroupChat is a group chat - GroupChat - // PeerChat is a direct message - PeerChat -) - -// Chat is the struct of the chat itself -type Chat struct { - PK cipher.PubKey - CType int - Conn net.Conn - Info info.Info - Msgs []message.Message - - //GroupChat - peers []peer.Peer -} - -// GetPK gets the public key -func (c *Chat) GetPK() cipher.PubKey { - return c.PK -} - -// GetType gets the chat type -func (c *Chat) GetType() int { - return c.CType -} - -// GetConnection returns net.Conn -func (c *Chat) GetConnection() net.Conn { - return c.Conn -} - -// GetInfo returns info.Info -func (c *Chat) GetInfo() info.Info { - return c.Info -} - -// GetMessages returns []message.Message -func (c *Chat) GetMessages() []message.Message { - return c.Msgs -} - -// GetPeers returns []peer.Peer -func (c *Chat) GetPeers() []peer.Peer { - return c.peers -} - -//Setter - -// SetConnection sets the connection type used -func (c *Chat) SetConnection(Conn net.Conn) { - c.Conn = Conn -} - -// DeleteConnection clears the connection -func (c *Chat) DeleteConnection() { - c.Conn = nil -} - -// AddMessage Add the given message to the given chat -func (c *Chat) AddMessage(m message.Message) { - c.Msgs = append(c.Msgs, m) -} - -// Constructors - -// NewUndefinedChat creates undefined empty chat to a public key -func NewUndefinedChat(PK cipher.PubKey) Chat { - c := Chat{} - c.PK = PK - c.CType = errChatType - c.Conn = nil - c.Info = info.NewDefaultInfo() - c.Msgs = []message.Message{} - return c -} - -// NewChat creates a new chat -func NewChat(PK cipher.PubKey, CType int, i info.Info, Msgs []message.Message) Chat { - c := Chat{} - c.PK = PK - c.CType = CType - c.Info = i - c.Msgs = Msgs - return c -} diff --git a/cmd/apps/skychat/internal/domain/chat/room.go b/cmd/apps/skychat/internal/domain/chat/room.go new file mode 100644 index 000000000..d89842d7c --- /dev/null +++ b/cmd/apps/skychat/internal/domain/chat/room.go @@ -0,0 +1,309 @@ +package chat + +import ( + "fmt" + "net" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// types of rooms +const ( + // ErrRoomType is used to handle room errors types + ErrRoomType = iota + // ChatRoomType is used to define as chat room + ChatRoomType + // BoardRoomType is used to define as board + BoardRoomType + // VoiceRoomType is used to define as voice chat + // VoiceRoom +) + +const DefaultRoomType = ChatRoomType + +// Room defines a room that can be of different types +// A Room always is a part of a server +// A Server is always a part of a visor +// So you can think of this hierarchial structure: +// (Visor (PublicKey1)) +// -> Server1 (PublicKey1.1) +// -> Room1 (PublicKey1.1.1) +// -> Room2 (PublicKey1.1.2) +// -> Room3 (PublicKey1.1.2) +// -> Server2 (PublicKey1.2) +// -> Room1 (PublicKey1.2.1) +type Room struct { + //P2P & Server + PKRoute util.PKRoute // P2P: send // Server: only send when room isVisible + Info info.Info // P2P: send // Server: only send when room isVisible + Msgs []message.Message // P2P: send // Server: only send to members when room isVisible + + //Server + IsVisible bool //setting to make room visible for all server-members + Type int64 //roomType --> board,chat,voice + + //Private (only send to room members) + Members map[cipher.PubKey]peer.Peer // all members + Mods map[cipher.PubKey]bool // all moderators (can mute and unmute members, can 'delete' messages, can add pks to blacklist) + Muted map[cipher.PubKey]bool // all muted members (messages get received but not sent to other members) + Blacklist map[cipher.PubKey]bool // blacklist to block incoming connections + Whitelist map[cipher.PubKey]bool // maybe also a whitelist, so only specific members can connect + + //only for local server + Conns map[cipher.PubKey]net.Conn // active peer connections +} + +// GetPKRoute returns the PKRoute +func (r *Room) GetPKRoute() util.PKRoute { + return r.PKRoute +} + +// SetInfo sets the room's rinfo to the given info +func (r *Room) SetInfo(info info.Info) { + r.Info = info +} + +// GetInfo returns the info of the room +func (r *Room) GetInfo() info.Info { + return r.Info +} + +// AddMessage adds the given message to the messages +func (r *Room) AddMessage(m message.Message) { + r.Msgs = append(r.Msgs, m) +} + +//[]:SetMessages to update messages + +// GetMessages returns all messages +func (r *Room) GetMessages() []message.Message { + return r.Msgs +} + +// GetIsVisible returns if the room is visible +func (r *Room) GetIsVisible() bool { + return r.IsVisible +} + +// SetIsVisible sets if the room is visible +func (r *Room) SetIsVisible(isVisible bool) { + r.IsVisible = isVisible +} + +// GetType returns the room's type +func (r *Room) GetType() int64 { + return r.Type +} + +// SetType sets the room's type +func (r *Room) SetType(t int64) { + r.Type = t +} + +// AddMember adds the given peer to the room +func (r *Room) AddMember(peer peer.Peer) error { + _, err := r.GetMemberByPK(peer.GetPK()) + if err != nil { + r.Members[peer.GetPK()] = peer + return nil + } + return fmt.Errorf("peer already member of room") +} + +// DeleteMember deletes the member with the given pk +func (r *Room) DeleteMember(pk cipher.PubKey) error { + _, err := r.GetMemberByPK(pk) + if err != nil { + return nil //we don't need to send an error if the member does not even exist + } + delete(r.Members, pk) + return nil +} + +// GetMemberByPK returns the the member mapped by pk if available and returns err if no member with given pk exists +func (r *Room) GetMemberByPK(pk cipher.PubKey) (*peer.Peer, error) { + if member, ok := r.Members[pk]; ok { + return &member, nil + } + return nil, fmt.Errorf("member does not exist") +} + +// SetMember updates the given peer +func (r *Room) SetMember(peer peer.Peer) error { + //check if peer exists + if _, ok := r.Members[peer.GetPK()]; ok { + r.Members[peer.GetPK()] = peer + return nil + } + return fmt.Errorf("member does not exist") +} + +// GetAllMembers returns all members (peers) of the room +func (r *Room) GetAllMembers() map[cipher.PubKey]peer.Peer { + return r.Members +} + +// AddMod adds the given pk (peer) as moderator of the room +func (r *Room) AddMod(pk cipher.PubKey) error { + //check if peer is already mod + if _, ok := r.Mods[pk]; ok { + return fmt.Errorf("peer is already mod") + } + r.Mods[pk] = true + return nil +} + +// DeleteMod removes the given pk (peer) as moderator from the room +func (r *Room) DeleteMod(pk cipher.PubKey) error { + //check if peer is mod + if _, ok := r.Mods[pk]; ok { + delete(r.Mods, pk) + return nil + } + return fmt.Errorf("member is no mod") //? handle as error? +} + +// GetAllMods returns all moderators +func (r *Room) GetAllMods() map[cipher.PubKey]bool { + return r.Mods +} + +// AddMuted mutes the given pk (peer) +func (r *Room) AddMuted(pk cipher.PubKey) error { + //check if peer already muted + if _, ok := r.Muted[pk]; ok { + return fmt.Errorf("peer already muted") + } + r.Muted[pk] = true //?maybe one day make map of type "Time-stamp" or something similar to enable timed mutes + return nil +} + +// DeleteMuted removes the given pk (peer) from muted status +func (r *Room) DeleteMuted(pk cipher.PubKey) error { + //check if peer is muted + if _, ok := r.Muted[pk]; ok { + delete(r.Muted, pk) + return nil + } + return fmt.Errorf("member is not muted") //? handle as error? +} + +// GetAllMuted returns all muted members/peers +func (r *Room) GetAllMuted(pk cipher.PubKey) map[cipher.PubKey]bool { + return r.Muted +} + +// AddToBlacklist blocks the given pk from joining the room +func (r *Room) AddToBlacklist(pk cipher.PubKey) error { + //check if peer already blacklisted + if _, ok := r.Blacklist[pk]; ok { + return fmt.Errorf("peer already blacklisted") + } + r.Blacklist[pk] = true + return nil +} + +// DeleteFromBlacklist unblocks the given pk from joining the room +func (r *Room) DeleteFromBlacklist(pk cipher.PubKey) error { + //check if peer is blacklisted + if _, ok := r.Blacklist[pk]; ok { + delete(r.Blacklist, pk) + return nil + } + return fmt.Errorf("member is not blacklisted") //? handle as error? +} + +// GetBlacklist returns all blacklisted/banned members/peers +func (r *Room) GetBlacklist() map[cipher.PubKey]bool { + return r.Blacklist +} + +// AddToWhitelist adds a pk to the join-only-list of the room +func (r *Room) AddToWhitelist(pk cipher.PubKey) error { + //check if peer already whitelisted + if _, ok := r.Whitelist[pk]; ok { + return fmt.Errorf("peer already whitelisted") + } + r.Whitelist[pk] = true + return nil +} + +// DeleteFromWhitelist removes a pk from the join-only-list of the room +func (r *Room) DeleteFromWhitelist(pk cipher.PubKey) error { + //check if peer is whitelisted + if _, ok := r.Whitelist[pk]; ok { + delete(r.Whitelist, pk) + return nil + } + return fmt.Errorf("member is not whitelisted") //? handle as error? +} + +// GetWhitelist returns all whitelisted members/peers +func (r *Room) GetWhitelist(pk cipher.PubKey) map[cipher.PubKey]bool { + return r.Whitelist +} + +// NewDefaultLocalRoom returns a new default local room +func NewDefaultLocalRoom(roomRoute util.PKRoute) Room { + r := Room{} + r.PKRoute = roomRoute + r.Info = info.NewDefaultInfo() + //Msgs + r.IsVisible = false + r.Type = ChatRoomType + + r.Members = make(map[cipher.PubKey]peer.Peer) + r.Mods = make(map[cipher.PubKey]bool) + r.Muted = make(map[cipher.PubKey]bool) + r.Blacklist = make(map[cipher.PubKey]bool) + r.Whitelist = make(map[cipher.PubKey]bool) + r.Conns = make(map[cipher.PubKey]net.Conn) + + return r +} + +// NewDefaultP2PRoom returns a new default p2p room +func NewDefaultP2PRoom(pk cipher.PubKey) Room { + r := Room{} + r.PKRoute = util.NewP2PRoute(pk) + r.Info = info.NewDefaultInfo() + r.IsVisible = true + r.Type = ChatRoomType + + r.Members = make(map[cipher.PubKey]peer.Peer) + r.Mods = make(map[cipher.PubKey]bool) + r.Muted = make(map[cipher.PubKey]bool) + r.Blacklist = make(map[cipher.PubKey]bool) + r.Whitelist = make(map[cipher.PubKey]bool) + r.Conns = make(map[cipher.PubKey]net.Conn) + + return r +} + +// NewLocalRoom returns a new local room +func NewLocalRoom(roomRoute util.PKRoute, i info.Info, t int64) Room { + r := Room{} + r.PKRoute = roomRoute + r.Info = i + //[]:maybe delete when a picture can be set from the ui? + if i.Img == "" { + r.Info.Img = info.DefaultImage + } + r.Info.Pk = roomRoute.Room + //Msgs + r.IsVisible = false + r.Type = t + + r.Members = make(map[cipher.PubKey]peer.Peer) + r.Mods = make(map[cipher.PubKey]bool) + r.Muted = make(map[cipher.PubKey]bool) + r.Blacklist = make(map[cipher.PubKey]bool) + r.Whitelist = make(map[cipher.PubKey]bool) + r.Conns = make(map[cipher.PubKey]net.Conn) + + return r +} diff --git a/cmd/apps/skychat/internal/domain/chat/server.go b/cmd/apps/skychat/internal/domain/chat/server.go new file mode 100644 index 000000000..2eb4fc36f --- /dev/null +++ b/cmd/apps/skychat/internal/domain/chat/server.go @@ -0,0 +1,344 @@ +package chat + +import ( + "fmt" + "net" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// Server defines a server for a collection of rooms +type Server struct { + //Public + PKRoute util.PKRoute + Info info.Info // the public info of the server + + Members map[cipher.PubKey]peer.Peer // all members + Admins map[cipher.PubKey]bool // all admins (can do everything that mods can do but on all rooms and can hire and unhire mods, can add pks to blacklist) + Muted map[cipher.PubKey]bool // all members muted for all rooms + Blacklist map[cipher.PubKey]bool // Blacklist to block inocming connections + Whitelist map[cipher.PubKey]bool // maybe also a whitelist, so only specific members can connect + Rooms map[cipher.PubKey]Room // all rooms of the server + + //? Maybe also add a Messages []message.Message here for "logging purposes" e.g. "Requested to join server", "Join Request accepted", "Request to join Room" etc. + + //only for local server + Conns map[cipher.PubKey]net.Conn // active peer connections +} + +// AddMessage adds a message to the server +func (s *Server) AddMessage(m message.Message) { + r := s.Rooms[m.Dest.Room] + r.AddMessage(m) +} + +// GetPKRoute returns the PKRoute +func (s *Server) GetPKRoute() util.PKRoute { + return s.PKRoute +} + +// SetInfo sets the server's rinfo to the given info +func (s *Server) SetInfo(info info.Info) { + s.Info = info +} + +// GetInfo returns the info of the server +func (s *Server) GetInfo() info.Info { + return s.Info +} + +// AddRoom adds the given room to the server +func (s *Server) AddRoom(room Room) error { + _, err := s.GetRoomByPK(room.PKRoute.Room) + if err != nil { + s.Rooms[room.PKRoute.Room] = room + return nil + + } + return fmt.Errorf("room already exists in server") +} + +// DeleteRoom removes the given room from the server +func (s *Server) DeleteRoom(pk cipher.PubKey) error { + _, err := s.GetRoomByPK(pk) + if err != nil { + return fmt.Errorf("room does not exist") //? handle as error? + + } + delete(s.Rooms, pk) + return nil + +} + +// GetRoomByPK returns the the room mapped by pk if available and returns err if no room with given pk is available +func (s *Server) GetRoomByPK(pk cipher.PubKey) (*Room, error) { + if room, ok := s.Rooms[pk]; ok { + return &room, nil + } + return nil, fmt.Errorf("no room with pk %s found in visor %s and server %s", pk.Hex(), s.PKRoute.Visor, s.PKRoute.Server) +} + +// SetRoom updates the given room +func (s *Server) SetRoom(room Room) error { + //check if room exists + if _, ok := s.Rooms[room.PKRoute.Room]; ok { + s.Rooms[room.PKRoute.Room] = room + return nil + } + return fmt.Errorf("no room with pk %s found in server %s", room.PKRoute.Room.Hex(), s.PKRoute.Server) +} + +// GetAllRooms returns a room-map of all rooms +func (s *Server) GetAllRooms() map[cipher.PubKey]Room { + return s.Rooms +} + +// GetAllRoomsBoolMap returns a bool-map of all rooms +func (s *Server) GetAllRoomsBoolMap() map[cipher.PubKey]bool { + r := make(map[cipher.PubKey]bool) + for k := range s.Rooms { + r[k] = true + } + return r +} + +// AddMember adds the given peer to the server +func (s *Server) AddMember(peer peer.Peer) error { + _, err := s.GetMemberByPK(peer.GetPK()) + if err != nil { + return fmt.Errorf("peer already member of server") + } + s.Members[peer.GetPK()] = peer + return nil +} + +// DeleteMember deletes the member with the given pk +func (s *Server) DeleteMember(pk cipher.PubKey) error { + _, err := s.GetMemberByPK(pk) + if err != nil { + delete(s.Members, pk) + return nil + } + return fmt.Errorf("member does not exist") //? handle as error? +} + +// GetMemberByPK returns the the member mapped by pk if available and returns err if no member with given pk exists +func (s *Server) GetMemberByPK(pk cipher.PubKey) (*peer.Peer, error) { + if member, ok := s.Members[pk]; ok { + return &member, nil + } + return nil, fmt.Errorf("member does not exist") +} + +// SetMember updates the given peer +func (s *Server) SetMember(peer peer.Peer) error { + //check if peer exists + if _, ok := s.Members[peer.GetPK()]; ok { + s.Members[peer.GetPK()] = peer + return nil + } + return fmt.Errorf("member does not exist") +} + +// GetAllMembers returns all members (peers) of the server +func (s *Server) GetAllMembers() map[cipher.PubKey]peer.Peer { + return s.Members +} + +// SetMemberInfo sets the given info of the member inside the server and all rooms +func (s *Server) SetMemberInfo(i info.Info) error { + //set member info in server + member, err := s.GetMemberByPK(i.GetPK()) + if err != nil { + return err + } + member.SetInfo(i) + err = s.SetMember(*member) + if err != nil { + return err + } + + //set member info in rooms + for _, room := range s.Rooms { + room.GetMemberByPK(i.GetPK()) + if err != nil { + return err + } + member.SetInfo(i) + err = room.SetMember(*member) + if err != nil { + return err + } + } + + return nil +} + +// AddAdmin adds the given pk (peer) as admin of the server +func (s *Server) AddAdmin(pk cipher.PubKey) error { + //check if peer is already admin + if _, ok := s.Admins[pk]; ok { + return fmt.Errorf("peer is already admin") + } + s.Admins[pk] = true + return nil +} + +// DeleteAdmin removes the given pk (peer) as admin from the server +func (s *Server) DeleteAdmin(pk cipher.PubKey) error { + //check if peer is admin + if _, ok := s.Admins[pk]; ok { + delete(s.Admins, pk) + return nil + } + return fmt.Errorf("member is no admin") //? handle as error? +} + +// GetAllAdmin returns all admins +func (s *Server) GetAllAdmin() map[cipher.PubKey]bool { + return s.Admins +} + +// AddMuted mutes the given pk (peer) +func (s *Server) AddMuted(pk cipher.PubKey) error { + //check if peer already muted + if _, ok := s.Muted[pk]; ok { + return fmt.Errorf("peer already muted") + } + s.Muted[pk] = true //?maybe one day make map of type "Time-stamp" or something similar to enable timed mutes + return nil +} + +// DeleteMuted removes the given pk (peer) from muted status +func (s *Server) DeleteMuted(pk cipher.PubKey) error { + //check if peer is muted + if _, ok := s.Muted[pk]; ok { + delete(s.Muted, pk) + return nil + } + return fmt.Errorf("member is not muted") //? handle as error? +} + +// GetAllMuted returns all muted members/peers +func (s *Server) GetAllMuted(pk cipher.PubKey) map[cipher.PubKey]bool { + return s.Muted +} + +// AddToBlacklist blocks the given pk from joining the server +func (s *Server) AddToBlacklist(pk cipher.PubKey) error { + //check if peer already blacklisted + if _, ok := s.Blacklist[pk]; ok { + return fmt.Errorf("peer already blacklisted") + } + s.Blacklist[pk] = true + return nil +} + +// DeleteFromBlacklist unblocks the given pk from joining the server +func (s *Server) DeleteFromBlacklist(pk cipher.PubKey) error { + //check if peer is blacklisted + if _, ok := s.Blacklist[pk]; ok { + delete(s.Blacklist, pk) + return nil + } + return fmt.Errorf("member is not blacklisted") //? handle as error? +} + +// GetBlacklist returns all blacklisted/banned members/peers +func (s *Server) GetBlacklist() map[cipher.PubKey]bool { + return s.Blacklist +} + +// AddToWhitelist adds a pk to the join-only-list of the server +func (s *Server) AddToWhitelist(pk cipher.PubKey) error { + //check if peer already whitelisted + if _, ok := s.Whitelist[pk]; ok { + return fmt.Errorf("peer already whitelisted") + } + s.Whitelist[pk] = true + return nil +} + +// DeleteFromWhitelist removes a pk from the join-only-list of the server +func (s *Server) DeleteFromWhitelist(pk cipher.PubKey) error { + //check if peer is whitelisted + if _, ok := s.Whitelist[pk]; ok { + delete(s.Whitelist, pk) + return nil + } + return fmt.Errorf("member is not whitelisted") //? handle as error? +} + +// GetWhitelist returns all whitelisted members/peers +func (s *Server) GetWhitelist(pk cipher.PubKey) map[cipher.PubKey]bool { + return s.Whitelist +} + +// AddConn adds the given net.Conn to the server to keep track of connected peers +func (s *Server) AddConn(pk cipher.PubKey, conn net.Conn) error { + //check if conn already added + if _, ok := s.Conns[pk]; ok { + return fmt.Errorf("conn already added") + } + s.Conns[pk] = conn + return nil +} + +// DeleteConn removes the given net.Conn from the server +func (s *Server) DeleteConn(pk cipher.PubKey) error { + //check if conn is added + if _, ok := s.Conns[pk]; ok { + delete(s.Conns, pk) + return nil + } + return fmt.Errorf("pk has no connection") //? handle as error? +} + +// GetAllConns returns all connections +func (s *Server) GetAllConns() map[cipher.PubKey]net.Conn { + return s.Conns +} + +// GetConnByPK returns connection of PK +func (s *Server) GetConnByPK(pk cipher.PubKey) (*net.Conn, error) { + if conn, ok := s.Conns[pk]; ok { + return &conn, nil + } + return nil, fmt.Errorf("connection of pk does not exist") +} + +// NewLocalServer returns a new local server +func NewLocalServer(serverRoute util.PKRoute, i info.Info) (*Server, error) { + s := Server{} + s.PKRoute = serverRoute + s.Info = i + + s.Members = make(map[cipher.PubKey]peer.Peer) + s.Admins = make(map[cipher.PubKey]bool) + s.Muted = make(map[cipher.PubKey]bool) + s.Blacklist = make(map[cipher.PubKey]bool) + s.Whitelist = make(map[cipher.PubKey]bool) + s.Rooms = make(map[cipher.PubKey]Room) + s.Conns = make(map[cipher.PubKey]net.Conn) + + return &s, nil +} + +// NewServer returns a new server +func NewServer(route util.PKRoute, info info.Info, members map[cipher.PubKey]peer.Peer, admins map[cipher.PubKey]bool, muted map[cipher.PubKey]bool, blacklist map[cipher.PubKey]bool, whitelist map[cipher.PubKey]bool, rooms map[cipher.PubKey]Room) *Server { + s := Server{} + s.PKRoute = route + s.Info = info + s.Members = members + s.Admins = admins + s.Muted = muted + s.Blacklist = blacklist + s.Whitelist = whitelist + s.Rooms = rooms + + return &s +} diff --git a/cmd/apps/skychat/internal/domain/chat/visor.go b/cmd/apps/skychat/internal/domain/chat/visor.go new file mode 100644 index 000000000..c75e09012 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/chat/visor.go @@ -0,0 +1,178 @@ +package chat + +import ( + "fmt" + "net" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" +) + +// Visor defines a remote or the local visor with all its servers +type Visor struct { + PK cipher.PubKey + Conn net.Conn + + //P2P or direct chat + P2P Room + + //Server + Server map[cipher.PubKey]Server +} + +// GetPK gets the public key +func (v *Visor) GetPK() cipher.PubKey { + return v.PK +} + +// GetConnection returns net.Conn +func (v *Visor) GetConnection() net.Conn { + return v.Conn +} + +// GetP2P returns peer to peer Room +func (v *Visor) GetP2P() (Room, error) { + //TODO: check if p2p is empty + return v.P2P, nil +} + +// AddServer adds the given server to the visor +func (v *Visor) AddServer(server Server) error { + //check if server already exists + _, err := v.GetServerByPK(server.PKRoute.Server) + if err != nil { + //add server to field server + v.Server[server.PKRoute.Server] = server + return nil + } + return fmt.Errorf("server already exists in visor") +} + +// DeleteServer removes the given pk (server) from the visor +func (v *Visor) DeleteServer(pk cipher.PubKey) error { + //check if server exists + _, err := v.GetServerByPK(pk) + if err != nil { + return fmt.Errorf("server does not exist in visor") //? should this be treaded as an error like now? + } + delete(v.Server, pk) + return nil +} + +// SetServer updates the given server +func (v *Visor) SetServer(server Server) error { + //check if server exists + _, err := v.GetServerByPK(server.PKRoute.Server) + if err != nil { + return fmt.Errorf("server does not exist in visor") //? should this be treaded as an error like now? -> or maybe even call AddServer when server does not exist? + } + v.Server[server.PKRoute.Server] = server + return nil +} + +// AddP2P adds the given room as p2p-chat to the visor +func (v *Visor) AddP2P(p2p Room) error { + //check if p2p already exists + _, err := v.GetP2P() + if err != nil { + return fmt.Errorf("p2p already exists in visor") + } + //add server to field server + v.P2P = p2p + return nil +} + +// SetP2P updates the p2p-chat of the visor +func (v *Visor) SetP2P(p2p Room) error { + //check if room exists + _, err := v.GetP2P() + if err != nil { + v.P2P = p2p + } + return fmt.Errorf("p2p does not exist in visor") //? should this be treaded as an error like now? -> or maybe even call AddP2P when p2p does not exist? +} + +// DeleteP2P removes the p2p-chat-room from the visor +func (v *Visor) DeleteP2P() error { + //check if p2p exists + _, err := v.GetP2P() + if err != nil { + v.P2P = Room{} + } + return fmt.Errorf("p2p does not exist in visor") //? should this be treaded as an error like now? +} + +// GetAllServer returns all mapped server +func (v *Visor) GetAllServer() map[cipher.PubKey]Server { + return v.Server +} + +// GetAllServerBoolMap returns a bool-map of all servers +func (v *Visor) GetAllServerBoolMap() map[cipher.PubKey]bool { + r := make(map[cipher.PubKey]bool) + for k := range v.Server { + r[k] = true + } + return r +} + +// GetServerByPK returns the the server mapped by pk if available and returns err if no server with given pk is available +func (v *Visor) GetServerByPK(pk cipher.PubKey) (*Server, error) { + if server, ok := v.Server[pk]; ok { + return &server, nil + } + return nil, fmt.Errorf("no server with pk %s found in visor %s", pk.Hex(), v.PK) +} + +// SetConnection sets the connection type used +func (v *Visor) SetConnection(conn net.Conn) { + v.Conn = conn +} + +// DeleteConnection clears the connection +func (v *Visor) DeleteConnection() { + v.Conn = nil +} + +// AddMessage Adds the given message to the given visor depending on the destination of the message +func (v *Visor) AddMessage(m message.Message) { + if m.Dest.Server == m.Dest.Visor { + v.P2P.AddMessage(m) + return + } + s := v.Server[m.Dest.Server] + s.AddMessage(m) +} + +// Constructors + +// NewUndefinedVisor creates undefined empty visor to a public key +func NewUndefinedVisor(pk cipher.PubKey) Visor { + v := Visor{} + v.PK = pk + v.Conn = nil + v.Server = make(map[cipher.PubKey]Server) + + return v +} + +// NewVisor creates a new visor with p2p and servers +func NewVisor(pk cipher.PubKey, p2p Room, server map[cipher.PubKey]Server) Visor { + v := Visor{} + v.PK = pk + v.Conn = nil + v.P2P = p2p + v.Server = server + return v +} + +// NewDefaultP2PVisor creates a new visor with only a default p2p room +func NewDefaultP2PVisor(pk cipher.PubKey) Visor { + v := Visor{} + v.PK = pk + v.Conn = nil + v.P2P = NewDefaultP2PRoom(pk) + v.Server = make(map[cipher.PubKey]Server) + + return v +} diff --git a/cmd/apps/skychat/internal/domain/chat/chat_repository.go b/cmd/apps/skychat/internal/domain/chat/visor_repository.go similarity index 69% rename from cmd/apps/skychat/internal/domain/chat/chat_repository.go rename to cmd/apps/skychat/internal/domain/chat/visor_repository.go index 5308d3a6c..421eda74f 100644 --- a/cmd/apps/skychat/internal/domain/chat/chat_repository.go +++ b/cmd/apps/skychat/internal/domain/chat/visor_repository.go @@ -7,9 +7,9 @@ import ( // Repository is the interface to the chat repository type Repository interface { - GetByPK(pk cipher.PubKey) (*Chat, error) - GetAll() ([]Chat, error) - Add(c Chat) error - Update(c Chat) error + GetByPK(pk cipher.PubKey) (*Visor, error) + GetAll() ([]Visor, error) + Add(v Visor) error + Set(v Visor) error Delete(pk cipher.PubKey) error } diff --git a/cmd/apps/skychat/internal/domain/client/client.go b/cmd/apps/skychat/internal/domain/client/client.go index 29cc4359e..06ec0581d 100644 --- a/cmd/apps/skychat/internal/domain/client/client.go +++ b/cmd/apps/skychat/internal/domain/client/client.go @@ -3,13 +3,16 @@ package client import ( "fmt" + "net" "os" "os/signal" + "reflect" "runtime" ipc "github.com/james-barrow/golang-ipc" "github.com/skycoin/skywire-utilities/pkg/buildinfo" + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" "github.com/skycoin/skywire/pkg/app" "github.com/skycoin/skywire/pkg/app/appnet" @@ -20,12 +23,13 @@ import ( // Client defines a chat client type Client struct { - appCl *app.Client // Skywire app client - ipcCl *ipc.Client // IPC client - netType appnet.Type // app netType - port routing.Port // app port - log *logging.Logger // app logger - clientCh chan string // client channel + appCl *app.Client // Skywire app client + ipcCl *ipc.Client // IPC client + netType appnet.Type // app netType + port routing.Port // app port + log *logging.Logger // app logger + conns map[cipher.PubKey]net.Conn // active connections + clientCh chan string // client channel } // Getter @@ -45,6 +49,31 @@ func (c *Client) GetPort() routing.Port { return c.port } +// GetConns returns a map of active connections +func (c *Client) GetConns() map[cipher.PubKey]net.Conn { + return c.conns +} + +// AddConn adds the given net.Conn to the map to keep track of active connections +func (c *Client) AddConn(pk cipher.PubKey, conn net.Conn) error { + //check if conn already added + if _, ok := c.conns[pk]; ok { + return fmt.Errorf("conn already added") + } + c.conns[pk] = conn + return nil +} + +// DeleteConn removes the given net.Conn from the map +func (c *Client) DeleteConn(pk cipher.PubKey) error { + //check if conn is added + if _, ok := c.conns[pk]; ok { + delete(c.conns, pk) + return nil + } + return fmt.Errorf("pk has no connection") //? handle as error? +} + // GetLog returns *logging.Logger func (c *Client) GetLog() *logging.Logger { return c.log @@ -55,7 +84,7 @@ func (c *Client) GetChannel() chan string { return c.clientCh } -// NewClient retrns *Client +// NewClient returns *Client func NewClient() *Client { c := Client{} c.appCl = app.NewClient(nil) @@ -66,6 +95,7 @@ func NewClient() *Client { } c.log = logging.MustGetLogger("chat") + c.conns = make(map[cipher.PubKey]net.Conn) c.netType = appnet.TypeSkynet c.port = routing.Port(1) @@ -103,7 +133,7 @@ func NewClient() *Client { // IsEmpty checks if the client is empty func (c *Client) IsEmpty() bool { - return *c == Client{} + return reflect.DeepEqual(*c, Client{}) } // SetAppStatus sets appserver.AppDetailedStatus diff --git a/cmd/apps/skychat/internal/domain/info/info.go b/cmd/apps/skychat/internal/domain/info/info.go index fce99a50a..4ca19fb2a 100644 --- a/cmd/apps/skychat/internal/domain/info/info.go +++ b/cmd/apps/skychat/internal/domain/info/info.go @@ -7,6 +7,7 @@ import ( // Info is conceptually similar to "account info" type Info struct { + //? change Pk to PKRoute or even delete it? Pk cipher.PubKey Alias string Desc string @@ -70,11 +71,13 @@ func NewDefaultInfo() Info { info.Alias = "Unknown" info.Desc = "Unknown" - info.Img = "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAIAAAAHjs1qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5OTMyNUUzOTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjY5OTMyNUU0OTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6Njk5MzI1RTE5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Njk5MzI1RTI5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7FIRCzAAAPn0lEQVR42uyd+VNTVxvH2ZIQlhBCJMEEAoiQAC8FpMrSyOKMVdEp7Uz7l/V/aDtTbTtFcFrTlE0RBBWBEtAghNUgCCSBLMD7mHSYKVqlmHvOTe7384Mj2z0nz/nk5Dn3niXx22+/TQBAGiQhBAC6AwDdAYDuAEB3AKA7ANAdAOgOAHQHALoDAN0BgO4AugMA3QGA7gBAdwCgOwDQHQDoDgB0BwC6AwDdAYDuALoDAN0BgO4AQHcAoDsA0B0A6A4AdAcAugMA3QH4JykIQfRjmpKi1Wo1Go1arc7IyEhLS1MqlQqFQi6Xy2Syw187ODgIhUJ+vz8QCOzs7Hi9Xo/HsxHm1atX9CNEErqLFJVKVVBQoNfrdTpdVlZWYmLiB/+EfkcW5u0f0TuBpHe73cvLyy6Xa2trCxGG7vwxGAzFxcUmk4kUj+Jl6Z2gCVNWVkZfvn79emFh4fnz5/QvYg7dWUNZSnl5+dmzZylXYVMcUVlZSQmP0+mcmJigbAetAN0Fp7CwsKqqKj8/n0vp6enp/wuzurr69OnT6elpSnvQKNA9+pw5c6auro7GoGKojC5MfX39kydPyPu9vT00EHSPDqdPn25qasrNzRVbxSiVoopVV1cPDw9ThoOWgu4fRVpamtVqLSkpEXMlKcNpaWmhDKe3t3dpaQmtBt1PAg1GGxsbFQpFTNQ2Jyfnyy+/nJqa6uvrCwQCaD7oflxSU1Pb2tqKiopiruZms9loNNrt9vn5ebTj22ASwVH0ev0333wTi64fJvTXr19vaGg4zqMu9O6SxmKxNDc3Jycnx/SrINFra2t1Ol13d7ff70ezond/BxcuXKAcJtZdP8RgMHz99dfZ2dloWeh+lJaWlrq6ujh7UVlZWV999ZUIb6FCd55cunSpoqIiXofdHR0dp0+fRitD97/7dbPZHMcvUCaT0eAVfTx0Tzh//ny89utHjL9x4wbyeEnrXlZW9umnn0rkxVJWQ328UqmE7lKEPtwpjZHUS1apVFeuXJHy/XiJ6i6Xy6nhU1Ik99iBxqyfffYZdJcWra2tmZmZ0nztVVVVBQUF0F0qlJaWinySo9C0tbXR5xt0l8SIzWq1Jkib9PR0aaY0ktO9oaGBjE+QPBaLRa/XQ/d4RqPRUDPD9QgS7OCTpNbAmBZ7iE6nKy4uhu7xicFg4LWDgGiRzlM2yeleW1sLv4+g1WoLCwuhe7yRk5Mj2ZvN76eqqgq6xxs1NTUw+51QgqdSqSTyYiXxFF0mk505c4ZX6bu7u8th1tfXNzc36ctgMEhVSklJIc/UajVlFDRqPHXqFK9hdHl5+eDgIHSPE86ePctleszi4uLY2Njc3Nzbu3xFvuPxeA53hlEqlWaz2WKxsJ+mS30BdI8fSktLGZfodrv7+vqoRz/+n+zs7DwKQ7Wtr69nOaWHPmE0Gg19+ED3mId6TZZL1w4ODkZGRoaGhk68Wen09LTT6bRarZRjMKt2cXGxFHSP/6GqyWRilhOHQqE7d+48ePDgIzfmpevY7faenh5mG/waDAYpfM7Hv+7MHi1ROt7V1UUdc7QuOD4+brPZ2FSexspSeN4c/7ozy2T++OMPl8sV3Ws6HI7R0VEGlZfJZJS+Q/eY5+7du5RMr66u7u/vC1fKxMQE5dxCXHlwcHBtbY1BoKSwVUH8D1UXw0Q6sPww1N9HtyfzeDwDAwPCjX37+/s7OjqEDpQUencJLdYMBoPOMAnhjdsLCgpI/by8vI+/5Tc8PEwXF/Qdu7KyIvT0dCk8W5Xolqg+n28qTEL4rvOh+ifYzX17e/uvv/4SusJUhNC6S2HxLnYAfnOMIzE2Nha5QUHqGwwG+s8xH8TSaJLB7cLZ2dnW1lZBi4iVgxuge9RYDUPJSXJycmR+PCX675/NMjMzw6BiOzs79J6kDyLhipDCmkbo/m729vbmw0S6vcMx7hHhvF4vs4eRm5ubguouhV13oPuH8fv9z8IkhM/GMJlMRqOR1KfxLsvjfOmtJej1k5KSoDv4Bx6PZyJMQnjJCMvdWkKhEOIP3bnB+KR2oZMNQR/DiQTs7x4zUO4k9HAFugOxIPSyDykkS9A9Zrp2oZ96+nw+6A5EQUlJidATdHd2dqA7EAUM9voT+kYndAfHwmQyabVaoUvZ2NiA7oAzlMM0NjYyKIjxfVXoDt7BuXPn2MxEd7vd0B3wJDc3l81Z3tvb28jdAU+USuXVq1eTk5MZlPWftsSB7iDKRI66zsjIYFPc4WZm0B2whnr0a9euMVsrfXBwEMX9QqA7+G+ut7e3G41GZiVS1y6FZ0wJmBEpNhQKBeUwjA8Je/78uUTCC91FhEqlon6d8QYYwWAwskQdugN25OXlXb16ValUMi6XunZBdw2B7uAoFoulubmZzT3HIzx58kQ6cYbunInMEaiuruZS+uzsLJsd+aA7ePMg6fPPP+e42fTw8LCkAg7duaHT6a5cucLsQdLbzMzMSGGeDHTnT0VFhdVq5ZKsRwiFQvfu3ZNa2KE7a0jxixcvsjyI5p08fPjQ4/FAdyAglLpQAkNpDN9qUA7D5pQE6C5d8vLyyHWh9884Thpjs9mYnfoE3aUIxzvrRxgYGJDCwiXozo2mpiZed9aP8OzZs/Hxcck2BHQXfGBKCUxhYaEYKrO2tsbsKD/oLjkUCsWNGze4D0wjeL3e27dvS3xfVeguFDQk7ejoEHqnu2MSCAQ6OzsleOcRurNApVJ98cUXIjncK3K+saTmxkB3dqSnp1O/LpKTvcj17u7uyFGbAIv3okxqaqrYXJ+bm0O7oHePPjKZjMamgp6gdHyCwSCNTdGvQ3ehuHz5skiOWvf5fOT6y5cv0SjQXRAaGxtFcn99Y2Ojs7Nza2sLjQLdBaGoqKimpkYMNVlaWurq6vL7/WgU6C4I6enpbW1tYqiJw+Gw2+1SOGUJunOjtbWV+5HT+/v79+/ff/z4MZoDugtIaWmpyWTiW4fd3d3ffvvN5XKhOaC7kOFLSWFz1sB7WFtb6+7uxsAUugvOuXPnKHHnWIGpqak///wTyTp0Fxy5XP7JJ5/wKp0U7+/vl/LkdejOFHJdJpNxKdrj8VACg6dI0J0RiYmJlZWVXIpeXFy8c+cODU/RCtCdEUVFRVwWWT9+/PjevXvSXFgN3blhNpsZl7i/v9/T0zM5OYngQ3emJCcn5+fnsyzR7/dTArOwsIDgQ3fWGI3GlBR2odve3u7s7FxfX0fkoTsHWD5GJdd//vlnPEWKCljNdBJOnTrFpiCPxwPXoTtncnJyGJQSWY4E16E7T1QqFZunSz09Pdg+ALrz151BKbOzsw6HA9GG7vGv+/7+/sDAAEIN3fnD4CzIubm5zc1NhBq6iyBkSYIHzel0Is7QXRQwGKeurKwgztBdKni9XgQBuosCBkeqi+GQD+gO3sBgi3SRbDEJ3QGLTEMkJyBAd/BmzpbQRXDfyQO6g79hMBG3oKBAJEchQHep4/f7hT71JSkpqaGhAaGG7qKAwbmkJSUlpaWlCDV058/y8jKDUlpaWkSyWzx0lzTz8/MMSpHJZO3t7Xx3KYPuIMHtdjM4tDEYDA4NDeEJaxTBWtUT8uLFC0G3VVpdXf39998xLxK6iwKHwyGQ7vv7+yMjI8PDw9g7CbqLhZWVlfX1dY1GE93LUndOnTp17YgwcndxMTExEd0LTk5Ofv/993AduosRsjNa+5JGzoW02+0M5p9Bd3ASSM2obK9Oo17q1OlfhBS5u6h59OhRRUXFiVevBoPBgYGBqCdFAL27IAQCgdHR0ZP9LeXoP/zwA1xH7x5LjI2NlZeXZ2dnH/9PcKsRvXusQu729vYe//dfv35969atoaEhuI7ePSZZWFiYnJykPv6Dv0mpS39/P26/QPfYpq+vz2AwZGVl/dsv+Hw+u92O2y9IZuIB6rBtNhslNu/86ezs7HfffQfXoXv8sLy8TBn5kW8Gg0Hq1Lu6unBQHpKZeGNkZCQ3N7e4uDjyJWY1onePc+7evbu+vk5ZDfX0N2/ehOvo3eOZyJEbSqUSM72guyTYCoM4IJkBALoDAN0BgO4AQHcAPgTuzAhIRkaG0WjMzs5WqVRyuVyhUCSEt5gMBAJbW1sbGxsLCwsM9qsB0F1AcnJyzGZzUVHRe2aMHULev3jxYmpqyu12I3TQPZagvryurs5gMBz/T6jjrwqzvLw8OjqKaWTQPQbIzMy0Wq3Uo5/4Cnl5ee3t7S6Xq7+/n8EW8tIk+dq1a4jCR1JaWnr9+nWtVvvxl6L8x2KxUHL/8uVLBBa9u+hobGysqamJZpOkpFy8eFGn09lsNizwg+4i4tKlSzQqFeLKZWVlaWlpt2/f3tvbQ5yjBe67n5ympiaBXI+Qn59/+fLlxMREhBq6c4Z63+rqaqFLKS4urq+vR7ShO0/UanVzczObsmhgUFBQgJhDd27QUFImk7Epi5IZemvR+BVhh+4coASDsmqWJapUqtraWkQeunOAi3lVVVVyuRzBh+5MycvL0+l07MtVKBQVFRWIP3RniqB3Ht8PThWG7qwpLCzkVbRWq6UkHk0A3Rmh0WjS0tI4VsBkMqEVoDu7xJ1vBfR6PVoBujNCrVbzrcBx1osA6B4ntiF3h+7sYPYkVbQVgO7QnR2YSgDd2fFvpxUwA6s9oDs7gsEg3wrgUCfozg6fz8e3Al6vF60A3RnB/WwC7KMN3dmxtrbGtwKvXr1CK0B3RiwsLPBdKO1yudAK0J3dSJHjETSBQGBpaQmtAN3ZMTMzw6top9OJTTigO1McDoff7+dS9Pj4OOIP3ZkSDAYnJyfZlzs/P4+j/KA7B0ZGRnZ2dliWeHBwMDg4iMhDdw5QMsNYvrGxMez+Dt25QfkMDRzZlLW2tnb//n3EHLrzxGazbWxsCF2Kz+fr7u7GDRnozplAIPDLL79sb28LmjX9+uuvmDgA3UWB1+u9deuWQCdteDyen376ifu0BegO/iHlzZs3Z2dno3vZxcXFH3/8ETNkog5Wx0Qhq+nq6qqsrLxw4UJqaupHXi0YDD58+HB0dBSBhe7iZXx8/NmzZ+fPn7dYLCdbYhcKhaanpx88eMB9Vj10Bx9md3e3t7d3aGiooqKipKTk+CeTUdLidDqfPn3K+OkVdAdRkH4kTFZWltFo1Ov1arU6MzNTLpdHVnZTukL5z/b29ubm5srKisvl4r5qBLqDj2UzzMTEBEIhHnBnBkB3AKA7ANAdAOgOAHQHALoDAN0BgO4AQHcAoDsA0B1AdwCgOwDQHQDoDgB0BwC6AwDdAYDuAEB3AKA7ANAdQHcAoDsA0B0A6A4AdAcAugMA3QGA7gBAdwCgOwDQHUiX/wswADN/ucDefiV4AAAAAElFTkSuQmCC" + info.Img = DefaultImage return info } +const DefaultImage = "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAIAAAAHjs1qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5OTMyNUUzOTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjY5OTMyNUU0OTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6Njk5MzI1RTE5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Njk5MzI1RTI5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7FIRCzAAAPn0lEQVR42uyd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" + // IsEmpty checks if info is empty func (i *Info) IsEmpty() bool { return *i == Info{} diff --git a/cmd/apps/skychat/internal/domain/message/message.go b/cmd/apps/skychat/internal/domain/message/message.go index f5593368b..e8c8e5cd3 100644 --- a/cmd/apps/skychat/internal/domain/message/message.go +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -6,6 +6,7 @@ import ( "time" "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) // types of messages @@ -49,7 +50,8 @@ type Message struct { ID int64 //an identifier for p2p chats and groups, Id is set by the receiver/server Origin cipher.PubKey //the originator of the Message Time time.Time //the utc+0 timestamp of the Message - Sender cipher.PubKey //from who the Message was received (e.g. peer/group) + Root util.PKRoute //the root from where the Message was received (e.g. peer/group) + Dest util.PKRoute //the destination where the message should be sent. MsgType int //see const above MsgSubtype int //see const above Message []byte //the actual Message @@ -62,7 +64,8 @@ type JSONMessage struct { ID int64 `json:"Id"` Origin cipher.PubKey `json:"Origin"` Time time.Time `json:"Time"` - Sender cipher.PubKey `json:"Sender"` + Root util.PKRoute `json:"Root"` + Dest util.PKRoute `json:"Dest"` MsgType int `json:"Msgtype"` MsgSubtype int `json:"MsgSubtype"` Message string `json:"Message"` @@ -76,7 +79,8 @@ func NewJSONMessage(m Message) JSONMessage { m.ID, m.Origin, m.Time, - m.Sender, + m.Root, + m.Dest, m.MsgType, m.MsgSubtype, string(m.Message), @@ -91,7 +95,8 @@ func NewMessage(m JSONMessage) Message { m.ID, m.Origin, m.Time, - m.Sender, + m.Root, + m.Dest, m.MsgType, m.MsgSubtype, []byte(m.Message), @@ -106,10 +111,11 @@ func (m Message) MarshalJSON() ([]byte, error) { } // NewTextMessage returns a Message -func NewTextMessage(pk cipher.PubKey, msg []byte) Message { +func NewTextMessage(pkOrigin cipher.PubKey, routeDestination util.PKRoute, msg []byte) Message { m := Message{} - m.Origin = pk - m.Sender = pk + m.Origin = pkOrigin + m.Root = util.NewVisorOnlyRoute(pkOrigin) + m.Dest = routeDestination m.MsgType = TxtMsgType m.MsgSubtype = 0 m.Message = msg @@ -118,11 +124,12 @@ func NewTextMessage(pk cipher.PubKey, msg []byte) Message { return m } -// NewChatRequestMessage returns a request Message -func NewChatRequestMessage(pk cipher.PubKey) Message { +// NewRouteRequestMessage returns a request Message +func NewRouteRequestMessage(pkOrigin cipher.PubKey, routeDestination util.PKRoute) Message { m := Message{} - m.Origin = pk - m.Sender = pk + m.Origin = pkOrigin + m.Root = util.NewVisorOnlyRoute(pkOrigin) + m.Dest = routeDestination m.MsgType = ConnMsgType m.MsgSubtype = ConnMsgTypeRequest m.Status = MsgStatusInitial @@ -130,11 +137,14 @@ func NewChatRequestMessage(pk cipher.PubKey) Message { return m } -// NewChatAcceptMessage returns a chat accepted message -func NewChatAcceptMessage(pk cipher.PubKey) Message { +/* NewChatAcceptMessage returns a chat accepted message +pk is the users pk to set the messages root +*/ +func NewChatAcceptMessage(root util.PKRoute, dest util.PKRoute) Message { m := Message{} - m.Origin = pk - m.Sender = pk + m.Origin = root.Visor + m.Root = root + m.Dest = dest m.MsgType = ConnMsgType m.MsgSubtype = ConnMsgTypeAccept m.Status = MsgStatusInitial @@ -143,10 +153,11 @@ func NewChatAcceptMessage(pk cipher.PubKey) Message { } // NewChatRejectMessage returns new chat rejected message -func NewChatRejectMessage(pk cipher.PubKey) Message { +func NewChatRejectMessage(root util.PKRoute, dest util.PKRoute) Message { m := Message{} - m.Origin = pk - m.Sender = pk + m.Origin = root.Visor + m.Root = root + m.Dest = dest m.MsgType = ConnMsgType m.MsgSubtype = ConnMsgTypeReject m.Status = MsgStatusInitial @@ -155,10 +166,11 @@ func NewChatRejectMessage(pk cipher.PubKey) Message { } // NewChatInfoMessage returns new chat info -func NewChatInfoMessage(pk cipher.PubKey, info []byte) Message { +func NewChatInfoMessage(root util.PKRoute, dest util.PKRoute, info []byte) Message { m := Message{} - m.Origin = pk - m.Sender = pk + m.Origin = root.Visor + m.Root = root + m.Dest = dest m.MsgType = InfoMsgType m.Message = info m.Status = MsgStatusInitial @@ -181,9 +193,24 @@ func (m *Message) GetTime() time.Time { return m.Time } -// GetSender returns the sender public key -func (m *Message) GetSender() cipher.PubKey { - return m.Sender +// GetRootVisor returns the root visor public key +func (m *Message) GetRootVisor() cipher.PubKey { + return m.Root.Visor +} + +// GetDestinationVisor returns the destination visor +func (m *Message) GetDestinationVisor() cipher.PubKey { + return m.Dest.Visor +} + +// GetDestinationServer returns the destination server +func (m *Message) GetDestinationServer() cipher.PubKey { + return m.Dest.Server +} + +// GetDestinationRoom returns the destination server +func (m *Message) GetDestinationRoom() cipher.PubKey { + return m.Dest.Room } // GetMessageType returns the message type integer diff --git a/cmd/apps/skychat/internal/domain/peer/peer.go b/cmd/apps/skychat/internal/domain/peer/peer.go index 31c2990a7..9dfc40e0f 100644 --- a/cmd/apps/skychat/internal/domain/peer/peer.go +++ b/cmd/apps/skychat/internal/domain/peer/peer.go @@ -2,12 +2,47 @@ package peer import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" ) // Peer contains information about a peer type Peer struct { + // Info is the info that is managed and updated by the peer Info info.Info - //TODO: make peerRepository so the user can give each Peer a Custom Alias - //TODO: CustomAlias string + // Alias is a custom alias that can be set by the user + Alias string +} + +// GetPK returns the public key of the peer +func (p *Peer) GetPK() cipher.PubKey { + return p.Info.GetPK() +} + +// GetInfo returns the info of the peer +func (p *Peer) GetInfo() info.Info { + return p.Info +} + +// GetAlias returns the alias of the peer +func (p *Peer) GetAlias() string { + return p.Alias +} + +// SetInfo updates the info of the peer with the given info +func (p *Peer) SetInfo(i info.Info) { + p.Info = i +} + +// SetAlias sets or updates the peer with the given alias +func (p *Peer) SetAlias(a string) { + p.Alias = a +} + +// NewPeer is constructor for Peer +func NewPeer(i info.Info, alias string) *Peer { + if alias == "" { + return &Peer{i, i.GetAlias()} + } + return &Peer{i, alias} } diff --git a/cmd/apps/skychat/internal/domain/peer/peerbook.go b/cmd/apps/skychat/internal/domain/peer/peerbook.go new file mode 100644 index 000000000..c5c580f39 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/peer/peerbook.go @@ -0,0 +1,37 @@ +package peer + +import ( + "fmt" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" +) + +// Peerbook contains a map of peers +type Peerbook struct { + peers map[cipher.PubKey]Peer +} + +// GetPeerByPK returns a peer from the peerbook if it is available +func (pb *Peerbook) GetPeerByPK(pk cipher.PubKey) (*Peer, error) { + if p, ok := pb.peers[pk]; ok { + return &p, nil + } + return nil, fmt.Errorf("peer not found") +} + +// SetPeer updates or adds the given peer in the peerbook +func (pb *Peerbook) SetPeer(p Peer) { + pb.peers[p.GetPK()] = p +} + +// DeletePeer deletes the given peer from the peerbook +func (pb *Peerbook) DeletePeer(pk cipher.PubKey) { + delete(pb.peers, pk) +} + +// AddPeer adds a new peer to the peerbook +func (pb *Peerbook) AddPeer(i info.Info, alias string) { + p := NewPeer(i, alias) + pb.peers[i.GetPK()] = *p +} diff --git a/cmd/apps/skychat/internal/domain/server/server.go b/cmd/apps/skychat/internal/domain/server/server.go deleted file mode 100644 index 1854608b0..000000000 --- a/cmd/apps/skychat/internal/domain/server/server.go +++ /dev/null @@ -1,13 +0,0 @@ -// Package server contains the code required by the chat app for peering -package server - -// Server defies the chat server -// type Server struct { -// appCl *app.Client // Skywire app client //nolint -// clientCh chan string //nolint -// conns map[cipher.PubKey]peer.Peer // peer connections //nolint -// info info.Info // the public info of the server //nolint -// msgs []message.Message // all messages send/received //nolint -// blacklist []cipher.PubKey // Blacklist to block inocming connections //nolint -// connsMu sync.Mutex //nolint -// } diff --git a/cmd/apps/skychat/internal/domain/user/user.go b/cmd/apps/skychat/internal/domain/user/user.go index dbf358562..d0c2621a8 100644 --- a/cmd/apps/skychat/internal/domain/user/user.go +++ b/cmd/apps/skychat/internal/domain/user/user.go @@ -5,6 +5,7 @@ import ( "fmt" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/settings" ) @@ -12,6 +13,7 @@ import ( type User struct { info info.Info // the info of the local user settings settings.Settings // the settings of the local user + peerbook peer.Peerbook // the contactsbook of the local user } // GetInfo gets the user info @@ -24,7 +26,12 @@ func (u *User) GetSettings() *settings.Settings { return &u.settings } -// SetInfo sets the chat info +// GetPeerbook returns the peerbook +func (u *User) GetPeerbook() *peer.Peerbook { + return &u.peerbook +} + +// SetInfo sets the user's info func (u *User) SetInfo(i info.Info) { u.info = i } @@ -34,6 +41,11 @@ func (u *User) SetSettings(s settings.Settings) { u.settings = s } +// SetPeerbook sets the peerbook +func (u *User) SetPeerbook(p peer.Peerbook) { + u.peerbook = p +} + // NewDefaultUser returns *User func NewDefaultUser() *User { fmt.Println("user - NewDefaultUser") diff --git a/cmd/apps/skychat/internal/domain/util/pkroute.go b/cmd/apps/skychat/internal/domain/util/pkroute.go new file mode 100644 index 000000000..4abcf3815 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/util/pkroute.go @@ -0,0 +1,78 @@ +// Package util collects all structs and functions needed inside skychat +package util + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" +) + +// PKRoute defines the routing inside the skychat app if a root or destination is from a p2p chat or a specific room of a specific server. +type PKRoute struct { + Visor cipher.PubKey // PK of visor + Server cipher.PubKey // P2P: Server=Visor // Server: PK of server + Room cipher.PubKey // P2P: Room=nil // Server: PK of room +} + +// NewVisorOnlyRoute returns a route with only the visor pubkey +func NewVisorOnlyRoute(pk cipher.PubKey) PKRoute { + pkr := PKRoute{} + pkr.Visor = pk + return pkr +} + +// NewP2PRoute returns a route with visor pubkey == server pubkey +func NewP2PRoute(visorpk cipher.PubKey) PKRoute { + pkr := PKRoute{} + pkr.Visor = visorpk + pkr.Server = visorpk + return pkr +} + +// NewServerRoute returns a new route of a server +func NewServerRoute(visorpk cipher.PubKey, serverpk cipher.PubKey) PKRoute { + pkr := PKRoute{} + pkr.Visor = visorpk + pkr.Server = serverpk + return pkr +} + +// NewRoomRoute returns a new route of a room +func NewRoomRoute(visorpk cipher.PubKey, serverpk cipher.PubKey, roompk cipher.PubKey) PKRoute { + pkr := PKRoute{} + pkr.Visor = visorpk + pkr.Server = serverpk + pkr.Room = roompk + return pkr +} + +// String returns a string representation of PKRoute +func (r *PKRoute) String() string { + return "pkVisor: " + r.Visor.Hex() + " pkServer: " + r.Server.Hex() + " pkRoom: " + r.Room.Hex() +} + +// NewLocalServerRoute sets up a new local defined server route +func NewLocalServerRoute(visorPK cipher.PubKey, existingServer map[cipher.PubKey]bool) PKRoute { + + serverPK := cipher.PubKey{} + + for ok := true; ok; ok = !existingServer[serverPK] { + serverPK, _ = cipher.GenerateKeyPair() + existingServer[serverPK] = true + + } + + r := NewServerRoute(visorPK, serverPK) + return r +} + +// NewLocalRoomRoute sets up a new local defined room route +func NewLocalRoomRoute(visorPK cipher.PubKey, serverPK cipher.PubKey, existingRooms map[cipher.PubKey]bool) PKRoute { + roomPK := cipher.PubKey{} + + for ok := true; ok; ok = !existingRooms[roomPK] { + roomPK, _ = cipher.GenerateKeyPair() + existingRooms[roomPK] = true + } + + r := NewRoomRoute(visorPK, serverPK, roomPK) + return r +} diff --git a/cmd/apps/skychat/internal/inputports/cli/cli.go b/cmd/apps/skychat/internal/inputports/cli/cli.go new file mode 100644 index 000000000..b89c35676 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/cli/cli.go @@ -0,0 +1,4 @@ +// Package cli is an api for cli-commands +package cli + +//[] add cli functionality with cobra & viper --> Talk to Moses on what is needed and how to implement it diff --git a/cmd/apps/skychat/internal/inputports/http/chat/handler.go b/cmd/apps/skychat/internal/inputports/http/chat/handler.go index 719cf873b..d4f4b0175 100644 --- a/cmd/apps/skychat/internal/inputports/http/chat/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/chat/handler.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "net/http" + "strconv" "strings" "github.com/gorilla/mux" @@ -13,6 +14,8 @@ import ( chatservices "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/chat" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/chat/commands" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/chat/queries" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) // Handler Chat http request handler @@ -25,85 +28,307 @@ func NewHandler(cs chatservices.ChatServices) *Handler { return &Handler{chatServices: cs} } -// GetAll Returns all available chats -func (c Handler) GetAll(w http.ResponseWriter, r *http.Request) { - fmt.Println(formatRequest(r)) - chats, err := c.chatServices.Queries.GetAllChatsHandler.Handle() +//[]: change to AddRoom -> as this also can be used to add a room at a remote server (when being admin) + +// AddLocalRoomURLParam contains the parameter identifier to be parsed by the handler +const AddLocalRoomURLParam = "addLocalRoom" + +// AddLocalRoomRequestModel represents the request model expected for Add request +type AddLocalRoomRequestModel struct { + //PKRoute + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + //Info + Alias string `json:"alias"` + Desc string `json:"desc"` + Img string `json:"img"` + //Type + Type string `json:"type"` +} + +// AddLocalRoom adds a room to the local visor/server +func (c Handler) AddLocalRoom(w http.ResponseWriter, r *http.Request) { + var requestModel AddLocalRoomRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr.Error()) + return + } + + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + err := visorpk.Set(requestModel.VisorPk) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, err.Error()) return } + route.Visor = visorpk + if requestModel.ServerPk != "" { + serverpk := cipher.PubKey{} + err = serverpk.Set(requestModel.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + } + + info := info.Info{} + info.SetAlias(requestModel.Alias) + info.SetDescription(requestModel.Desc) + info.SetImg(requestModel.Img) + + var roomType int64 + + if requestModel.Type != "" { + roomType, err = strconv.ParseInt(requestModel.Type, 10, 64) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + } else { + roomType = 1 + } - err = json.NewEncoder(w).Encode(chats) + err = c.chatServices.Commands.AddLocalRoomHandler.Handle(commands.AddLocalRoomRequest{ + Route: route, + Info: info, + Type: roomType, + }) if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) return } + w.WriteHeader(http.StatusOK) } -// GetChatPKURLParam contains the parameter identifier to be parsed by the handler -const GetChatPKURLParam = "chatPK" +//[]: change to AddServer -> as this also can be used to add a server at a remote visor (when being admin) -// GetByPK Returns the chat with the provided pk -func (c Handler) GetByPK(w http.ResponseWriter, r *http.Request) { - fmt.Println(formatRequest(r)) - vars := mux.Vars(r) - pk := cipher.PubKey{} - err := pk.Set(vars[GetChatPKURLParam]) +// AddLocalServerURLParam contains the parameter identifier to be parsed by the handler +const AddLocalServerURLParam = "addLocalServer" + +// AddLocalServerRequestModel represents the request model expected for Add request +type AddLocalServerRequestModel struct { + //PKRoute + VisorPk string `json:"visorpk"` + //Info + Alias string `json:"alias"` + Desc string `json:"desc"` + Img string `json:"img"` +} + +// AddLocalServer adds a room to the local visor/server +func (c Handler) AddLocalServer(w http.ResponseWriter, r *http.Request) { + var requestModel AddLocalServerRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr.Error()) + return + } + + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + err := visorpk.Set(requestModel.VisorPk) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, err.Error()) return } + route.Visor = visorpk - chat, err := c.chatServices.Queries.GetChatByPKHandler.Handle(queries.GetChatByPKRequest{Pk: pk}) + info := info.Info{} + info.SetAlias(requestModel.Alias) + info.SetDescription(requestModel.Desc) + info.SetImg(requestModel.Img) - /*if err == nil && chat == nil { - w.WriteHeader(http.StatusNotFound) - fmt.Fprint(w, "Not Found") + err = c.chatServices.Commands.AddLocalServerHandler.Handle(commands.AddLocalServerRequest{ + Route: route, + Info: info, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) return - }*/ + } + w.WriteHeader(http.StatusOK) +} +// AddRemoteRouteURLParam contains the parameter identifier to be parsed by the handler +const AddRemoteRouteURLParam = "addRemoteRoute" + +// AddRemoteRouteRequestModel represents the request model expected for Add request +type AddRemoteRouteRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` +} + +// AddRemoteRoute adds the provided route +func (c Handler) AddRemoteRoute(w http.ResponseWriter, r *http.Request) { + //fmt.Println(formatRequest(r)) + var routeToAdd AddRemoteRouteRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&routeToAdd) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr.Error()) + return + } + fmt.Println("HTTPHandler - Add - Route: " + routeToAdd.VisorPk + "," + routeToAdd.ServerPk + "," + routeToAdd.RoomPk) + + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + err := visorpk.Set(routeToAdd.VisorPk) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, err.Error()) return } - err = json.NewEncoder(w).Encode(chat) + route.Visor = visorpk + if routeToAdd.ServerPk != "" { + serverpk := cipher.PubKey{} + err = serverpk.Set(routeToAdd.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + if routeToAdd.RoomPk != "" { + roompk := cipher.PubKey{} + err = roompk.Set(routeToAdd.RoomPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Room = roompk + } + } + + err = c.chatServices.Commands.AddRemoteRouteHandler.Handle(commands.AddRemoteRouteRequest{ + Route: route, + }) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, err.Error()) return } + w.WriteHeader(http.StatusOK) } -// AddChatRequestModel represents the request model expected for Add request -type AddChatRequestModel struct { - Pk string `json:"pk"` +// DeleteLocalRoomByRouteURLParam contains the parameter identifier to be parsed by the handler +const DeleteLocalRoomByRouteURLParam = "deleteLocalRoom" + +// DeleteLocalRoomByRouteRequestModel represents the request model expected for Delete request +type DeleteLocalRoomByRouteRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` } -// Add adds the provided pk -func (c Handler) Add(w http.ResponseWriter, r *http.Request) { - //fmt.Println(formatRequest(r)) - var chatToAdd AddChatRequestModel - decodeErr := json.NewDecoder(r.Body).Decode(&chatToAdd) +// DeleteLocalRoomByRoute adds a room to the local visor/server +func (c Handler) DeleteLocalRoomByRoute(w http.ResponseWriter, r *http.Request) { + var requestModel DeleteLocalRoomByRouteRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) if decodeErr != nil { w.WriteHeader(http.StatusBadRequest) fmt.Fprint(w, decodeErr.Error()) return } - fmt.Println("HTTPHandler - Add - PK: " + chatToAdd.Pk) - pk := cipher.PubKey{} - err := pk.Set(chatToAdd.Pk) + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + err := visorpk.Set(requestModel.VisorPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Visor = visorpk + if requestModel.ServerPk != "" { + serverpk := cipher.PubKey{} + err = serverpk.Set(requestModel.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + if requestModel.RoomPk != "" { + roompk := cipher.PubKey{} + err = roompk.Set(requestModel.RoomPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Room = roompk + } + } + + err = c.chatServices.Commands.DeleteLocalRoomHandler.Handle(commands.DeleteLocalRoomRequest{ + Route: route, + }) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, err.Error()) return } + w.WriteHeader(http.StatusOK) +} + +// DeleteLocalServerByRouteURLParam contains the parameter identifier to be parsed by the handler +const DeleteLocalServerByRouteURLParam = "deleteLocalServer" + +// DeleteLocalServerByRouteRequestModel represents the request model expected for Delete request +type DeleteLocalServerByRouteRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` +} - err = c.chatServices.Commands.AddChatHandler.Handle(commands.AddChatRequest{ - Pk: pk, +// DeleteLocalServerByRoute adds a room to the local visor/server +func (c Handler) DeleteLocalServerByRoute(w http.ResponseWriter, r *http.Request) { + var requestModel DeleteLocalServerByRouteRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr.Error()) + return + } + + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + err := visorpk.Set(requestModel.VisorPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Visor = visorpk + if requestModel.ServerPk != "" { + serverpk := cipher.PubKey{} + err = serverpk.Set(requestModel.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + } + + err = c.chatServices.Commands.DeleteLocalServerHandler.Handle(commands.DeleteLocalServerRequest{ + Route: route, }) if err != nil { w.WriteHeader(http.StatusInternalServerError) @@ -113,36 +338,152 @@ func (c Handler) Add(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -// DeleteChatPKURLParam contains the parameter identifier to be parsed by the handler -const DeleteChatPKURLParam = "delete" +// DeleteVisorByPKURLParam contains the parameter identifier to be parsed by the handler +const DeleteVisorByPKURLParam = "deleteVisor" -// Delete Deletes the crag with the provided id -func (c Handler) Delete(w http.ResponseWriter, r *http.Request) { +// DeleteVisorByPK Deletes the remote visor with the provided pk +func (c Handler) DeleteVisorByPK(w http.ResponseWriter, r *http.Request) { fmt.Println(formatRequest(r)) vars := mux.Vars(r) fmt.Println(vars) - fmt.Println(vars[DeleteChatPKURLParam]) + fmt.Println(vars[DeleteVisorByPKURLParam]) chatPK := cipher.PubKey{} - err := chatPK.Set(vars[DeleteChatPKURLParam]) + err := chatPK.Set(vars[DeleteVisorByPKURLParam]) if err != nil { fmt.Println("could not convert pubkey") } fmt.Println(chatPK.Hex()) - err = c.chatServices.Commands.DeleteChatHandler.Handle(commands.DeleteChatRequest{Pk: chatPK}) + err = c.chatServices.Commands.DeleteRemoteVisorHandler.Handle(commands.DeleteRemoteVisorRequest{Pk: chatPK}) if err != nil { w.WriteHeader(http.StatusBadRequest) fmt.Fprint(w, err.Error()) } +} + +// LeaveRemoteRoomByRouteURLParam contains the parameter identifier to be parsed by the handler +const LeaveRemoteRoomByRouteURLParam = "leaveRemoteRoom" + +// LeaveRemoteRoomByRouteRequestModel represents the request model expected for Leave request +type LeaveRemoteRoomByRouteRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` +} + +// LeaveRemoteRoomByRoute adds a room to the local visor/server +func (c Handler) LeaveRemoteRoomByRoute(w http.ResponseWriter, r *http.Request) { + var requestModel LeaveRemoteRoomByRouteRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr.Error()) + return + } + + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + err := visorpk.Set(requestModel.VisorPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Visor = visorpk + if requestModel.ServerPk != "" { + serverpk := cipher.PubKey{} + err = serverpk.Set(requestModel.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + if requestModel.RoomPk != "" { + roompk := cipher.PubKey{} + err = roompk.Set(requestModel.RoomPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Room = roompk + } + } + err = c.chatServices.Commands.LeaveRemoteRoomHandler.Handle(commands.LeaveRemoteRoomRequest{ + Route: route, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + w.WriteHeader(http.StatusOK) } +// LeaveRemoteServerByRouteURLParam contains the parameter identifier to be parsed by the handler +const LeaveRemoteServerByRouteURLParam = "leaveRemoteRoom" + +// LeaveRemoteServerByRouteRequestModel represents the request model expected for Leave request +type LeaveRemoteServerByRouteRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` +} + +// LeaveRemoteServerByRoute adds a room to the local visor/server +func (c Handler) LeaveRemoteServerByRoute(w http.ResponseWriter, r *http.Request) { + var requestModel LeaveRemoteServerByRouteRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr.Error()) + return + } + + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + err := visorpk.Set(requestModel.VisorPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Visor = visorpk + if requestModel.ServerPk != "" { + serverpk := cipher.PubKey{} + err = serverpk.Set(requestModel.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + } + + err = c.chatServices.Commands.LeaveRemoteServerHandler.Handle(commands.LeaveRemoteServerRequest{ + Route: route, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + w.WriteHeader(http.StatusOK) +} + +//[]:rename to SendTextMessageURLParam + // SendTextMessagePKURLParam contains the parameter identifier to be parsed by the handler const SendTextMessagePKURLParam = "sendTxtMsg" // SendTextMessageRequestModel represents the request model expected for Add request type SendTextMessageRequestModel struct { - Pk string `json:"pk"` - Msg string `json:"message"` + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` + Msg string `json:"message"` } // SendTextMessage sends a message to the provided pk @@ -156,17 +497,33 @@ func (c Handler) SendTextMessage(w http.ResponseWriter, r *http.Request) { return } - pk := cipher.PubKey{} - err := pk.Set(msgToSend.Pk) + visorpk := cipher.PubKey{} + err := visorpk.Set(msgToSend.VisorPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + + serverpk := cipher.PubKey{} + err = serverpk.Set(msgToSend.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + + roompk := cipher.PubKey{} + err = roompk.Set(msgToSend.RoomPk) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, err.Error()) return } - err = c.chatServices.Commands.SendTextHandler.Handle(commands.SendTextMessageRequest{ - Pk: pk, - Msg: []byte(msgToSend.Msg), + err = c.chatServices.Commands.SendTextMessageHandler.Handle(commands.SendTextMessageRequest{ + Route: util.NewRoomRoute(visorpk, serverpk, roompk), + Msg: []byte(msgToSend.Msg), }) if err != nil { w.WriteHeader(http.StatusInternalServerError) @@ -176,6 +533,236 @@ func (c Handler) SendTextMessage(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } +// GetAllMessagesFromRoomByRouteURLParam contains the parameter identifier to be parsed by the handler +const GetAllMessagesFromRoomByRouteURLParam = "getRoomMessages" + +// GetAllMessagesFromRoomByRouteRequestModel represents the request model expected for Get request +type GetAllMessagesFromRoomByRouteRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` +} + +// GetAllMessagesFromRoomByRoute returns the server of the provided route +func (c Handler) GetAllMessagesFromRoomByRoute(w http.ResponseWriter, r *http.Request) { + var routeToGet GetAllMessagesFromRoomByRouteRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&routeToGet) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr.Error()) + return + } + + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + err := visorpk.Set(routeToGet.VisorPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Visor = visorpk + if routeToGet.ServerPk != "" { + serverpk := cipher.PubKey{} + err = serverpk.Set(routeToGet.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + if routeToGet.RoomPk != "" { + roompk := cipher.PubKey{} + err = roompk.Set(routeToGet.RoomPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Room = roompk + } + } + messages, err := c.chatServices.Queries.GetAllMessagesFromRoomHandler.Handle(queries.GetAllMessagesFromRoomRequest{ + Route: route, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + err = json.NewEncoder(w).Encode(messages) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } +} + +// GetAllVisors Returns all available visors +func (c Handler) GetAllVisors(w http.ResponseWriter, r *http.Request) { + fmt.Println(formatRequest(r)) + visors, err := c.chatServices.Queries.GetAllVisorsHandler.Handle() + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + + err = json.NewEncoder(w).Encode(visors) + if err != nil { + return + } +} + +// GetRoomByRouteURLParam contains the parameter identifier to be parsed by the handler +const GetRoomByRouteURLParam = "getRoom" + +// GetRoomByRoute returns the server of the provided route +func (c Handler) GetRoomByRoute(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + qVisor := query.Get("visor") + qServer := query.Get("server") + qRoom := query.Get("room") + + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + err := visorpk.Set(qVisor) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Visor = visorpk + if qServer != "" { + serverpk := cipher.PubKey{} + err = serverpk.Set(qServer) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + if qRoom != "" { + roompk := cipher.PubKey{} + err = roompk.Set(qRoom) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Room = roompk + } + } + room, err := c.chatServices.Queries.GetRoomByRouteHandler.Handle(queries.GetRoomByRouteRequest{ + Route: route, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + err = json.NewEncoder(w).Encode(room) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } +} + +// GetServerByRouteURLParam contains the parameter identifier to be parsed by the handler +const GetServerByRouteURLParam = "getServer" + +// GetServerByRouteRequestModel represents the request model expected for Get request +type GetServerByRouteRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` +} + +// GetServerByRoute returns the server of the provided route +func (c Handler) GetServerByRoute(w http.ResponseWriter, r *http.Request) { + var routeToGet GetServerByRouteRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&routeToGet) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr.Error()) + return + } + + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + err := visorpk.Set(routeToGet.VisorPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Visor = visorpk + if routeToGet.ServerPk != "" { + serverpk := cipher.PubKey{} + err = serverpk.Set(routeToGet.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + } + + server, err := c.chatServices.Queries.GetServerByRouteHandler.Handle(queries.GetServerByRouteRequest{ + Route: route, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + err = json.NewEncoder(w).Encode(server) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } +} + +// GetVisorByPKURLParam contains the parameter identifier to be parsed by the handler +const GetVisorByPKURLParam = "getVisor" + +// GetVisorByPK Returns the chat with the provided pk +func (c Handler) GetVisorByPK(w http.ResponseWriter, r *http.Request) { + fmt.Println(formatRequest(r)) + vars := mux.Vars(r) + pk := cipher.PubKey{} + err := pk.Set(vars[GetVisorByPKURLParam]) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + + chat, err := c.chatServices.Queries.GetVisorByPKHandler.Handle(queries.GetVisorByPKRequest{Pk: pk}) + + /*if err == nil && chat == nil { + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, "Not Found") + return + }*/ + + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + err = json.NewEncoder(w).Encode(chat) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } +} + // formatRequest generates ascii representation of a request func formatRequest(r *http.Request) string { // Create return string diff --git a/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go b/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go index a72137974..5a293c761 100644 --- a/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go @@ -23,7 +23,7 @@ func (c Handler) SubscribeNotifications(w http.ResponseWriter, r *http.Request) f, ok := w.(http.Flusher) if !ok { - http.Error(w, "Streaming unsupported!", http.StatusBadRequest) + http.Error(w, "Streaming unsupported!", http.StatusInternalServerError) return } @@ -31,6 +31,12 @@ func (c Handler) SubscribeNotifications(w http.ResponseWriter, r *http.Request) w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") w.Header().Set("Transfer-Encoding", "chunked") + w.Header().Set("Access-Control-Allow-Origin", "*") + + c.ns.InitChannel() + defer func() { + c.ns.DeferChannel() + }() for { select { diff --git a/cmd/apps/skychat/internal/inputports/http/server.go b/cmd/apps/skychat/internal/inputports/http/server.go index 1a8849d42..0de0ae0b8 100644 --- a/cmd/apps/skychat/internal/inputports/http/server.go +++ b/cmd/apps/skychat/internal/inputports/http/server.go @@ -7,6 +7,7 @@ import ( "io/fs" "log" "net/http" + "time" "github.com/gorilla/mux" @@ -32,8 +33,10 @@ func NewServer(appServices app.Services) *Server { httpServer := &Server{appServices: appServices} httpServer.router = mux.NewRouter() httpServer.router.Handle("/", http.FileServer(getFileSystem())) - //TODO: add router to favicon.ico instead of html base64 string - //TODO: could not get it to work with go embed but it should work withit + httpServer.router.Handle("/favicon.ico", http.FileServer(getFileSystem())) + httpServer.router.Handle("/index.js", http.FileServer(getFileSystem())) + httpServer.router.Handle("/stylesheet.css", http.FileServer(getFileSystem())) + httpServer.AddChatHTTPRoutes() httpServer.AddUserHTTPRoutes() httpServer.AddNotificationHTTPRoutes() @@ -46,13 +49,22 @@ func NewServer(appServices app.Services) *Server { func (httpServer *Server) AddChatHTTPRoutes() { const chatsHTTPRoutePath = "/chats" //Queries - httpServer.router.HandleFunc(chatsHTTPRoutePath, chat.NewHandler(httpServer.appServices.ChatServices).GetAll).Methods("GET") - httpServer.router.HandleFunc(chatsHTTPRoutePath+"/{"+chat.GetChatPKURLParam+"}", chat.NewHandler(httpServer.appServices.ChatServices).GetByPK).Methods("GET") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.GetAllMessagesFromRoomByRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).GetAllMessagesFromRoomByRoute).Methods("GET") + httpServer.router.HandleFunc(chatsHTTPRoutePath, chat.NewHandler(httpServer.appServices.ChatServices).GetAllVisors).Methods("GET") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.GetRoomByRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).GetRoomByRoute).Methods("GET") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.GetServerByRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).GetServerByRoute).Methods("GET") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/{"+chat.GetVisorByPKURLParam+"}", chat.NewHandler(httpServer.appServices.ChatServices).GetVisorByPK).Methods("GET") //Commands - httpServer.router.HandleFunc(chatsHTTPRoutePath, chat.NewHandler(httpServer.appServices.ChatServices).Add).Methods("POST") - httpServer.router.HandleFunc(chatsHTTPRoutePath+"/sendmessage", chat.NewHandler(httpServer.appServices.ChatServices).SendTextMessage).Methods("POST") - httpServer.router.HandleFunc(chatsHTTPRoutePath+"/{"+chat.DeleteChatPKURLParam+"}", chat.NewHandler(httpServer.appServices.ChatServices).Delete).Methods("DELETE") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.AddLocalRoomURLParam, chat.NewHandler(httpServer.appServices.ChatServices).AddLocalRoom).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.AddLocalServerURLParam, chat.NewHandler(httpServer.appServices.ChatServices).AddLocalServer).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.AddRemoteRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).AddRemoteRoute).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.DeleteLocalRoomByRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).DeleteLocalRoomByRoute).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.DeleteLocalServerByRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).DeleteLocalServerByRoute).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/{"+chat.DeleteVisorByPKURLParam+"}", chat.NewHandler(httpServer.appServices.ChatServices).DeleteVisorByPK).Methods("DELETE") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.LeaveRemoteRoomByRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).LeaveRemoteRoomByRoute).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.LeaveRemoteServerByRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).LeaveRemoteServerByRoute).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendTextMessagePKURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendTextMessage).Methods("POST") } @@ -62,10 +74,15 @@ func (httpServer *Server) AddUserHTTPRoutes() { //Queries httpServer.router.HandleFunc(userHTTPRoutePath+"/"+user.GetInfoURLParam, user.NewHandler(httpServer.appServices.UserServices).GetInfo).Methods("GET") httpServer.router.HandleFunc(userHTTPRoutePath+"/"+user.GetSettingsURLParam, user.NewHandler(httpServer.appServices.UserServices).GetSettings).Methods("GET") + httpServer.router.HandleFunc(userHTTPRoutePath+"/"+user.GetPeerbookURLParam, user.NewHandler(httpServer.appServices.UserServices).GetPeerbook).Methods("GET") //Commands httpServer.router.HandleFunc(userHTTPRoutePath+"/"+user.SetInfoURLParam, user.NewHandler(httpServer.appServices.UserServices).SetInfo).Methods("PUT") httpServer.router.HandleFunc(userHTTPRoutePath+"/"+user.SetSettingsURLParam, user.NewHandler(httpServer.appServices.UserServices).SetSettings).Methods("PUT") + httpServer.router.HandleFunc(userHTTPRoutePath+"/"+user.AddPeerURLParam, user.NewHandler(httpServer.appServices.UserServices).AddPeer).Methods("PUT") + httpServer.router.HandleFunc(userHTTPRoutePath+"/"+user.SetPeerURLParam, user.NewHandler(httpServer.appServices.UserServices).SetPeer).Methods("PUT") + httpServer.router.HandleFunc(userHTTPRoutePath+"/{"+user.DeletePeerURLParam+"}", user.NewHandler(httpServer.appServices.UserServices).DeletePeer).Methods("DELETE") + } // AddNotificationHTTPRoutes adds the sse route @@ -78,7 +95,13 @@ func (httpServer *Server) AddNotificationHTTPRoutes() { // ListenAndServe Starts listening for requests func (httpServer *Server) ListenAndServe(addr *string) { fmt.Println("Serving HTTP on", *addr) - log.Fatal(http.ListenAndServe(*addr, nil)) + srv := &http.Server{ + Addr: *addr, + ReadTimeout: 5 * time.Second, + WriteTimeout: 10 * time.Second, + } + + log.Fatal(srv.ListenAndServe()) } diff --git a/cmd/apps/skychat/internal/inputports/http/static/index.html b/cmd/apps/skychat/internal/inputports/http/static/index.html index 87020c717..cac713162 100644 --- a/cmd/apps/skychat/internal/inputports/http/static/index.html +++ b/cmd/apps/skychat/internal/inputports/http/static/index.html @@ -4,642 +4,38 @@ Skychat - + - - +
        -
        - -
          +
              - - - - + \ No newline at end of file diff --git a/cmd/apps/skychat/internal/inputports/http/static/index.js b/cmd/apps/skychat/internal/inputports/http/static/index.js new file mode 100644 index 000000000..c9d463b53 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/static/index.js @@ -0,0 +1,1319 @@ + +///////////////////////////////////////////////////////////// +//// Classes +///////////////////////////////////////////////////////////// + +class Info{ + constructor(pk,alias,desc,img){ + this.pk = pk; + this.alias = alias; + this.desc = desc; + this.img = img; + } + } + + class Settings{ + constructor(blacklist){ + this.blacklist = blacklist; + } + } + + class User{ + constructor(info,settings,peerbook){ + this.info = info; + this.settings = settings; + this.peerbook = peerbook; + + this.inSettings = false; + } + } + + class Peer{ + constructor(info,alias){ + this.info = info; + this.alias = alias; + } + } + + class Peerbook{ + constructor(peers){ + this.peers = peers + } + } + + class Message{ + constructor(id,origin,ts,root,dest,type,subtype,message,status,seen){ + this.id = id; + this.origin = origin; + this.ts = ts; + this.root = root; + this.dest = dest; + this.type = type; + this.subtype = subtype; + this.message = message; + this.status = status; + this.seen = seen; + } + } + + class Route{ + constructor(visor,server,room){ + this.visor = visor; + this.server = server; + this.room = room; + } + } + + class Room{ + constructor(route,info,messages,isVisible,type,members,mods,muted,blacklist,whitelist){ + this.pk = route.room; + this.route = route; + this.info = info; + this.messages = messages; + this.isVisible = isVisible; + this.type = type; + this.members = members; + this.mods = mods; + this.muted = muted; + this.blacklist = blacklist; + this.whitelist = whitelist; + } + } + + class Server{ + constructor(route,info,members,admins,muted,blacklist,whitelist,rooms){ + this.route = route; + this.info = info; + this.members = members; + this.admins = admins; + this.muted = muted; + this.blacklist = blacklist; + this.whitelist = whitelist; + this.rooms = rooms; + } + } + + class Visor{ + constructor(pk,p2p,server){ + this.pk = pk, + this.p2p = p2p; + this.server = server; + } + } + +/**Dummy Data */ +//Default img +Img = "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAIAAAAHjs1qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5OTMyNUUzOTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjY5OTMyNUU0OTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6Njk5MzI1RTE5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Njk5MzI1RTI5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7FIRCzAAAPn0lEQVR42uyd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" +//Types of Messages +ConnMsgType = 1 +TxtMsgType = 2 +InfoMsgType = 3 +CmdMsgType = 4 + +//subtypes of ConnMsgType +ConnMsgTypeRequest = 1 +ConnMsgTypeAccept = 2 +ConnMsgTypeReject = 3 + +//Types of MessageStatus +MsgStatusSent = 1 +MsgStatusReceived = 2 + +//Types of Rooms +ChatRoomType = 1 +BoardRoomType = 2 + +//Peer1 dummy +dummyPeer1PK = "12345678901" +dummyPeer1Alias = "Dummy-Peer1-Alias" +dummyPeer1Description = "Dummy-Peer1-Description" +dummyPeer1Info = new Info(dummyPeer1PK,dummyPeer1Alias,dummyPeer1Description,Img) +dummyPeer1CustomAlias ="Dummy-Peer1-Custom-Alias" +dummyPeer1 = new Peer(dummyPeer1Info,dummyPeer1CustomAlias) +//Peer2 dummy +dummyPeer2PK = "12345678902" +dummyPeer2Alias = "Dummy-Peer2-Alias" +dummyPeer2Description = "Dummy-Peer2-Description" +dummyPeer2Info = new Info(dummyPeer2PK,dummyPeer2Alias,dummyPeer2Description,Img) +dummyPeer2CustomAlias ="Dummy-Peer2-Custom-Alias" +dummyPeer2 = new Peer(dummyPeer2Info,dummyPeer2CustomAlias) +//Peer3 dummy +dummyPeer3PK = "12345678903" +dummyPeer3Alias = "Dummy-Peer3-Alias" +dummyPeer3Description = "Dummy-Peer3-Description" +dummyPeer3Info = new Info(dummyPeer3PK,dummyPeer3Alias,dummyPeer3Description,Img) +dummyPeer3CustomAlias ="Dummy-Peer3-Custom-Alias" +dummyPeer3 = new Peer(dummyPeer3Info,dummyPeer3CustomAlias) +//User dummy +dummyUserPK = "12345678900" +dummyUserAlias = "Dummy-User-Alias" +dummyUserDescription = "Dummy-User-Description" +dummyUserInfo = new Info(dummyUserPK,dummyUserAlias,dummyUserDescription,Img) +dummyUserSettings = new Settings("") +dummyUserPeerbook = new Peerbook([dummyPeer1,dummyPeer2]) +dummyUser = new User(dummyUserInfo,dummyUserSettings,dummyUserPeerbook) + +/******************************* */ +//GroupChat dummyChat-local +/******************************* */ +///--Route +dummyChatGroupLocal1Visor = dummyUserPK +dummyChatGroupLocal1Server = "1" +dummyChatGroupLocal1Room = "1" +dummyChatGroupLocal1Route = new Route(dummyChatGroupLocal1Visor,dummyChatGroupLocal1Server,dummyChatGroupLocal1Room) +///--Info +dummyChatGroupLocal1PK = dummyChatGroupLocal1Room +dummyChatGroupLocal1Alias = "Dummy-ChatGroup-Local1-Alias" +dummyChatGroupLocal1Description = "Dummy-ChatGroup-Local1-Description" +dummyChatGroupLocal1Info = new Info(dummyChatGroupLocal1PK,dummyChatGroupLocal1Alias,dummyChatGroupLocal1Description,Img) +///--Messages +///---Message 1 +dummyChatGroupLocal1Message1Id = 1 +dummyChatGroupLocal1Message1Origin = dummyPeer1PK +dummyChatGroupLocal1Message1Ts = "2022-11-29 19:03:01" +dummyChatGroupLocal1Message1Root = new Route(dummyPeer1PK,dummyPeer1PK,dummyPeer1PK) +dummyChatGroupLocal1Message1Dest = new Route(dummyChatGroupLocal1Visor,dummyChatGroupLocal1Server,dummyChatGroupLocal1Room) +dummyChatGroupLocal1Message1Type = TxtMsgType +dummyChatGroupLocal1Message1Subtype = 0 +dummyChatGroupLocal1Message1Message = "Hello I am Peer 1" +dummyChatGroupLocal1Message1Status = MsgStatusReceived +dummyChatGroupLocal1Message1Seen = true +dummyChatGroupLocal1Message1 = new Message(dummyChatGroupLocal1Message1Id,dummyChatGroupLocal1Message1Origin,dummyChatGroupLocal1Message1Ts,dummyChatGroupLocal1Message1Root,dummyChatGroupLocal1Message1Dest,dummyChatGroupLocal1Message1Type,dummyChatGroupLocal1Message1Subtype,dummyChatGroupLocal1Message1Message,dummyChatGroupLocal1Message1Status,dummyChatGroupLocal1Message1Seen) +///---Message 2 +dummyChatGroupLocal1Message2Id = 2 +dummyChatGroupLocal1Message2Origin = dummyPeer2PK +dummyChatGroupLocal1Message2Ts = "2022-11-29 19:04:01" +dummyChatGroupLocal1Message2Root = new Route(dummyPeer2PK,dummyPeer2PK,dummyPeer2PK) +dummyChatGroupLocal1Message2Dest = new Route(dummyChatGroupLocal1Visor,dummyChatGroupLocal1Server,dummyChatGroupLocal1Room) +dummyChatGroupLocal1Message2Type = TxtMsgType +dummyChatGroupLocal1Message2Subtype = 0 +dummyChatGroupLocal1Message2Message = "Hello I am Peer 2" +dummyChatGroupLocal1Message2Status = MsgStatusReceived +dummyChatGroupLocal1Message2Seen = true +dummyChatGroupLocal1Message2 = new Message(dummyChatGroupLocal1Message2Id,dummyChatGroupLocal1Message2Origin,dummyChatGroupLocal1Message2Ts,dummyChatGroupLocal1Message2Root,dummyChatGroupLocal1Message2Dest,dummyChatGroupLocal1Message2Type,dummyChatGroupLocal1Message2Subtype,dummyChatGroupLocal1Message2Message,dummyChatGroupLocal1Message2Status,dummyChatGroupLocal1Message2Seen) +///---Message 3 +dummyChatGroupLocal1Message3Id = 3 +dummyChatGroupLocal1Message3Origin = dummyUserPK +dummyChatGroupLocal1Message3Ts = "2022-11-29 19:05:01" +dummyChatGroupLocal1Message3Root = new Route(dummyUserPK,dummyUserPK,dummyUserPK) +dummyChatGroupLocal1Message3Dest = new Route(dummyChatGroupLocal1Visor,dummyChatGroupLocal1Server,dummyChatGroupLocal1Room) +dummyChatGroupLocal1Message3Type = TxtMsgType +dummyChatGroupLocal1Message3Subtype = 0 +dummyChatGroupLocal1Message3Message = "Hello I am the User" +dummyChatGroupLocal1Message3Status = MsgStatusReceived +dummyChatGroupLocal1Message3Seen = true +dummyChatGroupLocal1Message3 = new Message(dummyChatGroupLocal1Message3Id,dummyChatGroupLocal1Message3Origin,dummyChatGroupLocal1Message3Ts,dummyChatGroupLocal1Message3Root,dummyChatGroupLocal1Message3Dest,dummyChatGroupLocal1Message3Type,dummyChatGroupLocal1Message3Subtype,dummyChatGroupLocal1Message3Message,dummyChatGroupLocal1Message3Status,dummyChatGroupLocal1Message3Seen) +///---Message 4 +dummyChatGroupLocal1Message4Id = 3 +dummyChatGroupLocal1Message4Origin = dummyPeer3PK +dummyChatGroupLocal1Message4Ts = "2022-11-29 19:06:01" +dummyChatGroupLocal1Message4Root = new Route(dummyPeer3PK,dummyPeer3PK,dummyPeer3PK) +dummyChatGroupLocal1Message4Dest = new Route(dummyChatGroupLocal1Visor,dummyChatGroupLocal1Server,dummyChatGroupLocal1Room) +dummyChatGroupLocal1Message4Type = TxtMsgType +dummyChatGroupLocal1Message4Subtype = 0 +dummyChatGroupLocal1Message4Message = "Hello I am Peer 3" +dummyChatGroupLocal1Message4Status = MsgStatusReceived +dummyChatGroupLocal1Message4Seen = true +dummyChatGroupLocal1Message4 = new Message(dummyChatGroupLocal1Message4Id,dummyChatGroupLocal1Message4Origin,dummyChatGroupLocal1Message4Ts,dummyChatGroupLocal1Message4Root,dummyChatGroupLocal1Message4Dest,dummyChatGroupLocal1Message4Type,dummyChatGroupLocal1Message4Subtype,dummyChatGroupLocal1Message4Message,dummyChatGroupLocal1Message4Status,dummyChatGroupLocal1Message4Seen) + + +dummyChatGroupLocal1Messages = [dummyChatGroupLocal1Message1,dummyChatGroupLocal1Message2,dummyChatGroupLocal1Message3,dummyChatGroupLocal1Message4] +///--isVisible +dummyChatGroupLocal1IsVisible = false +///--Type +dummyChatGroupLocal1Type = ChatRoomType +///--Members +dummyChatGroupLocal1Members = [dummyUser,dummyPeer1,dummyPeer2,dummyPeer3] +///--Room +dummyChatGroupLocal1 = new Room(dummyChatGroupLocal1Route,dummyChatGroupLocal1Info,dummyChatGroupLocal1Messages,dummyChatGroupLocal1IsVisible,dummyChatGroupLocal1Type,dummyChatGroupLocal1Members,null,null,null,null) +//TODO:dummyChatGroup + + +//Server dummyChat-local +//TODO:dummyChatServer + +/******************************* */ +//P2P dummyChat-remote (Peer1) +/******************************* */ +///--Route +dummyChatP2P1Visor = dummyPeer1PK +dummyChatP2P1Server = dummyPeer1PK +dummyChatP2P1Room = dummyPeer1PK +dummyChatP2P1Route = new Route(dummyChatP2P1Visor,dummyChatP2P1Server,dummyChatP2P1Room) +///--Info +dummyChatP2P1PK = dummyPeer1PK +dummyChatP2P1Alias = "Dummy-ChatP2P-Remote1-Alias" +dummyChatP2P1Description = "Dummy-ChatP2P-Remote1-Description" +dummyChatP2P1Info = new Info(dummyChatP2P1PK,dummyChatP2P1Alias,dummyChatP2P1Description,Img) +///--Messages +///---Message 1 +dummyChatP2P1Message1Id = 1 +dummyChatP2P1Message1Origin = dummyPeer1PK +dummyChatP2P1Message1Ts = "2022-11-29 19:03:01" +dummyChatP2P1Message1Root = new Route(dummyPeer1PK,dummyPeer1PK,dummyPeer1PK) +dummyChatP2P1Message1Dest = new Route(dummyUserPK,dummyUserPK,dummyUserPK) +dummyChatP2P1Message1Type = TxtMsgType +dummyChatP2P1Message1Subtype = 0 +dummyChatP2P1Message1Message = "Hello" +dummyChatP2P1Message1Status = MsgStatusReceived +dummyChatP2P1Message1Seen = true +dummyChatP2P1Message1 = new Message(dummyChatP2P1Message1Id,dummyChatP2P1Message1Origin,dummyChatP2P1Message1Ts,dummyChatP2P1Message1Root,dummyChatP2P1Message1Dest,dummyChatP2P1Message1Type,dummyChatP2P1Message1Subtype,dummyChatP2P1Message1Message,dummyChatP2P1Message1Status,dummyChatP2P1Message1Seen) +///---Message 2 +dummyChatP2P1Message2Id = 2 +dummyChatP2P1Message2Origin = dummyUserPK +dummyChatP2P1Message2Ts = "2022-11-29 19:05:01" +dummyChatP2P1Message2Root = new Route(dummyUserPK,dummyUserPK,dummyUserPK) +dummyChatP2P1Message2Dest = new Route(dummyPeer1PK,dummyPeer1PK,dummyPeer1PK) +dummyChatP2P1Message2Type = TxtMsgType +dummyChatP2P1Message2Subtype = 0 +dummyChatP2P1Message2Message = "Hello Back" +dummyChatP2P1Message2Status = MsgStatusSent +dummyChatP2P1Message2Seen = true +dummyChatP2P1Message2 = new Message(dummyChatP2P1Message2Id,dummyChatP2P1Message2Origin,dummyChatP2P1Message2Ts,dummyChatP2P1Message2Root,dummyChatP2P1Message2Dest,dummyChatP2P1Message2Type,dummyChatP2P1Message2Subtype,dummyChatP2P1Message2Message,dummyChatP2P1Message2Status,dummyChatP2P1Message2Seen) + + +dummyChatP2P1Messages = [dummyChatP2P1Message1,dummyChatP2P1Message2] +///--isVisible +dummyChatP2P1IsVisible = true +///--Type +dummyChatP2P1Type = ChatRoomType +///--Room +dummyChatP2P1 = new Room(dummyChatP2P1Route,dummyChatP2P1Info,dummyChatP2P1Messages,dummyChatP2P1IsVisible,dummyChatP2P1Type,null,null,null,null,null) + +/******************************* */ +//P2P dummyChat-remote (Peer2) +/******************************* */ +///--Route +dummyChatP2P2Visor = dummyPeer2PK +dummyChatP2P2Server = dummyPeer2PK +dummyChatP2P2Room = dummyPeer2PK +dummyChatP2P2Route = new Route(dummyChatP2P2Visor,dummyChatP2P2Server,dummyChatP2P2Room) +///--Info +dummyChatP2P2PK = dummyPeer2PK +dummyChatP2P2Alias = "Dummy-ChatP2P-Remote2-Alias" +dummyChatP2P2Description = "Dummy-ChatP2P-Remote1-Description" +dummyChatP2P2Info = new Info(dummyChatP2P2PK,dummyChatP2P2Alias,dummyChatP2P2Description,Img) +///--Messages +///---Message 1 +dummyChatP2P2Message1Id = 1 +dummyChatP2P2Message1Origin = dummyPeer2PK +dummyChatP2P2Message1Ts = "2022-11-29 20:03:00" +dummyChatP2P2Message1Root = new Route(dummyPeer2PK,dummyPeer2PK,dummyPeer2PK) +dummyChatP2P2Message1Dest = new Route(dummyUserPK,dummyUserPK,dummyUserPK) +dummyChatP2P2Message1Type = TxtMsgType +dummyChatP2P2Message1Subtype = 0 +dummyChatP2P2Message1Message = "Hello User" +dummyChatP2P2Message1Status = MsgStatusReceived +dummyChatP2P2Message1Seen = true +dummyChatP2P2Message1 = new Message(dummyChatP2P2Message1Id,dummyChatP2P2Message1Origin,dummyChatP2P2Message1Ts,dummyChatP2P2Message1Root,dummyChatP2P2Message1Dest,dummyChatP2P2Message1Type,dummyChatP2P2Message1Subtype,dummyChatP2P2Message1Message,dummyChatP2P2Message1Status,dummyChatP2P2Message1Seen) +///---Message 2 +dummyChatP2P2Message2Id = 2 +dummyChatP2P2Message2Origin = dummyUserPK +dummyChatP2P2Message2Ts = "2022-11-29 20:05:01" +dummyChatP2P2Message2Root = new Route(dummyUserPK,dummyUserPK,dummyUserPK) +dummyChatP2P2Message2Dest = new Route(dummyPeer2PK,dummyPeer2PK,dummyPeer2PK) +dummyChatP2P2Message2Type = TxtMsgType +dummyChatP2P2Message2Subtype = 0 +dummyChatP2P2Message2Message = "Hello Peer2" +dummyChatP2P2Message2Status = MsgStatusSent +dummyChatP2P2Message2Seen = false +dummyChatP2P2Message2 = new Message(dummyChatP2P2Message2Id,dummyChatP2P2Message2Origin,dummyChatP2P2Message2Ts,dummyChatP2P2Message2Root,dummyChatP2P2Message2Dest,dummyChatP2P2Message2Type,dummyChatP2P2Message2Subtype,dummyChatP2P2Message2Message,dummyChatP2P2Message2Status,dummyChatP2P2Message2Seen) + + +dummyChatP2P2Messages = [dummyChatP2P2Message1,dummyChatP2P2Message2] +///--isVisible +dummyChatP2P2IsVisible = true +///--Type +dummyChatP2P2Type = ChatRoomType +///--Room +dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messages,dummyChatP2P2IsVisible,dummyChatP2P2Type,null,null,null,null,null) + + +//GroupChat dummyChat-peer +//TODO: +//Server dummyChat-peer +//TODO: + +/**End Dummy Data */ + +///////////////////////////////////////////////////////////// +//// Skychat +///////////////////////////////////////////////////////////// + class Skychat { + constructor() {} + + fetchData(test){ + if (!test) { + return Promise.all([this.getUserInfo(), + this.getUserSettings(), + this.getChatAll() + ]).then(([userInfo,userSettings,chats]) => { + this.user = new User(userInfo,userSettings); + this.chats = chats + return this.init() + }); + } + else { + return new Promise((resolve,reject)=>{ + setTimeout(() => { + resolve(10); + }, 1*100) + }).then(()=> { + this.user = dummyUser + this.chats = [dummyChatP2P1,dummyChatP2P2,dummyChatGroupLocal1]; + return this.init() + }) + + } + } + + init(){ + this.addUser(this.user); + this.addAddLocal(this.user); + this.addAddRemote(this.user); + + this.chat = null; + if (this.chats != null){ + this.chats.forEach(r => this._addChat(r)); + } + + this.notificationsSubscribe(); + return this; + } + +///////////////////////////////////////////////////////////// +//// UI specific functions +///////////////////////////////////////////////////////////// + + addUser(c) { + document.getElementById('user').innerHTML += + ` + +
              +
              + ${c.info.alias} +
              +
              + ${c.info.pk} +
              +
              +
              `; + + } + + addAddLocal(c){ + document.getElementById('addLocal').innerHTML += + ` +
              Add Local Server and Rooms
              +
              `; + } + + addAddRemote(c){ + document.getElementById('addRemote').innerHTML += + ` +
              Add Remote Server and Rooms
              +
              `; + } + + _updateUser(c) { + this.user = c + + document.getElementById('user').innerHTML = + ` + +
              +
              + ${c.info.alias} +
              +
              + ${c.info.pk} +
              +
              +
              `; + } + + _addChat(r) { + if (!this.chats.includes(r)) { + this.chats.push(r); + } + + + let lastMsg = this.getLastMessageFromRoute(r.route) + + let local = "" + if (r.route.visor == this.user.info.pk){ + local = String.fromCharCode(0x2302) + } + + document.getElementById('chatList').innerHTML += + ``; + + } + + _updateChat(r) { + var index = this.getChatIndexFromRoute(r.route) + this.chats[index] = r + + let lastMsg = this.getLastMessageFromRoute(r.route) + + let local = "" + if (r.route.visor == this.user.info.pk){ + local = String.fromCharCode(0x2302) + } + + document.getElementById('chat_'+ r.pk).innerHTML = + `
            • + +
              +
              + ${local} ${r.info.alias} +
              +
              + ${r.pk} +
              +
              + ${lastMsg} +
              +
              + +
            • `; + + if (this.chat = r.pk){ + document.getElementById('messages').innerHTML = ''; + this.getMessagesFromRoute(r.route).forEach(msg => this._showMessage(msg,r.route)); + document.getElementById('chatButtonsContainer').classList.remove('hidden'); + document.getElementById('msgForm').classList.remove('hidden'); + document.getElementById('msgField').focus(); + + let msgArea = document.getElementById('messages'); + msgArea.scrollTop = msgArea.scrollHeight; + } + } + + + _showSettings(){ + this.user.inSettings = true; + + let info = this.user.info; + let settings = this.user.settings; + this.chat = null + + //unselect chats in sidebar + document.querySelectorAll('.destination').forEach(item => + { + item.classList.remove('active'); + }); + + document.getElementById('form').innerHTML = + ``; + //empty messages + document.getElementById('messages').innerHTML = ''; + //empty header + document.getElementById('chatHeaderInformation').innerHTML = '' + //hide send message bar and button + document.getElementById('chatButtonsContainer').classList.add('hidden'); + document.getElementById('msgForm').classList.add('hidden'); + + document.getElementById('form').innerHTML += + `
              +
              X
              + +
              +
              Settings
              +
              + + +
              +
              +
              +
              Peerbook
              +
              +
              `; + } + + _hideSettings(){ + this.user.inSettings = false; + document.getElementById('form').innerHTML = + ``; + } + + _showAddLocal(){ + + this.user.inAddLocal = true; + + //unselect chats in sidebar + document.querySelectorAll('.destination').forEach(item => + { + item.classList.remove('active'); + }); + + document.getElementById('form').innerHTML = + ``; + //empty messages + document.getElementById('messages').innerHTML = ''; + //empty header + document.getElementById('chatHeaderInformation').innerHTML = '' + //hide send message bar and button + document.getElementById('chatButtonsContainer').classList.add('hidden'); + document.getElementById('msgForm').classList.add('hidden'); + + document.getElementById('form').innerHTML += + `
              +
              X
              +
              To add a local Server or Group you have to insert the right Public Keys
              +
            • For new server you can leave server pk empty but have to give an info
            • +
            • For a new group you have to give the PK of the server where you want to add the room to and an info
            • +
              ServerPK
              +
              + +
              Info
              + + + +
              +
              `; + + } + + _hideInAddLocal(){ + this.user.inAddLocal = false; + document.getElementById('form').innerHTML = + ``; + } + + _showAddRemote(){ + + this.user.inAddRemote = true; + + //unselect chats in sidebar + document.querySelectorAll('.destination').forEach(item => + { + item.classList.remove('active'); + }); + + document.getElementById('form').innerHTML = + ``; + //empty messages + document.getElementById('messages').innerHTML = ''; + //empty header + document.getElementById('chatHeaderInformation').innerHTML = '' + //hide send message bar and button + document.getElementById('chatButtonsContainer').classList.add('hidden'); + document.getElementById('msgForm').classList.add('hidden'); + + document.getElementById('form').innerHTML += + `
              +
              X
              +
              To add a remote P2P or Group you have to insert the right Public Keys
              +
            • P2P: VisorPK
            • +
            • Group/Server: VisorPK & ServerPK & RoomPK
            • +
              + + + + +
              +
              VisorPK --------------------------- ServerPK -------------------------- RoomPK
              +
              + `; + } + + _hideInAddRemote(){ + this.user.inAddRemote = false; + document.getElementById('form').innerHTML = + ``; + } + + + _showMessage(msg,route) { + let c = this.user; + + switch(msg.type) { + case 1: + let connMsgOrigin + if (msg.sender == c.info.pk){ + connMsgOrigin = "user" + } else { + connMsgOrigin = "peer" + } + let connMsg + if (msg.subtype == 1){ + connMsg = "chat request from " + connMsgOrigin + } + else if (msg.subtype == 2){ + connMsg = "chat accepted" + } + else if (msg.subtype == 3){ + connMsg = "chat rejected" + } + else { + connMsg = "undefined chat type message" + } + document.getElementById('messages').innerHTML += `
            • ${connMsg}
            • `; + break; + case 2: + if (!msg.date) { + const liClassName = msg.origin === c.info.pk ? 'content-right' : 'content-left'; + const containerClassName = msg.origin === c.info.pk ? 'msg-sent' : 'msg-received'; + + let msgArea = document.getElementById('messages'); + let mustScroll = (msgArea.scrollHeight - msgArea.scrollTop) === msgArea.userHeight; + + if (route.visor == route.server){ + //P2P-Chat + document.getElementById('messages').innerHTML += + `
            • ${msg.message}
              ${msg.ts}
            • `; + } + else{ + document.getElementById('messages').innerHTML += + `
            • ${this.getAliasFromPKAndRoute(msg.origin,route)}
              ${msg.origin}
              ${msg.message}
              ${msg.ts}
            • `; + } + if (mustScroll) { + msgArea.scrollTop = msgArea.scrollHeight; + } + } else { + let date = msg.date.getFullYear().toString().padStart(2, '0') + '-'; + date += (msg.date.getMonth() + 1).toString().padStart(2, '0') + '-'; + date += msg.date.getDate().toString().padStart(2, '0'); + + document.getElementById('messages').innerHTML += `
            • ${date}
            • `; + } + break; + case 3: + let infoMsg + if (msg.origin == c.info.pk) { + infoMsg = "sent info to peer" + } else { + infoMsg = "peer updated info" + } + document.getElementById('messages').innerHTML += `
            • ${infoMsg}
            • `; + break; + } + } + + _selectChat(pk) { + if (this.chat === pk) { + return; + } + let chat = this.chats[this.getChatIndexFromPK(pk)] + let route = chat.route + + this._hideSettings(); + this._hideInAddLocal(); + this._hideInAddRemote(); + + this.chat = pk; + document.querySelectorAll('.destination').forEach(item => { + const pkArea = item.getElementsByClassName('pk')[0]; + + if (pkArea.innerText === pk) { + item.classList.add('active'); + } else { + item.classList.remove('active'); + } + }); + + document.getElementById('messages').innerHTML = ''; + document.getElementById('chatHeaderInformation').innerHTML = '' + document.getElementById('chatHeaderInformation').innerHTML += `
              ${chat.info.alias}
              `; + document.getElementById('chatHeaderInformation').innerHTML += `
              ${chat.info.desc}
              `; + document.getElementById('chatHeaderInformation').innerHTML += `
              Visor: ${chat.route.visor}
              `; + document.getElementById('chatHeaderInformation').innerHTML += `
              Server: ${chat.route.server}
              `; + document.getElementById('chatHeaderInformation').innerHTML += `
              Room: ${chat.route.room}
              `; + + this.getMessagesFromRoute(route).forEach(msg => this._showMessage(msg,route)); + document.getElementById('chatButtonsContainer').classList.remove('hidden'); + document.getElementById('msgForm').classList.remove('hidden'); + document.getElementById('msgField').focus(); + + let msgArea = document.getElementById('messages'); + msgArea.scrollTop = msgArea.scrollHeight; + + } + + ///////////////////////////////////////////////////////////// + //// HTTP /user + ///////////////////////////////////////////////////////////// + //// GET + //returns [Info] from [User] + getUserInfo(){ + return fetch('user/getInfo', { method: 'GET', body: null }) + .then(res => { + if (res.ok) { + return res.json().then(i => { + var info = new Info(i.Pk,i.Alias,i.Desc,i.Img); + return info + }); + } else { + res.text().then(text => alert(`Failed to get info`)); + } + }); + } + //returns [Settings] from [User] + getUserSettings(){ + + return fetch('user/getSettings', { method: 'GET', body: null }) + .then(res => { + if (res.ok) { + return res.json().then(s => { + var settings = new Settings(s.Blacklist); + return settings; + }); + } else { + res.text().then(text => alert(`Failed to get settings`)); + } + }); + + } + //// PUT + setUserInfo(el){ + let info = new Info(this.user.info.pk, el[0].value.trim(), el[1].value.trim(), el[2].value.trim()); + + if (info.alias.length == 0) { + return; + } + + fetch('user/setInfo', { method: 'PUT', body: JSON.stringify({ alias: info.alias, desc: info.desc, img: info.img}) }) + .then(res => { + if (res.ok) { + this.getUserInfo().then(info => { + this._updateUser(new User(info, this.user.settings)); + }); + } else { + res.text().then(text => alert(`Failed to set info`)); + } + }); + + } + + setUserSettings(el){ + let settings = new Settings(el[0].value.trim()); + + //[]:check for regex of blacklist array. --> maybe add one pk after another to blacklist. + + fetch('user/setSettings', { method: 'PUT', body: JSON.stringify({ blacklist: settings.blacklist}) }) + .then(res => { + if (res.ok) { + this.getUserSettings().then(settings => { + this._updateUser(new User(this.user.info, settings)); + }); + } else { + res.text().then(text => alert(`Failed to set settings`)); + } + }); + + } +///////////////////////////////////////////////////////////// +//// HTTP /chats +///////////////////////////////////////////////////////////// +//// GET + getRouteHTTP(r){ + return new Route(r.Visor,r.Server,r.Room) + } + getInfoHTTP(i){ + return new Info(i.Pk,i.Alias,i.Desc,i.Img) + } + + getMembersHTTP(mb){ + var members = [] + Object.keys(mb).forEach(m => { + var mInfo = this.getInfoHTTP(mb[m].Info) + members.push(new Peer(mInfo,mb[m].Alias))}) + return members + } + + getMessagesHTTP(ms){ + var msgs = [] + ms.forEach(m => { msgs.push(new Message(m.Id,m.Origin,m.Time,m.Root,m.Dest,m.Msgtype,m.MsgSubtype,m.Message,m.Status,m.Seen))}) + return msgs + } + + getRoomHTTP(r){ + let info = this.getInfoHTTP(r.Info) + var msgs = [] + if (r.Msgs != null){ + msgs = this.getMessagesHTTP(r.Msgs) + } + let members = [] + if (r.Members != null){ + if (Object.keys(r.Members).length){ + members = this.getMembersHTTP(r.Members) + } + } + let route = this.getRouteHTTP(r.PKRoute) + let room = new Room(route,info,msgs,r.IsVisible,r.Type,members,r.Mods,r.Muted,r.Blacklist,r.Whitelist) + console.log("getRoomHTTP") + console.log(room) + return room + } + + getRoomsHTTP(rms){ + var rooms = [] + Object.keys(rms).forEach(r => rooms.push(this.getRoomHTTP(rms[r]))) + return rooms + } + + getServerHTTP(s){ + var info = new Info(s.Info.Pk,s.Info.Alias,s.Info.Desc,s.Info.Img) + var members = [] + if (s.Members != null){ + if (Object.keys(s.Members).length){ + members = this.getMembersHTTP(s.Members) + } + } + var rooms = this.getRoomsHTTP(s.Rooms) + var route = this.getRouteHTTP(s.PKRoute) + var server = new Server(route,info,members,s.Admins,s.Muted,s.Blacklist,s.whitelist,rooms) + return server + } + + //returns an array of [Chat] + getChatAll(){ + + return fetch('chats', { method: 'GET', body: null }) + .then(res => { + if (res.ok) { + return res.json().then(visors => { + + var v_ = [] + console.log(visors) + if (visors != null){ + visors.forEach( v => { + console.log(v) + if (v.P2P != null) { + if (Object.keys(v.P2P).length){ + var p2p = this.getRoomHTTP(v.P2P) + } + } else { + p2p = null + } + var s_ = [] + if (v.Server != null){ + Object.keys(v.Server).forEach( s => { + s_.push(this.getServerHTTP(v.Server[s])) + }) + } + v_.push(new Visor(v.PK,p2p,s_)) + }) + + return this.getSortedChats(v_) + } + else { + console.log("No chats available") + } + }); + } else { + res.text().then(text => alert(`Failed to get chats`)); + } + }); + } + + //returns all chats so UI can display it + getSortedChats(visors){ + //for the first working skychat there is no sorting + var cs = [] + Object.keys(visors).forEach(v => { + if (visors[v].pk != undefined){ + cs.push(visors[v].p2p) + } + Object.keys(visors[v].server).forEach(s => { + Object.keys(visors[v].server[s].rooms).forEach(r =>{ + cs.push(visors[v].server[s].rooms[r]) + }) + }) + }) + return cs + } + + //returns the [Room] with the given route + getRoomByRoute(route){ + const visorpk = route.visor + const serverpk = route.server + const roompk = route.room + + const params = new URLSearchParams({visor: visorpk, server: serverpk,room: roompk}) + + return fetch('chats/'+ 'getRoom?' + params, { method: 'GET', body: null}) + .then(res => { + if (res.ok) { + return res.json().then(r => { + console.log(r) + return this.getRoomHTTP(r) + }) + } else { + res.text().then(text => alert(`Failed to get chat: ${text}`)); + } + }).catch(e => alert(e.message)); + ; + + } +//// POST + //adLocalRoute adds a new Server or Room in dependency on the given info + addLocalRoute(el){ + const visorpk = this.user.info.pk + const serverpk = this.processPk(el[0].value.trim()); + const alias = el[1].value.trim(); + let description = el[2].value.trim(); + + if (alias == ""){ + alert('Please enter an alias') + return; + } + + if (description == ""){ + alert('Description was not given and therefore set to "-"') + description = '-' + } + + if (serverpk != ""){ + if (serverpk.length != 66) { + alert('ServerPK: Public keys must be 66 characters long.') + return; + } + + if (!/^[0-9a-fA-F]+$/.test(serverpk)) { + alert('ServerPK: The public key includes invalid characters.') + return; + } + + fetch('chats/' + "addLocalRoom", { method: 'POST', body: JSON.stringify({ visorpk: visorpk, serverpk: serverpk, alias: alias, desc: description, img: null, type:null}) }) + .then(res => { + if (res.ok) { + res.text().then(); + } else { + res.text().then(text => alert(`Failed to add local room: ${text}`)); + } + }).catch(e => alert(e.message)); + }else{ + fetch('chats/' + "addLocalServer", { method: 'POST', body: JSON.stringify({ visorpk: visorpk, alias: alias, desc: description, img: ""}) }) + .then(res => { + if (res.ok) { + res.text().then(); + } else { + res.text().then(text => alert(`Failed to add local server: ${text}`)); + } + }).catch(e => alert(e.message)); + } + } + + //tries to add the given route + //returns nothing + addRemoteRoute(el) { + const visorpk = this.processPk(el[0].value.trim()); + const serverpk = this.processPk(el[1].value.trim()); + const roompk = this.processPk(el[2].value.trim()); + + + //for the moment it is only possible to add perfectly fine defined routes. + //TODO: Make this more user friendly + + if (visorpk.length != 66) { + alert('VisorPK: Public keys must be 66 characters long.') + return; + } + + if (!/^[0-9a-fA-F]+$/.test(visorpk)) { + alert('VisorPK: The public key includes invalid characters.') + return; + } + + if (serverpk != "") { + if (serverpk.length != 66) { + alert('ServerPK: Public keys must be 66 characters long.') + return; + } + + if (!/^[0-9a-fA-F]+$/.test(serverpk)) { + alert('ServerPK: The public key includes invalid characters.') + return; + } + } + + if (roompk != ""){ + + if (roompk.length != 66) { + alert('RoomPK: Public keys must be 66 characters long.') + return; + } + + if (!/^[0-9a-fA-F]+$/.test(roompk)) { + alert('RoomPK: The public key includes invalid characters.') + return; + } + } + + if (visorpk == this.user.info.pk){ + alert('You do not have to join a server that is hosted on your visor') + return; + } + + document.getElementById('visorPkToAdd').value = ""; + document.getElementById('serverPkToAdd').value = ""; + document.getElementById('roomPkToAdd').value = ""; + + + //TODO: Make if or switch case -> when visorpk is same as userpk and serverpk and roompk is empty then make new server with one room + //and if visorpk and serverpk is defined but roompk is empty then add new room to server + fetch('chats/' + "addRemoteRoute", { method: 'POST', body: JSON.stringify({ visorpk: visorpk, serverpk: serverpk, roompk: roompk}) }) + .then(res => { + if (res.ok) { + res.text().then(); + } else { + res.text().then(text => alert(`Failed to add chat: ${text}`)); + } + }) + .catch(e => alert(e.message)); + } + + //tries to send a [Message] to the current selected [Chat] + //returns nothing + sendMessage(el) { + const msg = el[0].value; + + if (msg.length == 0) { + return; + } + + let route = this.chats[this.getChatIndexFromPK(this.chat)].route + + const visorpk = route.visor; + const serverpk = route.server; + const roompk = route.room; + + fetch('chats/' + "sendTxtMsg", { method: 'POST', body: JSON.stringify({ visorpk: visorpk, serverpk: serverpk, roompk: roompk, message: msg}) }) + .then(res => { + if (res.ok) { + res.text().then(); + el[0].value = ''; + } else { + res.text().then(text => alert(`Failed to send message: ${text}`)); + } + }) + .catch(e => alert(e.message)); + } +//// DELETE + + //tries to delete the current selected [Chat] + deleteChat() { + if (!this.chat) { + return; + } + + const response = window.confirm("Are you sure you want to delete the chat?"); + + if (response) { + + fetch('chats' + '/' + this.chat.toString() , { method: 'DELETE' }) + .then(res => { + if (res.ok) { + res.text().then(); + this.chats = this.chats.filter(v => v.pk != this.chat); + + document.getElementById('messages').innerHTML = ''; + document.getElementById('chatButtonsContainer').classList.add('hidden'); + document.getElementById('msgForm').classList.add('hidden'); + document.querySelectorAll('.destination').forEach(item => { + + const pkArea = item.getElementsByClassName('pk')[0]; + + if (pkArea.innerText === this.chat) { + item.parentNode.removeChild(item); + }}); + this.chat = null; + } else { + //TODO: add visor-server-room pks to alert text + res.text().then(text => alert(`Failed to delete chat ${this.chat}: ${text}`)); + } + }) + + } + else{ + return; + } + } + +///////////////////////////////////////////////////////////// +//// HTTP /notification +///////////////////////////////////////////////////////////// +//// Subscribe + notificationsSubscribe() { + const source = new EventSource('/notifications'); + source.onmessage = (event) => { + const data = JSON.parse(event.data); + console.log(data) + const notifMessage = JSON.parse(data.message) + let visorpk = notifMessage.visorpk + let serverpk = notifMessage.serverpk + let roompk = notifMessage.roompk + let route = new Route(visorpk,serverpk,roompk) + + switch(data.type) { + //NewAddRouteNotifyType + case 1: + console.log("new add route notification") + this.getRoomByRoute(route).then(c => { + if (this.chats == null){ + this.chats = [] + } + this._addChat(c) + this._selectChat(roompk) + }) + break; + //NewChatNotifType + case 2: + console.log("new peer chat notification") + this.getRoomByRoute(route).then(chat => { + if (this.chats == null){ + this.chats = [] + } + this._addChat(chat) + }) + break; + //NewMsgNotifType + case 3: + //Fetch data of chat with new message from HTTP + + console.log("new message notification") + const message = JSON.parse(notifMessage.message) + visorpk = message.Dest.Visor + serverpk = message.Dest.Server + roompk = message.Dest.Room + route = new Route(visorpk,serverpk,roompk) + console.log(message) + + this.getRoomByRoute(route).then(c => { + this._updateChat(c) + }) + break; + default: + console.log("unknown notification") + break; + } + } + }; + +///////////////////////////////////////////////////////////// +//// Helper Functions to get or process sub steps +///////////////////////////////////////////////////////////// + //returns the given pk as lowerCase representation + processPk(pk) { + return pk.toLowerCase(); + } + + //returns the index inside this.chats of the given route + getChatIndexFromPK(pk) { + let arr = this.chats; + for (var i=0, iLen=arr.length; i { + window.app = skychat + }); + + function showDropdown() { + document.getElementById("myDropdown").classList.toggle("show"); + } + + // Close the dropdown if the user clicks outside of it + window.onclick = function(event) { + if (!event.target.matches(".dropbtn")) { + var dropdowns = document.getElementsByClassName("dropdown-content"); + var i; + for (i = 0; i < dropdowns.length; i++) { + var openDropdown = dropdowns[i]; + if (openDropdown.classList.contains("show")) { + openDropdown.classList.remove("show"); + } + } + } + } \ No newline at end of file diff --git a/cmd/apps/skychat/internal/inputports/http/static/stylesheet.css b/cmd/apps/skychat/internal/inputports/http/static/stylesheet.css new file mode 100644 index 000000000..b15441ebb --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/static/stylesheet.css @@ -0,0 +1,464 @@ +html { + font-family: sans-serif; + font-size: 13px; + } + + body { + display: flex; + height: 100vh; + margin: 0; + background: #455164; + } + + a { + text-decoration: none; + color: inherit; + } + + ul { + list-style: none; + padding: 0; + margin: 0; + } + + .sidebar { + display: flex; + flex-direction: column; + width: 240px; + padding: 1em; + color: #99a2b4; + overflow: auto; + } + + .user{ + flex: 0; + margin-top: 1em; + margin-bottom: 1em; + } + + .user a { + display: flex; + border-bottom: solid black 1px; + margin: 0 -1em; + padding: 1em; + } + + .user a .active { + color: white; + background: black; + cursor: unset; + } + + .user a .small-profile-picture { + width: 30px; + height: 30px; + margin-right: 10px; + object-fit: cover; + flex-shrink: 0; + } + + .user a .text-container { + min-width: 0; + } + + .user a .alias{ + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + + .user a .pk { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + + .chat-list { + flex: 1; + margin-top: 1em; + } + + .chat-list a { + display: flex; + border-bottom: solid black 1px; + margin: 0 -1em; + padding: 1em; + } + + .chat-list a.active { + color: white; + background: black; + cursor: unset; + } + + .chat-list a .small-profile-picture { + width: 30px; + height: 30px; + margin-right: 10px; + object-fit: cover; + flex-shrink: 0; + } + + .chat-list a .text-container { + min-width: 0; + } + + .chat-list a .pk { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + } + + .chat-list a .msg { + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; + margin-top: 2px; + opacity: 0.8; + font-size: 11px; + } + + .chat-list a .unreaded { + color: white; + background: red; + border-radius: 5px; + padding: 5px 8px; + margin-left: 5px; + flex-shrink: 0; + } + + .chatbox { + flex: 1; + display: flex; + flex-direction: column; + margin: 0.3em; + background: white; + border-radius: 2px; + } + + .message-list { + background-color: #161a20; + overflow: auto; + padding: 1em; + flex: 1; + } + + .content-left { + text-align: left; + } + + .content-right { + text-align: right; + } + + .content-center { + text-align: center; + } + + .date-container { + display: inline-block; + background-color: #eaeaea; + padding: 10px; + font-size: 12px; + border-radius: 10px; + margin-bottom: 5px; + } + + .msg-container { + color: white; + padding: 8px 12px; + border-radius: 10px; + margin-bottom: 5px; + display: inline-block; + max-width: 80%; + font-size: 14px; + line-height: 1.3; + } + + .msg-received { + background-color: #525f73; + border-bottom-left-radius: 0; + } + + .msg-sent { + background-color: #5ba74a; + border-bottom-right-radius: 0; + } + + .msg-alias { + color: rgb(11, 14, 107); + } + + .message-pk { + font-size: 11px; + opacity: 0.5; + text-align: right; + margin-top: 3px; + } + + .message-time { + font-size: 11px; + opacity: 0.5; + text-align: right; + margin-top: 3px; + } + + .message-form { + flex-shrink: 0; + display: flex; + padding: 0.3em; + background: #eee; + border-top: 2px solid #ddd; + } + + input[type=text] { + flex: 1; + padding: 0.5em; + margin-right: 1em; + border: 1px solid #ddd; + border-radius: 2px; + } + + input[type=submit] { + padding: 0.5em 2em; + background: #f6f6f6; + border: 1px solid #ddd; + border-radius: 2px; + outline: none; + } + + .chat-form input[type=submit] { + padding: 0.5em 0.7em; + } + + .hidden { + display: none !important; + } + + .chat-header-container { + display: inline-block; + border: 1px solid black; + background: #303948; + } + + .chat-header-information { + margin-top: 0.5em; + margin-left: 2em; + color: white; + } + + .chat-header-column { + float: left; + } + + .chat-header-column-left { + width: 95%; + } + + .chat-header-column-right { + width: 5%; + } + +/*Stolen from https://codepen.io/danimerida2000/pen/wVXegX */ +.showLeft { + text-shadow: white !important; + color: black !important; + padding: 10px; +} +.icons li { + background: none repeat scroll 0 0 white; + height: 6px; + width: 6px; + line-height: 0; + list-style: none outside none; + margin-right: 2px; + margin-top: 3px; + vertical-align: top; + border-radius: 50%; + pointer-events: none; +} +.btn-left { + left: 0.4em; +} +.btn-right { + right: 0.4em; +} +.btn-left, +.btn-right { + position: absolute; + top: 0.24em; +} +.dropbtn { + position: fixed; + color: white; + font-size: 16px; + border: none; + cursor: pointer; +} +.dropbtn:hover, +.dropbtn:focus { + background-color: #172141; +} +.dropdown { + position: absolute; + display: inline-block; + right: 6.7em; +} +.dropdown-content { + display: none; + position: relative; + margin-top: 60px; + background-color: #f9f9f9; + min-width: 160px; + overflow: auto; + box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2); + z-index: 1; +} + +.dropdown-content a { + color: black; + padding: 12px 16px; + text-decoration: none; + display: block; +} + +.dropdown a:hover { + background-color: #f1f1f1; +} + +.show { + display: block; +} + +/* End Stolen */ + + .chat-button { + width: 100px; + height: 100px; + background-image: radial-gradient(circle, black 10px, transparent 11px); + background-size: 100% 33.33%; + } + + .chat-image-config { + position: fixed; + width: 100%; + height: 100%; + background: white; + z-index: 100; + overflow: auto; + } + + .chat-image-config .small-text { + font-size: 10px; + } + + .chat-image-config .close-button { + position: fixed; + right: 25px; + padding: 10px; + font-size: 20px; + font-weight: bolder; + cursor: pointer; + } + + .chat-image-config .main-area { + margin: 30px; + text-align: center; + } + + .chat-image-config .main-area .big-profile-picture { + width: 250px; + height: 250px; + margin-top: 20px; + object-fit: cover; + } + + .chat-image-config .main-area .name { + font-size: 18px; + font-weight: bold; + } + + .chat-image-config .main-area .buttons-area { + margin-top: 20px; + } + + .settings-container { + display: flex; + justify-content: center; + flex-direction: column; + margin: 0.3em; + padding: 10px; + background: #455164; + border-radius: 2px; + } + + .settings-close-button{ + border: solid #d5d5d5 1px; + background: white; + color: #5e5e5e; + width: 15px; + height: 15px; + line-height: 16px; + text-align: center; + border-radius: 100%; + font-weight: bolder; + font-size: 7px; + cursor: pointer; + margin: 5px; + } + + .settings-user-info-container { + background: #99a2b4; + } + + .settings-user-info-heading{ + margin: 0.3em; + } + + .settings-user-info-form { + margin: 0.3em; + } + + .settings-settings-container{ + background: #5e6573; + } + + .settings-settings-heading { + margin: 0.3em; + } + + .settings-settings-form { + margin: 0.3em; + } + + + + /* add Chat Form*/ + +/* Extra styles for the cancel button */ +.cancelbtn { + width: auto; + padding: 10px 18px; + background-color: #f44336; +} + +/* Center the image and position the close button */ +.imgcontainer { + text-align: center; + margin: 24px 0 12px 0; + position: relative; +} + +img.avatar { + width: 40%; + border-radius: 50%; +} + +.container { + padding: 16px; +} + +span.psw { + float: right; + padding-top: 16px; +} \ No newline at end of file diff --git a/cmd/apps/skychat/internal/inputports/http/user/handler.go b/cmd/apps/skychat/internal/inputports/http/user/handler.go index d56433f22..7a82e3019 100644 --- a/cmd/apps/skychat/internal/inputports/http/user/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/user/handler.go @@ -6,9 +6,13 @@ import ( "fmt" "net/http" + "github.com/gorilla/mux" + "github.com/skycoin/skywire-utilities/pkg/cipher" userservices "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/user" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/user/commands" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" ) // Handler User http request handler @@ -21,58 +25,77 @@ func NewHandler(app userservices.UserServices) *Handler { return &Handler{userServices: app} } -// GetSettingsURLParam contains the parameter identifier to be parsed by the handler -const GetSettingsURLParam = "settings" +// AddPeerURLParam contains the parameter identifier to be parsed by the handler +const AddPeerURLParam = "addPeer" -// GetSettings Returns the settings of the user -func (c Handler) GetSettings(w http.ResponseWriter, r *http.Request) { - settings, err := c.userServices.Queries.GetUserSettingsHandler.Handle() - if err == nil && settings == nil { - w.WriteHeader(http.StatusNotFound) - fmt.Fprint(w, "Not Found") +// AddPeerRequestModel represents the request model of AddPeer +type AddPeerRequestModel struct { + //Info (from peer) + PK string `json:"pk"` + Alias string `json:"alias"` + Desc string `json:"desc"` + Img string `json:"img"` + //Alias + Custom string `json:"custom"` +} + +// AddPeer adds the given peer with the provided data +func (c Handler) AddPeer(w http.ResponseWriter, r *http.Request) { + + var reqPeerToSet AddPeerRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&reqPeerToSet) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr) return } + var pk cipher.PubKey + err := pk.Set(reqPeerToSet.PK) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, err.Error()) return } - err = json.NewEncoder(w).Encode(settings) + + info := info.NewInfo(pk, reqPeerToSet.Alias, reqPeerToSet.Desc, reqPeerToSet.Img) + + peerAddCommand := commands.AddPeerRequest{Info: info, Alias: reqPeerToSet.Custom} + + err = c.userServices.Commands.AddPeerHandler.Handle(peerAddCommand) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, err.Error()) - return } -} -// GetInfoURLParam contains the parameter identifier to be parsed by the handler -const GetInfoURLParam = "info" + w.WriteHeader(http.StatusOK) +} -// GetInfo Returns the info of the user -func (c Handler) GetInfo(w http.ResponseWriter, r *http.Request) { - info, err := c.userServices.Queries.GetUserInfoHandler.Handle() - if err == nil && info == nil { - w.WriteHeader(http.StatusNotFound) - fmt.Fprint(w, "Not Found") - return - } +// DeletePeerURLParam contains the parameter identifier to be parsed by the handler +const DeletePeerURLParam = "deletePeer" +// DeletePeer deletes the provided peer +func (c Handler) DeletePeer(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + pk := cipher.PubKey{} + err := pk.Set(vars[DeletePeerURLParam]) if err != nil { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprint(w, err.Error()) - return + fmt.Println("could not convert pubkey") } - err = json.NewEncoder(w).Encode(info) + + peerDeleteCommand := commands.DeletePeerRequest{PK: pk} + + err = c.userServices.Commands.DeletePeerHandler.Handle(peerDeleteCommand) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, err.Error()) - return } + + w.WriteHeader(http.StatusOK) } // SetInfoURLParam contains the parameter identifier to be parsed by the handler -const SetInfoURLParam = "info" +const SetInfoURLParam = "setInfo" // SetInfoRequestModel represents the request model of Update type SetInfoRequestModel struct { @@ -106,8 +129,56 @@ func (c Handler) SetInfo(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } +// SetPeerURLParam contains the parameter identifier to be parsed by the handler +const SetPeerURLParam = "setPeer" + +// SetPeerRequestModel represents the request model of SetPeer +type SetPeerRequestModel struct { + //Info (from peer) + PK string `json:"pk"` + Alias string `json:"alias"` + Desc string `json:"desc"` + Img string `json:"img"` + //Alias + Custom string `json:"custom"` +} + +// SetPeer updates the peer with the provided data +func (c Handler) SetPeer(w http.ResponseWriter, r *http.Request) { + + var reqPeerToSet SetPeerRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&reqPeerToSet) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr) + return + } + + var pk cipher.PubKey + err := pk.Set(reqPeerToSet.PK) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + + info := info.NewInfo(pk, reqPeerToSet.Alias, reqPeerToSet.Desc, reqPeerToSet.Img) + + peer := *peer.NewPeer(info, reqPeerToSet.Custom) + + peerSetCommand := commands.SetPeerRequest{Peer: peer} + + err = c.userServices.Commands.SetPeerHandler.Handle(peerSetCommand) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + } + + w.WriteHeader(http.StatusOK) +} + // SetSettingsURLParam contains the parameter identifier to be parsed by the handler -const SetSettingsURLParam = "settings" +const SetSettingsURLParam = "setSettings" // SetSettingsRequestModel represents the request model of SetSettings type SetSettingsRequestModel struct { @@ -143,3 +214,78 @@ func (c Handler) SetSettings(w http.ResponseWriter, r *http.Request) { } w.WriteHeader(http.StatusOK) } + +// GetInfoURLParam contains the parameter identifier to be parsed by the handler +const GetInfoURLParam = "getInfo" + +// GetInfo Returns the info of the user +func (c Handler) GetInfo(w http.ResponseWriter, r *http.Request) { + info, err := c.userServices.Queries.GetUserInfoHandler.Handle() + if err == nil && info == nil { + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, "Not Found") + return + } + + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + err = json.NewEncoder(w).Encode(info) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } +} + +// GetPeerbookURLParam contains the parameter identifier to be parsed by the handler +const GetPeerbookURLParam = "getPeerbook" + +// GetPeerbook returns the peerbook of the user +func (c Handler) GetPeerbook(w http.ResponseWriter, r *http.Request) { + info, err := c.userServices.Queries.GetUserPeerBookHandler.Handle() + if err == nil && info == nil { + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, "Not Found") + return + } + + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + err = json.NewEncoder(w).Encode(info) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } +} + +// GetSettingsURLParam contains the parameter identifier to be parsed by the handler +const GetSettingsURLParam = "getSettings" + +// GetSettings Returns the settings of the user +func (c Handler) GetSettings(w http.ResponseWriter, r *http.Request) { + settings, err := c.userServices.Queries.GetUserSettingsHandler.Handle() + if err == nil && settings == nil { + w.WriteHeader(http.StatusNotFound) + fmt.Fprint(w, "Not Found") + return + } + + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + err = json.NewEncoder(w).Encode(settings) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index b71469c3c..f4c247242 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -16,16 +16,18 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" "github.com/skycoin/skywire/pkg/app/appnet" ) // MessengerService provides a netcon implementation of the Service type MessengerService struct { - ctx context.Context - ns notification.Service - cliRepo client.Repository - usrRepo user.Repository - chatRepo chat.Repository + ctx context.Context + ns notification.Service + cliRepo client.Repository + usrRepo user.Repository + visorRepo chat.Repository + errs chan error } // NewMessengerService constructor for MessengerService @@ -39,39 +41,42 @@ func NewMessengerService(ns notification.Service, cR client.Repository, uR user. ms.ns = ns ms.cliRepo = cR ms.usrRepo = uR - ms.chatRepo = chR + ms.visorRepo = chR + + ms.errs = make(chan error, 1) return &ms } -// Handle handles the chat connection and incoming messanges -func (ms MessengerService) Handle(pk cipher.PubKey) error { - var err error +// Handle handles the visor connection and incoming messages +func (ms MessengerService) Handle(pk cipher.PubKey) { + errs := ms.errs - c, err := ms.chatRepo.GetByPK(pk) + pCli, err := ms.cliRepo.GetClient() if err != nil { - ch := chat.NewUndefinedChat(pk) - ms.chatRepo.Add(ch) //nolint:errcheck - c = &ch - fmt.Printf("New skychat added: %s\n", pk) + errs <- err + return } - conn := c.GetConnection() - if conn == nil { - fmt.Printf("Error, no connection\n") - conn, err = ms.Dial(pk) - if err != nil { - return err - } - } + conn := pCli.GetConns()[pk] + + localPK := pCli.GetAppClient().Config().VisorPK for { + //read packets buf := make([]byte, 32*1024) n, err := conn.Read(buf) if err != nil { fmt.Println("Failed to read packet:", err) - c.DeleteConnection() - return err + //close and delete connection + //TODO: close connection + err2 := pCli.DeleteConn(conn.RemoteAddr().(appnet.Addr).PubKey) + if err2 != nil { + errs <- err2 + return + } + errs <- err + return } //unmarshal the received bytes to a message.Message @@ -80,149 +85,62 @@ func (ms MessengerService) Handle(pk cipher.PubKey) error { err = json.Unmarshal(buf[:n], &m) if err != nil { fmt.Printf("Failed to unmarshal json message: %v", err) - } - - //TODO: first message has to be a request message, if not block and delete - //--> if we don't handle this it would be possible to send something else than request message via another - // app and bypass the blacklist - - //TODO: think about how to handle this - //If the received message has status MsgSTatusInitial it was just send and we have to send it back to let the - //peer know that we received it. - //if m.GetStatus() == message.MsgStatusInitial { - // m.SetStatus(message.MsgStatusReceived) - // ms.sendMessage(pk, m) - //} - //notify that a new message has been received - //save message to chatrepo - //TODO: make NewReceivedTextMessage - //! Can also be a message of the remote that the own send message has been received - - //get the current chat so when updating nothing gets overwritten - c, _ := ms.chatRepo.GetByPK(pk) - - switch m.GetMessageType() { - case message.ConnMsgType: - c.AddMessage(m) - ms.chatRepo.Update(*c) - err := ms.handleConnMsgType(m) - if err != nil { - fmt.Println(err) - } - case message.InfoMsgType: - jm := message.JSONMessage{} - err = json.Unmarshal(buf[:n], &jm) - if err != nil { - fmt.Printf("Failed to unmarshal json message: %v", err) - } - m = message.NewMessage(jm) - c.AddMessage(m) - ms.chatRepo.Update(*c) - - err = ms.handleInfoMsgType(c, m) + } else { + //unmarshal the received bytes to a message.JSONMessage{} + buf := make([]byte, 32*1024) + n, err := conn.Read(buf) if err != nil { - fmt.Println(err) + fmt.Println("Failed to read packet:", err) + continue } - case message.TxtMsgType: jm := message.JSONMessage{} err = json.Unmarshal(buf[:n], &jm) if err != nil { - fmt.Printf("Failed to unmarshal json message: %v", err) + fmt.Printf("Failed to unmarshal json jsonMessage: %v", err) + continue } m = message.NewMessage(jm) - c.AddMessage(m) - ms.chatRepo.Update(*c) - err := ms.handleTextMsgType(c, m) - if err != nil { - fmt.Println(err) - } - case message.CmdMsgType: - //not allowed, only for servers/groups - default: - fmt.Printf("Incorrect data received") - } - } -} - -// handleConnMsgType handles an incoming connection message and either accepts it and sends back the own info as message -// or if the public key is in the blacklist rejects the chat request. -func (ms MessengerService) handleConnMsgType(m message.Message) error { - usr, err := ms.usrRepo.GetUser() - if err != nil { - fmt.Printf("Error getting user from repository: %s", err) - return err - } - - switch m.MsgSubtype { - case message.ConnMsgTypeRequest: - //check if sender is in blacklist, if not so send info message back, else reject chat - if !usr.GetSettings().InBlacklist(m.Sender) { - //notify about the new chat initiated by the user - an := notification.NewChatNotification(m.Sender) - ms.ns.Notify(an) - msg := message.NewChatAcceptMessage(usr.GetInfo().GetPK()) - ms.sendMessage(m.Sender, msg) + //handle messages in dependency of destination + if m.GetDestinationVisor() == localPK { + if m.GetDestinationServer() == localPK { + err = ms.handleP2PMessage(m) + } else { + err = ms.handleLocalServerMessage(m) + } + if err != nil { + fmt.Println(err) + continue + } + } else { + err = ms.handleRemoteServerMessage(m) + if err != nil { + fmt.Println(err) + continue + } - ms.SendInfoMessage(m.Sender, *usr.GetInfo()) - - //n := notification.NewMsgNotification(m.Sender, m) - //ms.ns.Notify(n) - } else { - msg := message.NewChatRejectMessage(usr.GetInfo().GetPK()) - ms.sendMessage(m.Sender, msg) - ms.chatRepo.Delete(m.Sender) - - //TODO: notify about a rejected chat request cause of blacklist - return fmt.Errorf("pk in blacklist") + } } - case message.ConnMsgTypeAccept: - ms.SendInfoMessage(m.Sender, *usr.GetInfo()) - - case message.ConnMsgTypeReject: - //ms.chatRepo.Delete(m.Sender) - - n := notification.NewMsgNotification(m.Sender, m) - ms.ns.Notify(n) - return fmt.Errorf("peer rejected chat") - - } - - return nil -} -//TODO: document what function does -func (ms MessengerService) handleInfoMsgType(c *chat.Chat, m message.Message) error { - //save info in chat info - //unmarshal the received message bytes to info.Info - i := info.Info{} - err := json.Unmarshal(m.Message, &i) - if err != nil { - fmt.Printf("Failed to unmarshal json message: %v", err) } - c.Info = i - ms.chatRepo.Update(*c) - - //notify about new info message - n := notification.NewMsgNotification(c.GetPK(), m) - ms.ns.Notify(n) - - return nil } -//TODO: document what function does -func (ms MessengerService) handleTextMsgType(c *chat.Chat, m message.Message) error { - - n := notification.NewMsgNotification(c.GetPK(), message.NewTextMessage(m.Sender, m.Message)) - ms.ns.Notify(n) - - return nil -} +//TODO: think about how to handle this +//If the received message has status MsgSTatusInitial it was just send and we have to send it back to let the +//peer know that we received it. +//if m.GetStatus() == message.MsgStatusInitial { +// m.SetStatus(message.MsgStatusReceived) +// ms.sendMessage(pk, m) +//} +//notify that a new message has been received +//save message to chatrepo +//TODO: make NewReceivedTextMessage +//! Can also be a message of the remote that the own send message has been received // Dial dials the remote chat func (ms MessengerService) Dial(pk cipher.PubKey) (net.Conn, error) { - c, err := ms.chatRepo.GetByPK(pk) + c, err := ms.visorRepo.GetByPK(pk) if err != nil { //Should not happen as before dial chats get added to repo return nil, err @@ -235,11 +153,12 @@ func (ms MessengerService) Dial(pk cipher.PubKey) (net.Conn, error) { } conn := c.GetConnection() - if conn != nil { + /*if conn != nil { //TODO: maybe delete old connection and reconnect? //TODO: or skip dialing if connection alive //pCli.GetAppClient().Close() - } + + }*/ addr := appnet.Addr{ Net: pCli.GetNetType(), @@ -258,7 +177,10 @@ func (ms MessengerService) Dial(pk cipher.PubKey) (net.Conn, error) { //TODO: notify that dialing is happening? conn, err = pCli.GetAppClient().Dial(addr) //could not find a valid connection to a chat, so delete it. - ms.chatRepo.Delete(c.PK) + err2 := ms.visorRepo.Delete(c.PK) + if err2 != nil { + return err2 + } return err }) @@ -267,28 +189,36 @@ func (ms MessengerService) Dial(pk cipher.PubKey) (net.Conn, error) { } c.SetConnection(conn) - ms.chatRepo.Update(*c) + err = ms.visorRepo.Set(*c) + if err != nil { + return nil, err + } return conn, nil } -// sendMessage sends a message to the given chat -func (ms MessengerService) sendMessage(pk cipher.PubKey, m message.Message) error { - c, err := ms.chatRepo.GetByPK(pk) +// sendMessage sends a message to the given route +func (ms MessengerService) sendMessage(dest util.PKRoute, m message.Message) error { + v, err := ms.visorRepo.GetByPK(dest.Visor) if err != nil { - ch := chat.NewUndefinedChat(pk) - ms.chatRepo.Add(ch) - c = &ch - fmt.Printf("New skychat added: %s\n", pk) + ch := chat.NewUndefinedVisor(dest.Visor) + err2 := ms.visorRepo.Add(ch) + if err2 != nil { + return err2 + } + v = &ch + fmt.Printf("New skychat added: %s\n", dest.Visor) } + m.Dest = dest + bytes, err := json.Marshal(m) if err != nil { fmt.Printf("Failed to marshal json: %v", err) } - conn := c.GetConnection() + conn := v.GetConnection() if conn == nil { - conn, err = ms.Dial(pk) + conn, err = ms.Dial(dest.Visor) if err != nil { return err } @@ -299,15 +229,56 @@ func (ms MessengerService) sendMessage(pk cipher.PubKey, m message.Message) erro return err } - c, _ = ms.chatRepo.GetByPK(pk) - c.AddMessage(m) - ms.chatRepo.Update(*c) + v, err = ms.visorRepo.GetByPK(dest.Visor) + if err != nil { + return err + } + v.AddMessage(m) + err = ms.visorRepo.Set(*v) + if err != nil { + return err + } + + return nil +} + +// sendMessageNirvana sends a message to the given route without saving it somewhere +func (ms MessengerService) sendMessageNirvana(route util.PKRoute, m message.Message) error { + + pCli, err := ms.cliRepo.GetClient() + if err != nil { + return err + } + + m.Dest = route + + bytes, err := json.Marshal(m) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + } + + conn := pCli.GetConns()[route.Visor] + if conn == nil { + conn, err = ms.Dial(route.Visor) + if err != nil { + return err + } + } + + _, err = conn.Write(bytes) + if err != nil { + return err + } return nil } -// SendChatRequestMessage sends a chat request message to request a chat -func (ms MessengerService) SendChatRequestMessage(pk cipher.PubKey) error { +// SendRouteRequestMessage sends a request message to join the specified route +// if route.Visor == route.Server -> P2P request +// if route.Visor + (route.Server == nil) -> P2P request +// if route.Visor + route.Server -> ServerJoinRequest +// if route.Visor + route.Server + route.Room -> RoomRequest +func (ms MessengerService) SendRouteRequestMessage(route util.PKRoute) error { usr, err := ms.usrRepo.GetUser() if err != nil { @@ -315,27 +286,34 @@ func (ms MessengerService) SendChatRequestMessage(pk cipher.PubKey) error { return err } - m := message.NewChatRequestMessage(usr.GetInfo().GetPK()) + m := message.NewRouteRequestMessage(usr.GetInfo().GetPK(), route) - err = ms.sendMessage(pk, m) + err = ms.sendMessage(route, m) if err != nil { return err } //TODO: think about putting this notification in add_chat use case - //notify about the added chat - an := notification.NewAddChatNotification(pk) - ms.ns.Notify(an) + //notify about the added route + an := notification.NewAddRouteNotification(route) + err = ms.ns.Notify(an) + if err != nil { + return err + } //notify about sent chat request message - n := notification.NewMsgNotification(pk, m) - ms.ns.Notify(n) + n := notification.NewMsgNotification(route, m) + err = ms.ns.Notify(n) + if err != nil { + return err + } return nil } -// SendTextMessage sends a text message to the given chat -func (ms MessengerService) SendTextMessage(pk cipher.PubKey, msg []byte) error { +// SendTextMessage sends a text message to the given route +//[]: root and destination!! +func (ms MessengerService) SendTextMessage(route util.PKRoute, msg []byte) error { fmt.Println("MessengerService - SendTextMessage") usr, err := ms.usrRepo.GetUser() @@ -344,50 +322,96 @@ func (ms MessengerService) SendTextMessage(pk cipher.PubKey, msg []byte) error { return err } - m := message.NewTextMessage(usr.GetInfo().GetPK(), msg) + m := message.NewTextMessage(usr.GetInfo().GetPK(), route, msg) + + if m.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(m) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(m) + if err != nil { + return err + } + } + + return nil +} - err = ms.sendMessage(pk, m) +// sendMessageToRemoteRoute sends the given message to a remote route +func (ms MessengerService) sendMessageToRemoteRoute(msg message.Message) error { + err := ms.sendMessage(msg.Dest, msg) if err != nil { return err } //notify about sent text message - n := notification.NewMsgNotification(pk, m) - ms.ns.Notify(n) + n := notification.NewMsgNotification(msg.Dest, msg) + err = ms.ns.Notify(n) + if err != nil { + return err + } return nil } -// SendInfoMessage sends a info message to the given chat -func (ms MessengerService) SendInfoMessage(pk cipher.PubKey, info info.Info) error { - fmt.Println("MessengerService - SendInfoMessage") +// sendMessageToLocalRoute handles the message as a message received from a server +func (ms MessengerService) sendMessageToLocalRoute(msg message.Message) error { + err := ms.handleLocalServerMessage(msg) + if err != nil { + return err + } + //notification is handled inside handleServerMessage + + return nil +} +// SendInfoMessage sends an info message to the given chat and notifies about sent message +func (ms MessengerService) SendInfoMessage(root util.PKRoute, dest util.PKRoute, info info.Info) error { bytes, err := json.Marshal(info) if err != nil { fmt.Printf("Failed to marshal json: %v", err) } - usr, err := ms.usrRepo.GetUser() + m := message.NewChatInfoMessage(root, dest, bytes) + + err = ms.sendMessage(dest, m) if err != nil { - fmt.Printf("Error getting user from repository: %s", err) return err } - m := message.NewChatInfoMessage(usr.GetInfo().GetPK(), bytes) - - err = ms.sendMessage(pk, m) + //notify about sent info message + n := notification.NewMsgNotification(dest, m) + err = ms.ns.Notify(n) if err != nil { return err } - //notify about sent info message - n := notification.NewMsgNotification(pk, m) - ms.ns.Notify(n) + return nil +} + +// SendChatAcceptMessage sends an accept-message from the root to the destination +func (ms MessengerService) SendChatAcceptMessage(root util.PKRoute, dest util.PKRoute) error { + m := message.NewChatAcceptMessage(root, dest) + err := ms.sendMessage(dest, m) + if err != nil { + return err + } + return nil +} +// SendChatRejectMessage sends an reject-message from the root to the destination +func (ms MessengerService) SendChatRejectMessage(root util.PKRoute, dest util.PKRoute) error { + m := message.NewChatRejectMessage(root, dest) + err := ms.sendMessageNirvana(dest, m) + if err != nil { + return err + } return nil } -// Listen is used to listen for new incoming chats and pass them to the connection_handle routine +// Listen is used to listen for new incoming connections and pass them to the connection_handle routine func (ms MessengerService) Listen() { pCli, err := ms.cliRepo.GetClient() if err != nil { @@ -412,17 +436,21 @@ func (ms MessengerService) Listen() { fmt.Printf("Accepted skychat conn on %s from %s\n", conn.LocalAddr(), raddr.PubKey) - //check if the remote addr already is a saved chat - c, err := ms.chatRepo.GetByPK(raddr.PubKey) + //add connection to active connections of client + err = pCli.AddConn(raddr.PubKey, conn) if err != nil { - ch := chat.NewUndefinedChat(raddr.PubKey) - ms.chatRepo.Add(ch) - c = &ch - fmt.Printf("New skychat added: %s\n", raddr.PubKey) + fmt.Println(err) + } + err = ms.cliRepo.SetClient(*pCli) + if err != nil { + fmt.Println(err) } - c.SetConnection(conn) - ms.chatRepo.Update(*c) go ms.Handle(raddr.PubKey) + + if err := <-ms.errs; err != nil { + fmt.Printf("Error in go handle function: %s ", err) + } + } } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go new file mode 100644 index 000000000..74354914a --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go @@ -0,0 +1,271 @@ +package netcon + +import ( + "encoding/json" + "fmt" + + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// handleLocalServerMessage handles messages received to a local route (server/room) +// these can also be locally sent messages from the user to his own local route +func (ms MessengerService) handleLocalServerMessage(m message.Message) error { + //first check if the message is of type ConnMsgType + //we need to handle this first, as we first have to accept or reject a message + if m.GetMessageType() == message.ConnMsgType { + err := ms.handleLocalRoomConnMsgType(m) + if err != nil { + return err + } + } + + //if the message is not of type ConnMsgType check if the remote pk is blacklisted + // to prevent a peer from sending other messages before a connection-request message + visor, err := ms.visorRepo.GetByPK(m.Dest.Visor) + if err != nil { + return err + } + server, err := visor.GetServerByPK(m.Dest.Server) + if err != nil { + return err + } + r, err := server.GetRoomByPK(m.Dest.Room) + if err != nil { + return err + } + + //save room as local variable + room := *r + + //the root route of this server (== the Destination of the message) + root := m.Dest + //the destination route of a message to send back to the root + dest := m.Root + + //check if in blacklist of server //TODO: or not a member !! add always local as member + if _, ok := server.GetBlacklist()[m.Root.Visor]; ok { + err = ms.SendChatRejectMessage(root, dest) + if err != nil { + return err + } + return fmt.Errorf("Message rejected from " + m.Root.Visor.String()) + } + + //check if in blacklist of room //TODO: or ot a member + if _, ok := room.GetBlacklist()[m.Root.Visor]; ok { + err = ms.SendChatRejectMessage(root, dest) + if err != nil { + return err + } + return fmt.Errorf("Message rejected from " + m.Root.Visor.String()) + } + + //check if in muted of server + //TODO: + //check if in muted of room + //TODO: + + //now we can handle all other message-types + switch m.GetMessageType() { + case message.InfoMsgType: + //add the message to the room and update server, visor & repository + room.AddMessage(m) + err = server.SetRoom(room) + if err != nil { + return err + } + err = visor.SetServer(*server) + if err != nil { + return err + } + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + //handle the message + err = ms.handleLocalRoomInfoMsgType(visor, m) + if err != nil { + fmt.Println(err) + } + case message.TxtMsgType: + //add the message to the room and update server, visor & repository + room.AddMessage(m) + err = server.SetRoom(room) + if err != nil { + return err + } + err = visor.SetServer(*server) + if err != nil { + return err + } + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + //handle the message + err := ms.handleLocalRoomTextMsgType(visor, m) + if err != nil { + return err + } + case message.CmdMsgType: + return fmt.Errorf("commands are not allowed on p2p chats") + default: + return fmt.Errorf("incorrect data received") + + } + return nil +} + +// handleRoomConnMsgType handles an incoming connection message and either accepts it and sends back the own info as message +// or if the public key is in the blacklist rejects the chat request. +func (ms MessengerService) handleLocalRoomConnMsgType(m message.Message) error { + visor, err := ms.visorRepo.GetByPK(m.Dest.Visor) + if err != nil { + return err + } + server, err := visor.GetServerByPK(m.Dest.Server) + if err != nil { + return err + } + r, err := server.GetRoomByPK(m.Dest.Room) + if err != nil { + return err + } + + //save room as local variable + room := *r + + //the root route of this server (== the Destination of the message) + root := m.Dest + //the destination route of a message to send back to the root + dest := m.Root + + switch m.MsgSubtype { + case message.ConnMsgTypeRequest: + //check if sender is in blacklist, if not send accept and info messages back, else send reject message + if _, ok := server.GetBlacklist()[m.Root.Visor]; !ok { + if _, ok2 := room.GetBlacklist()[m.Root.Visor]; !ok2 { + + //TODO: Add chat request message to room + + //send a chat-accept-message to the remote peer + err = ms.SendChatAcceptMessage(root, dest) + if err != nil { + return err + } + + //send the rooms info to the remote peer + err = ms.SendInfoMessage(root, dest, room.GetInfo()) + if err != nil { + return err + } + + //add remote peer to members so he is able to send other messages than connMsgType + info := info.NewDefaultInfo() + info.Pk = m.Root.Visor + dummyPeer := peer.NewPeer(info, "") + //add remote peer to room + err = room.AddMember(*dummyPeer) + if err != nil { + return err + } + //update room inside server + err = server.SetRoom(room) + if err != nil { + return err + } + //add remote peer to server + err = server.AddMember(*dummyPeer) + if err != nil { + return err + } + //update server inside visor + err = visor.SetServer(*server) + if err != nil { + return err + } + //update visor inside repository + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + + //TODO: send new member-list to members + + //TODO: notify about new member + + } else { + //sends a chat-reject-message to the remote peer + err = ms.SendChatRejectMessage(root, dest) + if err != nil { + return err + } + return fmt.Errorf("pk in room-blacklist rejected") + } + } else { + //sends a chat-reject-message to the remote peer + err = ms.SendChatRejectMessage(root, dest) + if err != nil { + return err + } + return fmt.Errorf("pk in server-blacklist rejected") + } + default: + return fmt.Errorf("incorrect data received") + + } + + return nil +} + +// handleLocalRoomInfoMsgType handles messages of type info of peers +func (ms MessengerService) handleLocalRoomInfoMsgType(v *chat.Visor, m message.Message) error { + //unmarshal the received message bytes to info.Info + i := info.Info{} + err := json.Unmarshal(m.Message, &i) + if err != nil { + return fmt.Errorf("failed to unmarshal json message: %v", err) + } + s, err := v.GetServerByPK(m.GetDestinationServer()) + if err != nil { + return err + } + + //update the info of the member in the server and all rooms + s.SetMemberInfo(i) + err = ms.visorRepo.Set(*v) + if err != nil { + return err + } + + //notify about new info message + n := notification.NewMsgNotification(util.NewP2PRoute(v.GetPK()), m) + err = ms.ns.Notify(n) + if err != nil { + return err + } + + //TODO: send updated info of members to all members + + return nil +} + +// handleLocalRoomTextMstType handles messages of type text of the p2p chat +func (ms MessengerService) handleLocalRoomTextMsgType(c *chat.Visor, m message.Message) error { + + //notify about a new TextMessage + n := notification.NewMsgNotification(util.NewP2PRoute(c.GetPK()), message.NewTextMessage(m.Root.Visor, m.Dest, m.Message)) + err := ms.ns.Notify(n) + if err != nil { + return err + } + + //TODO: send message to all members + + return nil +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go new file mode 100644 index 000000000..8d79db64a --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go @@ -0,0 +1,218 @@ +package netcon + +import ( + "encoding/json" + "fmt" + + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// handleP2PMessage handles messages sent as direct message +func (ms MessengerService) handleP2PMessage(m message.Message) error { + + //first check if the message is of type ConnMsgType + //we need to handle this first, as we first have to accept or reject a message + if m.GetMessageType() == message.ConnMsgType { + err := ms.handleP2PConnMsgType(m) + if err != nil { + return err + } + } + //if the message is not of type ConnMsgType check if the remote pk is blacklisted + // to prevent a peer from sending other messages before a connection-request message + usr, err := ms.usrRepo.GetUser() + if err != nil { + return err + } + + //the p2p route of the user + root := util.NewP2PRoute(usr.GetInfo().GetPK()) + //the p2p route of the peer + dest := util.NewP2PRoute(m.Root.Visor) + + if usr.GetSettings().InBlacklist(m.Root.Visor) { + err = ms.SendChatRejectMessage(root, dest) + if err != nil { + return err + } + return fmt.Errorf("Message rejected from " + m.Root.Visor.String()) + } + + //get the current p2p-room so when updating nothing gets overwritten + visor, err := ms.visorRepo.GetByPK(m.Root.Visor) + if err != nil { + return err + } + p2p, err := visor.GetP2P() + if err != nil { + return err + } + + //now we can handle all other message-types + switch m.GetMessageType() { + case message.InfoMsgType: + //add the message to the p2p chat and update visor & repository + p2p.AddMessage(m) + err = visor.SetP2P(p2p) + if err != nil { + return err + } + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + //handle the message + err = ms.handleP2PInfoMsgType(visor, m) + if err != nil { + fmt.Println(err) + } + case message.TxtMsgType: + //add the message to the p2p chat and update visor & repository + p2p.AddMessage(m) + err = visor.SetP2P(p2p) + if err != nil { + return err + } + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + //handle the message + err := ms.handleP2PTextMsgType(visor, m) + if err != nil { + return err + } + case message.CmdMsgType: + return fmt.Errorf("commands are not allowed on p2p chats") + default: + return fmt.Errorf("incorrect data received") + } + return nil + +} + +// handleP2PConnMsgType handles an incoming connection message and either accepts it and sends back the own info as message +// or if the public key is in the blacklist rejects the chat request. +func (ms MessengerService) handleP2PConnMsgType(m message.Message) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + return err + } + + //the p2p route of the user + root := util.NewP2PRoute(usr.GetInfo().GetPK()) + //the p2p route of the peer + dest := util.NewP2PRoute(m.Root.Visor) + + switch m.MsgSubtype { + case message.ConnMsgTypeRequest: + //check if sender is in blacklist, if not send accetp and info messages back, else send reject message + if !usr.GetSettings().InBlacklist(m.Root.Visor) { + //make new default visor with a default p2p-room and save it in the visor repository + v := chat.NewDefaultP2PVisor(m.Root.Visor) + err = ms.visorRepo.Add(v) + if err != nil { + return err + } + + //TODO: Add request message to p2p + + //notify about the new chat initiated by a remote visor + n := notification.NewChatNotification(m.Root.Visor) + err = ms.ns.Notify(n) + if err != nil { + return err + } + + //sends a chat-accept-message to the remote peer + err = ms.SendChatAcceptMessage(root, dest) + if err != nil { + return err + } + + //sends the users info to the remote peer + err = ms.SendInfoMessage(root, dest, *usr.GetInfo()) + if err != nil { + return err + } + + } else { + //sends a chat-reject-message to the remote peer + err = ms.SendChatRejectMessage(root, dest) + if err != nil { + return err + } + //deletes the visor from the repository + err = ms.visorRepo.Delete(m.Root.Visor) + if err != nil { + return err + } + return fmt.Errorf("pk in blacklist rejected") + } + case message.ConnMsgTypeAccept: + //notify that we received an accept message + n := notification.NewMsgNotification(m.Root, m) + err = ms.ns.Notify(n) + if err != nil { + return err + } + //as the peer has accepted the chat request we now can send our info + err = ms.SendInfoMessage(root, dest, *usr.GetInfo()) + if err != nil { + return err + } + + case message.ConnMsgTypeReject: + n := notification.NewMsgNotification(m.Root, m) + err = ms.ns.Notify(n) + if err != nil { + return err + } + default: + return fmt.Errorf("incorrect data received") + } + + return nil +} + +// handleP2PInfoMsgType handles messages of type info of the p2p chat +func (ms MessengerService) handleP2PInfoMsgType(v *chat.Visor, m message.Message) error { + //unmarshal the received message bytes to info.Info + i := info.Info{} + err := json.Unmarshal(m.Message, &i) + if err != nil { + return fmt.Errorf("failed to unmarshal json message: %v", err) + } + //update the info of the p2p + v.P2P.Info = i + err = ms.visorRepo.Set(*v) + if err != nil { + return err + } + + //notify about new info message + n := notification.NewMsgNotification(util.NewP2PRoute(v.GetPK()), m) + err = ms.ns.Notify(n) + if err != nil { + return err + } + + return nil +} + +// handleP2PTextMstType handles messages of type text of the p2p chat +func (ms MessengerService) handleP2PTextMsgType(c *chat.Visor, m message.Message) error { + + //notify about a new TextMessage + n := notification.NewMsgNotification(util.NewP2PRoute(c.GetPK()), message.NewTextMessage(m.Root.Visor, m.Dest, m.Message)) + err := ms.ns.Notify(n) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go new file mode 100644 index 000000000..e8b0b0c6b --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go @@ -0,0 +1,189 @@ +package netcon + +import ( + "encoding/json" + "fmt" + + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// handleRemoteServerMessage handles all messages from a remote server/room +func (ms MessengerService) handleRemoteServerMessage(m message.Message) error { + //TODO: check if we are member -> if not ignore message + + visor, err := ms.visorRepo.GetByPK(m.Dest.Visor) + if err != nil { + return err + } + server, err := visor.GetServerByPK(m.Dest.Server) + if err != nil { + return err + } + r, err := server.GetRoomByPK(m.Dest.Room) + if err != nil { + return err + } + + //save room as local variable + room := *r + + switch m.GetMessageType() { + case message.ConnMsgType: + //add the message to the room and update server, visor & repository + room.AddMessage(m) + err = server.SetRoom(room) + if err != nil { + return err + } + err = visor.SetServer(*server) + if err != nil { + return err + } + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + //handle the message + err = ms.handleRemoteRoomConnMsgType(m) + if err != nil { + fmt.Println(err) + } + case message.InfoMsgType: + //add the message to the room and update server, visor & repository + room.AddMessage(m) + err = server.SetRoom(room) + if err != nil { + return err + } + err = visor.SetServer(*server) + if err != nil { + return err + } + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + //handle the message + err = ms.handleRemoteRoomInfoMsgType(visor, m) + if err != nil { + fmt.Println(err) + } + case message.TxtMsgType: + //add the message to the room and update server, visor & repository + room.AddMessage(m) + err = server.SetRoom(room) + if err != nil { + return err + } + err = visor.SetServer(*server) + if err != nil { + return err + } + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + //handle the message + err := ms.handleRemoteRoomTextMsgType(visor, m) + if err != nil { + return err + } + case message.CmdMsgType: + return fmt.Errorf("commands are not allowed on p2p chats") + default: + return fmt.Errorf("incorrect data received") + + } + return nil +} + +// handleRemoteRoomConnMsgType handles all messages of type ConnMsgtype of remote servers +func (ms MessengerService) handleRemoteRoomConnMsgType(m message.Message) error { + + //Get user to get the info + user, err := ms.usrRepo.GetUser() + if err != nil { + return err + } + + //the root route of this server (== the Destination of the message) + root := m.Dest + //the destination route of a message to send back to the root + dest := m.Root + + switch m.MsgSubtype { + case message.ConnMsgTypeAccept: + //notify that we received an accept message + n := notification.NewMsgNotification(m.Root, m) + err := ms.ns.Notify(n) + if err != nil { + return err + } + //as the remote route has accepted the chat request we now can send our info + err = ms.SendInfoMessage(root, dest, *user.GetInfo()) + if err != nil { + return err + } + + case message.ConnMsgTypeReject: + n := notification.NewMsgNotification(m.Root, m) + err := ms.ns.Notify(n) + if err != nil { + return err + } + //? do we have to delete something here? + return nil + + default: + return fmt.Errorf("incorrect data received") + } + return nil + +} + +// handleRemoteRoomInfoMsgType handles messages of type info of peers +func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message.Message) error { + //unmarshal the received message bytes to info.Info + i := info.Info{} + err := json.Unmarshal(m.Message, &i) + if err != nil { + return fmt.Errorf("failed to unmarshal json message: %v", err) + } + s, err := v.GetServerByPK(m.GetDestinationServer()) + if err != nil { + return err + } + + //update the info of the member in the server and all rooms + s.SetMemberInfo(i) + err = ms.visorRepo.Set(*v) + if err != nil { + return err + } + + //notify about new info message + n := notification.NewMsgNotification(util.NewP2PRoute(v.GetPK()), m) + err = ms.ns.Notify(n) + if err != nil { + return err + } + + return nil +} + +// handleRemoteRoomTextMstType handles messages of type text of the remote chat +func (ms MessengerService) handleRemoteRoomTextMsgType(c *chat.Visor, m message.Message) error { + + //notify about a new TextMessage + n := notification.NewMsgNotification(util.NewP2PRoute(c.GetPK()), message.NewTextMessage(m.Root.Visor, m.Dest, m.Message)) + err := ms.ns.Notify(n) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go b/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go index a089727d5..575a3f5db 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go @@ -15,13 +15,13 @@ type NotificationService struct { // NewNotificationService constructor for NotificationService func NewNotificationService() *NotificationService { n := NotificationService{} - n.notifCh = make(chan string) + //n.notifCh = make(chan string) return &n } // Notify sends out the notifications to the channel -func (ns NotificationService) Notify(notification notification.Notification) error { +func (ns *NotificationService) Notify(notification notification.Notification) error { jsonNotification, err := json.Marshal(notification) if err != nil { return err @@ -31,7 +31,18 @@ func (ns NotificationService) Notify(notification notification.Notification) err return nil } +//TODO: +func (ns *NotificationService) InitChannel() { + ns.notifCh = make(chan string) +} + // GetChannel returns the channel of the notification service -func (ns NotificationService) GetChannel() chan string { +func (ns *NotificationService) GetChannel() chan string { return ns.notifCh } + +//TODO: +func (ns *NotificationService) DeferChannel() { + close(ns.notifCh) + ns.notifCh = nil +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/services.go b/cmd/apps/skychat/internal/interfaceadapters/services.go index 05a337b3c..bc1bf744d 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/services.go +++ b/cmd/apps/skychat/internal/interfaceadapters/services.go @@ -16,7 +16,7 @@ import ( type Services struct { ClientRepository client.Repository UserRepository user.Repository - ChatRepository chat.Repository + VisorRepository chat.Repository MessengerService messenger.Service NotificationService notification.Service } @@ -26,14 +26,15 @@ func NewServices() Services { cliRepo := memory.NewClientRepo() cli, _ := cliRepo.GetClient() //nolint usrRepo := memory.NewUserRepo(cli.GetAppClient().Config().VisorPK) - chtRepo := memory.NewChatRepo() //memory.NewDummyChatRepo(cli.GetAppClient().Config().VisorPK) + vsrRepo := memory.NewVisorRepo() ns := channel.NewNotificationService() + ms := netcon.NewMessengerService(ns, cliRepo, usrRepo, vsrRepo) return Services{ ClientRepository: cliRepo, UserRepository: usrRepo, - ChatRepository: chtRepo, - MessengerService: netcon.NewMessengerService(ns, cliRepo, usrRepo, chtRepo), + VisorRepository: vsrRepo, + MessengerService: ms, NotificationService: ns, } } diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go deleted file mode 100644 index dffd903ae..000000000 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/chat_repo.go +++ /dev/null @@ -1,119 +0,0 @@ -// Package memory contains code of the chat repo of interfaceadapters -package memory - -import ( - "fmt" - "sync" - - "github.com/skycoin/skywire-utilities/pkg/cipher" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" -) - -// ChatRepo Implements the Repository Interface to provide an in-memory storage provider -type ChatRepo struct { - chats map[cipher.PubKey]chat.Chat - chatsMu sync.Mutex -} - -// NewChatRepo Constructor -func NewChatRepo() *ChatRepo { - cR := ChatRepo{} - cR.chats = make(map[cipher.PubKey]chat.Chat) - return &cR -} - -// GetByPK Returns the chat with the provided pk -func (r *ChatRepo) GetByPK(pk cipher.PubKey) (*chat.Chat, error) { - r.chatsMu.Lock() - defer r.chatsMu.Unlock() - - chat, ok := r.chats[pk] - if !ok { - return nil, fmt.Errorf("chat not found") - } - return &chat, nil -} - -// GetAll Returns all stored chats -func (r *ChatRepo) GetAll() ([]chat.Chat, error) { - r.chatsMu.Lock() - defer r.chatsMu.Unlock() - // TODO(ersonp): code is unused; check for usage - // keys := make([]cipher.PubKey, 0) - - // for key := range r.chats { - // keys = append(keys, key) - // } - - var values []chat.Chat - for _, value := range r.chats { - values = append(values, value) - } - - return values, nil -} - -// Add the provided chat -func (r *ChatRepo) Add(chat chat.Chat) error { - r.chatsMu.Lock() - defer r.chatsMu.Unlock() - - r.chats[chat.GetPK()] = chat - return nil -} - -// Update the provided chat -func (r *ChatRepo) Update(chat chat.Chat) error { - r.chatsMu.Lock() - defer r.chatsMu.Unlock() - - r.chats[chat.GetPK()] = chat - return nil -} - -// Delete the chat with the provided pk -func (r *ChatRepo) Delete(pk cipher.PubKey) error { - r.chatsMu.Lock() - defer r.chatsMu.Unlock() - - _, exists := r.chats[pk] - if !exists { - return fmt.Errorf("id %v not found", pk.String()) - } - delete(r.chats, pk) - return nil -} - -/* -func NewDummyChatRepo(pk cipher.PubKey) *ChatRepo { - cR := ChatRepo{} - - defaultpng := "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAIAAAAHjs1qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5OTMyNUUzOTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjY5OTMyNUU0OTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6Njk5MzI1RTE5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Njk5MzI1RTI5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7FIRCzAAAPn0lEQVR42uyd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" - - //Origin1 - pk1 := cipher.PubKey{} - pk1.Set("0200369389087217c9e9b5936c329c120c7ed1b29b404d708bc88634e4d6b4966b") - i1 := info.NewInfo(pk1, "Peer1", "Peer1 Description", defaultpng) - //TODO: make chat.NewChat() - //make dummy chats - PC1msg1 := message.NewTextMessage(pk1, []byte("Hello")) - PC1msg2 := message.NewTextMessage(pk, []byte("Hello Back")) - PC1 := chat.NewChat(pk1, chat.PeerChat, i1, []message.Message{PC1msg1, PC1msg2}) - - //Origin2 - pk2 := cipher.PubKey{} - pk2.Set("0200369389087217c9e9b5936c329c120c7ed1b29b404d708bc88634e4d6b4966a") - i2 := info.NewInfo(pk2, "Peer2", "Peer2 Description", defaultpng) - //TODO: make chat.NewChat() - //make dummy chats - PC2msg1 := message.NewTextMessage(pk2, []byte("Hello Peer2")) - PC2msg2 := message.NewTextMessage(pk, []byte("Hello Back Peer2")) - PC2 := chat.NewChat(pk2, chat.PeerChat, i2, []message.Message{PC2msg1, PC2msg2}) - - cR.chats = make(map[cipher.PubKey]chat.Chat) - cR.chats[pk1] = PC1 - cR.chats[pk2] = PC2 - - return &cR -} -*/ diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go index 105460dd0..435721e03 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go @@ -16,11 +16,11 @@ type ClientRepo struct { // NewClientRepo Constructor func NewClientRepo() *ClientRepo { - cR := ClientRepo{} + r := ClientRepo{} - cR.client, _ = cR.New() //nolint + r.client, _ = r.New() //nolint - return &cR + return &r } // New fills repo with a new client, if none has been set diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go index f9669f6bf..0f3c0fe36 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go @@ -15,16 +15,16 @@ type UserRepo struct { // NewUserRepo Constructor func NewUserRepo(pk cipher.PubKey) *UserRepo { - uR := UserRepo{} + r := UserRepo{} var err error - uR.user, err = uR.NewUser() - uR.user.GetInfo().SetPK(pk) + r.user, err = r.NewUser() + r.user.GetInfo().SetPK(pk) if err != nil { fmt.Println(err) } - return &uR + return &r } // NewUser fills repo with a new user, if none has been set diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go new file mode 100644 index 000000000..567801f5a --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go @@ -0,0 +1,85 @@ +// Package memory contains code of the chat repo of interfaceadapters +package memory + +import ( + "fmt" + "sync" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" +) + +// VisorRepo Implements the Repository Interface to provide an in-memory storage provider +type VisorRepo struct { + visors map[cipher.PubKey]chat.Visor + visorsMu sync.Mutex +} + +// NewVisorRepo Constructor +func NewVisorRepo() *VisorRepo { + r := VisorRepo{} + r.visors = make(map[cipher.PubKey]chat.Visor) + return &r +} + +// GetByPK Returns the visor with the provided pk +func (r *VisorRepo) GetByPK(pk cipher.PubKey) (*chat.Visor, error) { + r.visorsMu.Lock() + defer r.visorsMu.Unlock() + + visor, ok := r.visors[pk] + if !ok { + return nil, fmt.Errorf("visor not found") + } + return &visor, nil +} + +// GetAll Returns all stored visors +func (r *VisorRepo) GetAll() ([]chat.Visor, error) { + r.visorsMu.Lock() + defer r.visorsMu.Unlock() + // TODO(ersonp): code is unused; check for usage + // keys := make([]cipher.PubKey, 0) + + // for key := range r.chats { + // keys = append(keys, key) + // } + + var values []chat.Visor + for _, value := range r.visors { + values = append(values, value) + } + + return values, nil +} + +// Add adds the provided visor to the repository +func (r *VisorRepo) Add(visor chat.Visor) error { + r.visorsMu.Lock() + defer r.visorsMu.Unlock() + + r.visors[visor.GetPK()] = visor + return nil +} + +// Set sets the provided visor +func (r *VisorRepo) Set(visor chat.Visor) error { + r.visorsMu.Lock() + defer r.visorsMu.Unlock() + + r.visors[visor.GetPK()] = visor + return nil +} + +// Delete deletes the chat with the provided pk +func (r *VisorRepo) Delete(pk cipher.PubKey) error { + r.visorsMu.Lock() + defer r.visorsMu.Unlock() + + _, exists := r.visors[pk] + if !exists { + return fmt.Errorf("id %v not found", pk.String()) + } + delete(r.visors, pk) + return nil +} diff --git a/cmd/apps/skychat/skychat.go b/cmd/apps/skychat/skychat.go index eac3a65f0..fccc15a4a 100644 --- a/cmd/apps/skychat/skychat.go +++ b/cmd/apps/skychat/skychat.go @@ -19,7 +19,7 @@ func main() { flag.Parse() interfaceAdapterServices := interfaceadapters.NewServices() - appServices := app.NewServices(interfaceAdapterServices.ClientRepository, interfaceAdapterServices.UserRepository, interfaceAdapterServices.ChatRepository, interfaceAdapterServices.NotificationService, interfaceAdapterServices.MessengerService) + appServices := app.NewServices(interfaceAdapterServices.ClientRepository, interfaceAdapterServices.UserRepository, interfaceAdapterServices.VisorRepository, interfaceAdapterServices.NotificationService, interfaceAdapterServices.MessengerService) inputPortsServices := inputports.NewServices(appServices) //appclient listen diff --git a/vendor/github.com/ActiveState/termtest/conpty/term_other.go b/vendor/github.com/ActiveState/termtest/conpty/term_other.go index daef1c079..834d06230 100644 --- a/vendor/github.com/ActiveState/termtest/conpty/term_other.go +++ b/vendor/github.com/ActiveState/termtest/conpty/term_other.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package conpty diff --git a/vendor/github.com/ActiveState/termtest/conpty/term_windows.go b/vendor/github.com/ActiveState/termtest/conpty/term_windows.go index df091b5bb..b4d2ad00d 100644 --- a/vendor/github.com/ActiveState/termtest/conpty/term_windows.go +++ b/vendor/github.com/ActiveState/termtest/conpty/term_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package conpty diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go index a67327972..3195074fd 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/api.go b/vendor/github.com/Azure/go-ansiterm/winterm/api.go index 6055e33b9..2f297601b 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/api.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/api.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go index cbec8f728..644d8b2b4 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go index 3ee06ea72..6b4b8a1ef 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go index 244b5fa25..1298544a3 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go index 2d27fa1d0..03ab280c1 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go index afa7635d7..3535349f0 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go index 2d40fb75a..1e19ea0c3 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Microsoft/go-winio/backup.go b/vendor/github.com/Microsoft/go-winio/backup.go index 2be34af43..6b3f121f9 100644 --- a/vendor/github.com/Microsoft/go-winio/backup.go +++ b/vendor/github.com/Microsoft/go-winio/backup.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package winio diff --git a/vendor/github.com/Microsoft/go-winio/file.go b/vendor/github.com/Microsoft/go-winio/file.go index 0385e4108..0d97e08df 100644 --- a/vendor/github.com/Microsoft/go-winio/file.go +++ b/vendor/github.com/Microsoft/go-winio/file.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package winio diff --git a/vendor/github.com/Microsoft/go-winio/fileinfo.go b/vendor/github.com/Microsoft/go-winio/fileinfo.go index ada2fbab6..1720469ea 100644 --- a/vendor/github.com/Microsoft/go-winio/fileinfo.go +++ b/vendor/github.com/Microsoft/go-winio/fileinfo.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package winio diff --git a/vendor/github.com/Microsoft/go-winio/pipe.go b/vendor/github.com/Microsoft/go-winio/pipe.go index 96700a73d..58fa5f83a 100644 --- a/vendor/github.com/Microsoft/go-winio/pipe.go +++ b/vendor/github.com/Microsoft/go-winio/pipe.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package winio diff --git a/vendor/github.com/Microsoft/go-winio/privilege.go b/vendor/github.com/Microsoft/go-winio/privilege.go index 9c83d36fe..d6429f3c4 100644 --- a/vendor/github.com/Microsoft/go-winio/privilege.go +++ b/vendor/github.com/Microsoft/go-winio/privilege.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package winio diff --git a/vendor/github.com/Microsoft/go-winio/sd.go b/vendor/github.com/Microsoft/go-winio/sd.go index db1b370a1..ba7f7cfd3 100644 --- a/vendor/github.com/Microsoft/go-winio/sd.go +++ b/vendor/github.com/Microsoft/go-winio/sd.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package winio diff --git a/vendor/github.com/StackExchange/wmi/swbemservices.go b/vendor/github.com/StackExchange/wmi/swbemservices.go index 3ff875630..a250c846d 100644 --- a/vendor/github.com/StackExchange/wmi/swbemservices.go +++ b/vendor/github.com/StackExchange/wmi/swbemservices.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package wmi diff --git a/vendor/github.com/StackExchange/wmi/wmi.go b/vendor/github.com/StackExchange/wmi/wmi.go index b4bb4f090..0d9f9702d 100644 --- a/vendor/github.com/StackExchange/wmi/wmi.go +++ b/vendor/github.com/StackExchange/wmi/wmi.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows /* diff --git a/vendor/github.com/VictoriaMetrics/metrics/process_metrics_other.go b/vendor/github.com/VictoriaMetrics/metrics/process_metrics_other.go index 5e6ac935d..ca7167f80 100644 --- a/vendor/github.com/VictoriaMetrics/metrics/process_metrics_other.go +++ b/vendor/github.com/VictoriaMetrics/metrics/process_metrics_other.go @@ -1,3 +1,4 @@ +//go:build !linux // +build !linux package metrics diff --git a/vendor/github.com/creack/pty/ioctl.go b/vendor/github.com/creack/pty/ioctl.go index 067643795..45ec757a0 100644 --- a/vendor/github.com/creack/pty/ioctl.go +++ b/vendor/github.com/creack/pty/ioctl.go @@ -1,5 +1,5 @@ //go:build !windows && !solaris -//+build !windows,!solaris +// +build !windows,!solaris package pty diff --git a/vendor/github.com/creack/pty/ioctl_bsd.go b/vendor/github.com/creack/pty/ioctl_bsd.go index ab53e2db0..db3bf845b 100644 --- a/vendor/github.com/creack/pty/ioctl_bsd.go +++ b/vendor/github.com/creack/pty/ioctl_bsd.go @@ -1,5 +1,5 @@ -//go:build (darwin || dragonfly || freebsd || netbsd || openbsd) -//+build darwin dragonfly freebsd netbsd openbsd +//go:build darwin || dragonfly || freebsd || netbsd || openbsd +// +build darwin dragonfly freebsd netbsd openbsd package pty diff --git a/vendor/github.com/creack/pty/ioctl_solaris.go b/vendor/github.com/creack/pty/ioctl_solaris.go index 8b6cc0ec0..bff22dad0 100644 --- a/vendor/github.com/creack/pty/ioctl_solaris.go +++ b/vendor/github.com/creack/pty/ioctl_solaris.go @@ -1,5 +1,5 @@ //go:build solaris -//+build solaris +// +build solaris package pty diff --git a/vendor/github.com/creack/pty/pty_darwin.go b/vendor/github.com/creack/pty/pty_darwin.go index cca0971f1..9bdd71d08 100644 --- a/vendor/github.com/creack/pty/pty_darwin.go +++ b/vendor/github.com/creack/pty/pty_darwin.go @@ -1,5 +1,5 @@ //go:build darwin -//+build darwin +// +build darwin package pty diff --git a/vendor/github.com/creack/pty/pty_dragonfly.go b/vendor/github.com/creack/pty/pty_dragonfly.go index 7a1fec3a9..aa916aadf 100644 --- a/vendor/github.com/creack/pty/pty_dragonfly.go +++ b/vendor/github.com/creack/pty/pty_dragonfly.go @@ -1,5 +1,5 @@ //go:build dragonfly -//+build dragonfly +// +build dragonfly package pty diff --git a/vendor/github.com/creack/pty/pty_freebsd.go b/vendor/github.com/creack/pty/pty_freebsd.go index a4cfd925c..bcd3b6f90 100644 --- a/vendor/github.com/creack/pty/pty_freebsd.go +++ b/vendor/github.com/creack/pty/pty_freebsd.go @@ -1,5 +1,5 @@ //go:build freebsd -//+build freebsd +// +build freebsd package pty diff --git a/vendor/github.com/creack/pty/pty_linux.go b/vendor/github.com/creack/pty/pty_linux.go index 22ccbe128..a3b368f56 100644 --- a/vendor/github.com/creack/pty/pty_linux.go +++ b/vendor/github.com/creack/pty/pty_linux.go @@ -1,5 +1,5 @@ //go:build linux -//+build linux +// +build linux package pty diff --git a/vendor/github.com/creack/pty/pty_netbsd.go b/vendor/github.com/creack/pty/pty_netbsd.go index 98c089c8c..2b20d944c 100644 --- a/vendor/github.com/creack/pty/pty_netbsd.go +++ b/vendor/github.com/creack/pty/pty_netbsd.go @@ -1,5 +1,5 @@ //go:build netbsd -//+build netbsd +// +build netbsd package pty diff --git a/vendor/github.com/creack/pty/pty_openbsd.go b/vendor/github.com/creack/pty/pty_openbsd.go index d72b9d8d8..031367a85 100644 --- a/vendor/github.com/creack/pty/pty_openbsd.go +++ b/vendor/github.com/creack/pty/pty_openbsd.go @@ -1,5 +1,5 @@ //go:build openbsd -//+build openbsd +// +build openbsd package pty diff --git a/vendor/github.com/creack/pty/pty_solaris.go b/vendor/github.com/creack/pty/pty_solaris.go index 17e47461f..37f933e60 100644 --- a/vendor/github.com/creack/pty/pty_solaris.go +++ b/vendor/github.com/creack/pty/pty_solaris.go @@ -1,5 +1,5 @@ //go:build solaris -//+build solaris +// +build solaris package pty diff --git a/vendor/github.com/creack/pty/pty_unsupported.go b/vendor/github.com/creack/pty/pty_unsupported.go index 765523abc..c771020fa 100644 --- a/vendor/github.com/creack/pty/pty_unsupported.go +++ b/vendor/github.com/creack/pty/pty_unsupported.go @@ -1,5 +1,5 @@ //go:build !linux && !darwin && !freebsd && !dragonfly && !netbsd && !openbsd && !solaris -//+build !linux,!darwin,!freebsd,!dragonfly,!netbsd,!openbsd,!solaris +// +build !linux,!darwin,!freebsd,!dragonfly,!netbsd,!openbsd,!solaris package pty diff --git a/vendor/github.com/creack/pty/run.go b/vendor/github.com/creack/pty/run.go index 160001f9d..3e2b6ec33 100644 --- a/vendor/github.com/creack/pty/run.go +++ b/vendor/github.com/creack/pty/run.go @@ -1,5 +1,5 @@ //go:build !windows -//+build !windows +// +build !windows package pty diff --git a/vendor/github.com/creack/pty/winsize_unix.go b/vendor/github.com/creack/pty/winsize_unix.go index f358e9081..5d99c3dd9 100644 --- a/vendor/github.com/creack/pty/winsize_unix.go +++ b/vendor/github.com/creack/pty/winsize_unix.go @@ -1,5 +1,5 @@ //go:build !windows -//+build !windows +// +build !windows package pty diff --git a/vendor/github.com/creack/pty/winsize_unsupported.go b/vendor/github.com/creack/pty/winsize_unsupported.go index c4bff44e7..f1f1e1b67 100644 --- a/vendor/github.com/creack/pty/winsize_unsupported.go +++ b/vendor/github.com/creack/pty/winsize_unsupported.go @@ -1,5 +1,5 @@ //go:build windows -//+build windows +// +build windows package pty diff --git a/vendor/github.com/creack/pty/ztypes_386.go b/vendor/github.com/creack/pty/ztypes_386.go index 794515b4c..d126f4aa5 100644 --- a/vendor/github.com/creack/pty/ztypes_386.go +++ b/vendor/github.com/creack/pty/ztypes_386.go @@ -1,5 +1,5 @@ //go:build 386 -//+build 386 +// +build 386 // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types.go diff --git a/vendor/github.com/creack/pty/ztypes_amd64.go b/vendor/github.com/creack/pty/ztypes_amd64.go index dc6c52528..6c4a7677f 100644 --- a/vendor/github.com/creack/pty/ztypes_amd64.go +++ b/vendor/github.com/creack/pty/ztypes_amd64.go @@ -1,5 +1,5 @@ //go:build amd64 -//+build amd64 +// +build amd64 // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types.go diff --git a/vendor/github.com/creack/pty/ztypes_arm.go b/vendor/github.com/creack/pty/ztypes_arm.go index eac9b1ef7..de6fe160e 100644 --- a/vendor/github.com/creack/pty/ztypes_arm.go +++ b/vendor/github.com/creack/pty/ztypes_arm.go @@ -1,5 +1,5 @@ //go:build arm -//+build arm +// +build arm // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types.go diff --git a/vendor/github.com/creack/pty/ztypes_arm64.go b/vendor/github.com/creack/pty/ztypes_arm64.go index ecb3ddcab..c4f315cac 100644 --- a/vendor/github.com/creack/pty/ztypes_arm64.go +++ b/vendor/github.com/creack/pty/ztypes_arm64.go @@ -1,5 +1,5 @@ //go:build arm64 -//+build arm64 +// +build arm64 // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types.go diff --git a/vendor/github.com/creack/pty/ztypes_dragonfly_amd64.go b/vendor/github.com/creack/pty/ztypes_dragonfly_amd64.go index f4054cb60..183c42147 100644 --- a/vendor/github.com/creack/pty/ztypes_dragonfly_amd64.go +++ b/vendor/github.com/creack/pty/ztypes_dragonfly_amd64.go @@ -1,5 +1,5 @@ //go:build amd64 && dragonfly -//+build amd64,dragonfly +// +build amd64,dragonfly // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_dragonfly.go diff --git a/vendor/github.com/creack/pty/ztypes_freebsd_386.go b/vendor/github.com/creack/pty/ztypes_freebsd_386.go index 95a20ab3a..d80dbf717 100644 --- a/vendor/github.com/creack/pty/ztypes_freebsd_386.go +++ b/vendor/github.com/creack/pty/ztypes_freebsd_386.go @@ -1,5 +1,5 @@ //go:build 386 && freebsd -//+build 386,freebsd +// +build 386,freebsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_freebsd.go diff --git a/vendor/github.com/creack/pty/ztypes_freebsd_amd64.go b/vendor/github.com/creack/pty/ztypes_freebsd_amd64.go index e03a071c0..bfab4e458 100644 --- a/vendor/github.com/creack/pty/ztypes_freebsd_amd64.go +++ b/vendor/github.com/creack/pty/ztypes_freebsd_amd64.go @@ -1,5 +1,5 @@ //go:build amd64 && freebsd -//+build amd64,freebsd +// +build amd64,freebsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_freebsd.go diff --git a/vendor/github.com/creack/pty/ztypes_freebsd_arm.go b/vendor/github.com/creack/pty/ztypes_freebsd_arm.go index 7665bd3ca..3a8aeae37 100644 --- a/vendor/github.com/creack/pty/ztypes_freebsd_arm.go +++ b/vendor/github.com/creack/pty/ztypes_freebsd_arm.go @@ -1,5 +1,5 @@ //go:build arm && freebsd -//+build arm,freebsd +// +build arm,freebsd // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types_freebsd.go diff --git a/vendor/github.com/creack/pty/ztypes_freebsd_arm64.go b/vendor/github.com/creack/pty/ztypes_freebsd_arm64.go index 3f95bb8be..a83924918 100644 --- a/vendor/github.com/creack/pty/ztypes_freebsd_arm64.go +++ b/vendor/github.com/creack/pty/ztypes_freebsd_arm64.go @@ -1,5 +1,5 @@ //go:build arm64 && freebsd -//+build arm64,freebsd +// +build arm64,freebsd // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs types_freebsd.go diff --git a/vendor/github.com/creack/pty/ztypes_loongarchx.go b/vendor/github.com/creack/pty/ztypes_loongarchx.go index 674d2a408..e5142bf32 100644 --- a/vendor/github.com/creack/pty/ztypes_loongarchx.go +++ b/vendor/github.com/creack/pty/ztypes_loongarchx.go @@ -1,6 +1,6 @@ //go:build (loongarch32 || loongarch64) && linux -//+build linux -//+build loongarch32 loongarch64 +// +build loongarch32 loongarch64 +// +build linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types.go diff --git a/vendor/github.com/creack/pty/ztypes_mipsx.go b/vendor/github.com/creack/pty/ztypes_mipsx.go index eddad1639..281277977 100644 --- a/vendor/github.com/creack/pty/ztypes_mipsx.go +++ b/vendor/github.com/creack/pty/ztypes_mipsx.go @@ -1,6 +1,6 @@ //go:build (mips || mipsle || mips64 || mips64le) && linux -//+build linux -//+build mips mipsle mips64 mips64le +// +build mips mipsle mips64 mips64le +// +build linux // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types.go diff --git a/vendor/github.com/creack/pty/ztypes_netbsd_32bit_int.go b/vendor/github.com/creack/pty/ztypes_netbsd_32bit_int.go index 5b32e63eb..2ab7c4559 100644 --- a/vendor/github.com/creack/pty/ztypes_netbsd_32bit_int.go +++ b/vendor/github.com/creack/pty/ztypes_netbsd_32bit_int.go @@ -1,6 +1,6 @@ //go:build (386 || amd64 || arm || arm64) && netbsd -//+build netbsd -//+build 386 amd64 arm arm64 +// +build 386 amd64 arm arm64 +// +build netbsd package pty diff --git a/vendor/github.com/creack/pty/ztypes_openbsd_32bit_int.go b/vendor/github.com/creack/pty/ztypes_openbsd_32bit_int.go index c9aa3161b..1eb094816 100644 --- a/vendor/github.com/creack/pty/ztypes_openbsd_32bit_int.go +++ b/vendor/github.com/creack/pty/ztypes_openbsd_32bit_int.go @@ -1,6 +1,6 @@ //go:build (386 || amd64 || arm || arm64 || mips64) && openbsd -//+build openbsd -//+build 386 amd64 arm arm64 mips64 +// +build 386 amd64 arm arm64 mips64 +// +build openbsd package pty diff --git a/vendor/github.com/creack/pty/ztypes_ppc64.go b/vendor/github.com/creack/pty/ztypes_ppc64.go index 68634439b..bbb3da832 100644 --- a/vendor/github.com/creack/pty/ztypes_ppc64.go +++ b/vendor/github.com/creack/pty/ztypes_ppc64.go @@ -1,5 +1,5 @@ //go:build ppc64 -//+build ppc64 +// +build ppc64 // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types.go diff --git a/vendor/github.com/creack/pty/ztypes_ppc64le.go b/vendor/github.com/creack/pty/ztypes_ppc64le.go index 6b5621b17..8a4fac3e9 100644 --- a/vendor/github.com/creack/pty/ztypes_ppc64le.go +++ b/vendor/github.com/creack/pty/ztypes_ppc64le.go @@ -1,5 +1,5 @@ //go:build ppc64le -//+build ppc64le +// +build ppc64le // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types.go diff --git a/vendor/github.com/creack/pty/ztypes_riscvx.go b/vendor/github.com/creack/pty/ztypes_riscvx.go index 1233e75bc..dc5da9050 100644 --- a/vendor/github.com/creack/pty/ztypes_riscvx.go +++ b/vendor/github.com/creack/pty/ztypes_riscvx.go @@ -1,5 +1,5 @@ //go:build riscv || riscv64 -//+build riscv riscv64 +// +build riscv riscv64 // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs types.go diff --git a/vendor/github.com/creack/pty/ztypes_s390x.go b/vendor/github.com/creack/pty/ztypes_s390x.go index 02facea63..3433be7ca 100644 --- a/vendor/github.com/creack/pty/ztypes_s390x.go +++ b/vendor/github.com/creack/pty/ztypes_s390x.go @@ -1,5 +1,5 @@ //go:build s390x -//+build s390x +// +build s390x // Created by cgo -godefs - DO NOT EDIT // cgo -godefs types.go diff --git a/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go index 792994785..70ddeaad3 100644 --- a/vendor/github.com/davecgh/go-spew/spew/bypass.go +++ b/vendor/github.com/davecgh/go-spew/spew/bypass.go @@ -18,6 +18,7 @@ // tag is deprecated and thus should not be used. // Go versions prior to 1.4 are disabled because they use a different layout // for interfaces which make the implementation of unsafeReflectValue more complex. +//go:build !js && !appengine && !safe && !disableunsafe && go1.4 // +build !js,!appengine,!safe,!disableunsafe,go1.4 package spew diff --git a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go index 205c28d68..5e2d890d6 100644 --- a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go +++ b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go @@ -16,6 +16,7 @@ // when the code is running on Google App Engine, compiled by GopherJS, or // "-tags safe" is added to the go build command line. The "disableunsafe" // tag is deprecated and thus should not be used. +//go:build js || appengine || safe || disableunsafe || !go1.4 // +build js appengine safe disableunsafe !go1.4 package spew diff --git a/vendor/github.com/gen2brain/dlgs/color_darwin.go b/vendor/github.com/gen2brain/dlgs/color_darwin.go index d77c4cfd4..0ed8c14bd 100644 --- a/vendor/github.com/gen2brain/dlgs/color_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/color_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/color_js.go b/vendor/github.com/gen2brain/dlgs/color_js.go index 514ecb0d1..0602429b3 100644 --- a/vendor/github.com/gen2brain/dlgs/color_js.go +++ b/vendor/github.com/gen2brain/dlgs/color_js.go @@ -1,3 +1,4 @@ +//go:build js // +build js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/color_linux.go b/vendor/github.com/gen2brain/dlgs/color_linux.go index 3eed6d709..5bc26b39b 100644 --- a/vendor/github.com/gen2brain/dlgs/color_linux.go +++ b/vendor/github.com/gen2brain/dlgs/color_linux.go @@ -1,3 +1,4 @@ +//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/color_unsupported.go b/vendor/github.com/gen2brain/dlgs/color_unsupported.go index 213cb4c26..b3498110e 100644 --- a/vendor/github.com/gen2brain/dlgs/color_unsupported.go +++ b/vendor/github.com/gen2brain/dlgs/color_unsupported.go @@ -1,3 +1,4 @@ +//go:build !linux && !windows && !darwin && !js // +build !linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/color_windows.go b/vendor/github.com/gen2brain/dlgs/color_windows.go index 773b0e434..9e12cf5ba 100644 --- a/vendor/github.com/gen2brain/dlgs/color_windows.go +++ b/vendor/github.com/gen2brain/dlgs/color_windows.go @@ -1,3 +1,4 @@ +//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/date_darwin.go b/vendor/github.com/gen2brain/dlgs/date_darwin.go index 995f08a4f..79d7cd27e 100644 --- a/vendor/github.com/gen2brain/dlgs/date_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/date_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/date_js.go b/vendor/github.com/gen2brain/dlgs/date_js.go index c04e8aa62..44590fcbb 100644 --- a/vendor/github.com/gen2brain/dlgs/date_js.go +++ b/vendor/github.com/gen2brain/dlgs/date_js.go @@ -1,3 +1,4 @@ +//go:build js // +build js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/date_linux.go b/vendor/github.com/gen2brain/dlgs/date_linux.go index e01fcd51b..ac7dcb329 100644 --- a/vendor/github.com/gen2brain/dlgs/date_linux.go +++ b/vendor/github.com/gen2brain/dlgs/date_linux.go @@ -1,3 +1,4 @@ +//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/date_unsupported.go b/vendor/github.com/gen2brain/dlgs/date_unsupported.go index dedce2a46..d1743cd60 100644 --- a/vendor/github.com/gen2brain/dlgs/date_unsupported.go +++ b/vendor/github.com/gen2brain/dlgs/date_unsupported.go @@ -1,3 +1,4 @@ +//go:build !linux && !windows && !darwin && !js // +build !linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/date_windows.go b/vendor/github.com/gen2brain/dlgs/date_windows.go index 933269557..4e15ed042 100644 --- a/vendor/github.com/gen2brain/dlgs/date_windows.go +++ b/vendor/github.com/gen2brain/dlgs/date_windows.go @@ -1,3 +1,4 @@ +//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/dlgs_darwin.go b/vendor/github.com/gen2brain/dlgs/dlgs_darwin.go index d94a194bd..3c4359cc7 100644 --- a/vendor/github.com/gen2brain/dlgs/dlgs_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/dlgs_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/dlgs_linux.go b/vendor/github.com/gen2brain/dlgs/dlgs_linux.go index afb6d6f3a..9d7ddc4e5 100644 --- a/vendor/github.com/gen2brain/dlgs/dlgs_linux.go +++ b/vendor/github.com/gen2brain/dlgs/dlgs_linux.go @@ -1,3 +1,4 @@ +//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/dlgs_windows.go b/vendor/github.com/gen2brain/dlgs/dlgs_windows.go index e1feb3701..ba8034757 100644 --- a/vendor/github.com/gen2brain/dlgs/dlgs_windows.go +++ b/vendor/github.com/gen2brain/dlgs/dlgs_windows.go @@ -1,3 +1,4 @@ +//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/entry_darwin.go b/vendor/github.com/gen2brain/dlgs/entry_darwin.go index 19aa7613f..c10dcfae1 100644 --- a/vendor/github.com/gen2brain/dlgs/entry_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/entry_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/entry_js.go b/vendor/github.com/gen2brain/dlgs/entry_js.go index c4b96f825..eb786ec41 100644 --- a/vendor/github.com/gen2brain/dlgs/entry_js.go +++ b/vendor/github.com/gen2brain/dlgs/entry_js.go @@ -1,3 +1,4 @@ +//go:build js // +build js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/entry_linux.go b/vendor/github.com/gen2brain/dlgs/entry_linux.go index aabfbba54..500460e64 100644 --- a/vendor/github.com/gen2brain/dlgs/entry_linux.go +++ b/vendor/github.com/gen2brain/dlgs/entry_linux.go @@ -1,3 +1,4 @@ +//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/entry_unsupported.go b/vendor/github.com/gen2brain/dlgs/entry_unsupported.go index 25c53aa33..c8117aebe 100644 --- a/vendor/github.com/gen2brain/dlgs/entry_unsupported.go +++ b/vendor/github.com/gen2brain/dlgs/entry_unsupported.go @@ -1,3 +1,4 @@ +//go:build !linux && !windows && !darwin && !js // +build !linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/entry_windows.go b/vendor/github.com/gen2brain/dlgs/entry_windows.go index 9c8b22dd6..a78cc82af 100644 --- a/vendor/github.com/gen2brain/dlgs/entry_windows.go +++ b/vendor/github.com/gen2brain/dlgs/entry_windows.go @@ -1,3 +1,4 @@ +//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/file_darwin.go b/vendor/github.com/gen2brain/dlgs/file_darwin.go index 533793119..f4ffed1c2 100644 --- a/vendor/github.com/gen2brain/dlgs/file_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/file_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/file_js.go b/vendor/github.com/gen2brain/dlgs/file_js.go index d311ce04f..3c39b894f 100644 --- a/vendor/github.com/gen2brain/dlgs/file_js.go +++ b/vendor/github.com/gen2brain/dlgs/file_js.go @@ -1,10 +1,9 @@ +//go:build js // +build js package dlgs -import ( //"github.com/gopherjs/gopherjs/js" -) // File displays a file dialog, returning the selected file/directory and a bool for success. func File(title, filter string, directory bool) (string, bool, error) { diff --git a/vendor/github.com/gen2brain/dlgs/file_linux.go b/vendor/github.com/gen2brain/dlgs/file_linux.go index fce24d92c..bcec2ff04 100644 --- a/vendor/github.com/gen2brain/dlgs/file_linux.go +++ b/vendor/github.com/gen2brain/dlgs/file_linux.go @@ -1,3 +1,4 @@ +//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs @@ -9,8 +10,8 @@ import ( ) // File displays a file dialog, returning the selected file or directory, a bool for success, and an -// error if it was unable to display the dialog. Filter is a string that determines -// which extensions should be displayed for the dialog. Separate multiple file +// error if it was unable to display the dialog. Filter is a string that determines +// which extensions should be displayed for the dialog. Separate multiple file // extensions by spaces and use "*.extension" format for cross-platform compatibility, e.g. "*.png *.jpg". // A blank string for the filter will display all file types. func File(title, filter string, directory bool) (string, bool, error) { @@ -46,9 +47,9 @@ func File(title, filter string, directory bool) (string, bool, error) { return out, ret, err } -// FileMulti displays a file dialog that allows for selecting multiple files. It returns the selected -// files, a bool for success, and an error if it was unable to display the dialog. Filter is a string -// that determines which files should be available for selection in the dialog. Separate multiple file +// FileMulti displays a file dialog that allows for selecting multiple files. It returns the selected +// files, a bool for success, and an error if it was unable to display the dialog. Filter is a string +// that determines which files should be available for selection in the dialog. Separate multiple file // extensions by spaces and use "*.extension" format for cross-platform compatibility, e.g. "*.png *.jpg". // A blank string for the filter will display all file types. func FileMulti(title, filter string) ([]string, bool, error) { diff --git a/vendor/github.com/gen2brain/dlgs/file_unsupported.go b/vendor/github.com/gen2brain/dlgs/file_unsupported.go index 7c8784053..699ffc0cf 100644 --- a/vendor/github.com/gen2brain/dlgs/file_unsupported.go +++ b/vendor/github.com/gen2brain/dlgs/file_unsupported.go @@ -1,3 +1,4 @@ +//go:build !linux && !windows && !darwin && !js // +build !linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/file_windows.go b/vendor/github.com/gen2brain/dlgs/file_windows.go index 30d8c3fbf..f36d83cbc 100644 --- a/vendor/github.com/gen2brain/dlgs/file_windows.go +++ b/vendor/github.com/gen2brain/dlgs/file_windows.go @@ -1,3 +1,4 @@ +//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/list_darwin.go b/vendor/github.com/gen2brain/dlgs/list_darwin.go index 0775f184f..d41405a73 100644 --- a/vendor/github.com/gen2brain/dlgs/list_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/list_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/list_js.go b/vendor/github.com/gen2brain/dlgs/list_js.go index 905c03684..a6ff7e4ba 100644 --- a/vendor/github.com/gen2brain/dlgs/list_js.go +++ b/vendor/github.com/gen2brain/dlgs/list_js.go @@ -1,10 +1,9 @@ +//go:build js // +build js package dlgs -import ( //"github.com/gopherjs/gopherjs/js" -) // List displays a list dialog, returning the selected value and a bool for success. func List(title, text string, items []string) (string, bool, error) { diff --git a/vendor/github.com/gen2brain/dlgs/list_linux.go b/vendor/github.com/gen2brain/dlgs/list_linux.go index 38dc8a5d4..037ebb677 100644 --- a/vendor/github.com/gen2brain/dlgs/list_linux.go +++ b/vendor/github.com/gen2brain/dlgs/list_linux.go @@ -1,3 +1,4 @@ +//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/list_unsupported.go b/vendor/github.com/gen2brain/dlgs/list_unsupported.go index 026a25890..afe5a2bac 100644 --- a/vendor/github.com/gen2brain/dlgs/list_unsupported.go +++ b/vendor/github.com/gen2brain/dlgs/list_unsupported.go @@ -1,3 +1,4 @@ +//go:build !linux && !windows && !darwin && !js // +build !linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/list_windows.go b/vendor/github.com/gen2brain/dlgs/list_windows.go index 55ae56e0c..173780f15 100644 --- a/vendor/github.com/gen2brain/dlgs/list_windows.go +++ b/vendor/github.com/gen2brain/dlgs/list_windows.go @@ -1,3 +1,4 @@ +//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/message_darwin.go b/vendor/github.com/gen2brain/dlgs/message_darwin.go index bb56419d7..cfe8f9675 100644 --- a/vendor/github.com/gen2brain/dlgs/message_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/message_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/message_js.go b/vendor/github.com/gen2brain/dlgs/message_js.go index af204a5ac..a7a843806 100644 --- a/vendor/github.com/gen2brain/dlgs/message_js.go +++ b/vendor/github.com/gen2brain/dlgs/message_js.go @@ -1,3 +1,4 @@ +//go:build js // +build js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/message_linux.go b/vendor/github.com/gen2brain/dlgs/message_linux.go index 2f0f33cb2..2897a84d7 100644 --- a/vendor/github.com/gen2brain/dlgs/message_linux.go +++ b/vendor/github.com/gen2brain/dlgs/message_linux.go @@ -1,3 +1,4 @@ +//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/message_unsupported.go b/vendor/github.com/gen2brain/dlgs/message_unsupported.go index a633e8428..bd5ad0e2f 100644 --- a/vendor/github.com/gen2brain/dlgs/message_unsupported.go +++ b/vendor/github.com/gen2brain/dlgs/message_unsupported.go @@ -1,3 +1,4 @@ +//go:build !linux && !windows && !darwin && !js // +build !linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/message_windows.go b/vendor/github.com/gen2brain/dlgs/message_windows.go index f217575c7..a1ef23671 100644 --- a/vendor/github.com/gen2brain/dlgs/message_windows.go +++ b/vendor/github.com/gen2brain/dlgs/message_windows.go @@ -1,3 +1,4 @@ +//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/password_darwin.go b/vendor/github.com/gen2brain/dlgs/password_darwin.go index e2db710ef..9d9839512 100644 --- a/vendor/github.com/gen2brain/dlgs/password_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/password_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/password_js.go b/vendor/github.com/gen2brain/dlgs/password_js.go index 968fae5c2..73ebd4556 100644 --- a/vendor/github.com/gen2brain/dlgs/password_js.go +++ b/vendor/github.com/gen2brain/dlgs/password_js.go @@ -1,3 +1,4 @@ +//go:build js // +build js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/password_linux.go b/vendor/github.com/gen2brain/dlgs/password_linux.go index c755c0bb5..6ede485da 100644 --- a/vendor/github.com/gen2brain/dlgs/password_linux.go +++ b/vendor/github.com/gen2brain/dlgs/password_linux.go @@ -1,3 +1,4 @@ +//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/password_unsupported.go b/vendor/github.com/gen2brain/dlgs/password_unsupported.go index 607a2076d..74dc216cc 100644 --- a/vendor/github.com/gen2brain/dlgs/password_unsupported.go +++ b/vendor/github.com/gen2brain/dlgs/password_unsupported.go @@ -1,3 +1,4 @@ +//go:build !linux && !windows && !darwin && !js // +build !linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/password_windows.go b/vendor/github.com/gen2brain/dlgs/password_windows.go index ef1cf6beb..b4a13643e 100644 --- a/vendor/github.com/gen2brain/dlgs/password_windows.go +++ b/vendor/github.com/gen2brain/dlgs/password_windows.go @@ -1,3 +1,4 @@ +//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/go-ole/go-ole/com.go b/vendor/github.com/go-ole/go-ole/com.go index a9bef150a..6333441f9 100644 --- a/vendor/github.com/go-ole/go-ole/com.go +++ b/vendor/github.com/go-ole/go-ole/com.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/com_func.go b/vendor/github.com/go-ole/go-ole/com_func.go index cef539d9d..7b9fa67f3 100644 --- a/vendor/github.com/go-ole/go-ole/com_func.go +++ b/vendor/github.com/go-ole/go-ole/com_func.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/error_func.go b/vendor/github.com/go-ole/go-ole/error_func.go index 8a2ffaa27..6478b3390 100644 --- a/vendor/github.com/go-ole/go-ole/error_func.go +++ b/vendor/github.com/go-ole/go-ole/error_func.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/error_windows.go b/vendor/github.com/go-ole/go-ole/error_windows.go index d0e8e6859..8da277c05 100644 --- a/vendor/github.com/go-ole/go-ole/error_windows.go +++ b/vendor/github.com/go-ole/go-ole/error_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iconnectionpoint_func.go b/vendor/github.com/go-ole/go-ole/iconnectionpoint_func.go index 5414dc3cd..999720a0d 100644 --- a/vendor/github.com/go-ole/go-ole/iconnectionpoint_func.go +++ b/vendor/github.com/go-ole/go-ole/iconnectionpoint_func.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iconnectionpoint_windows.go b/vendor/github.com/go-ole/go-ole/iconnectionpoint_windows.go index 32bc18324..c7325ad0b 100644 --- a/vendor/github.com/go-ole/go-ole/iconnectionpoint_windows.go +++ b/vendor/github.com/go-ole/go-ole/iconnectionpoint_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_func.go b/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_func.go index 5dfa42aae..26e264d1b 100644 --- a/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_func.go +++ b/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_func.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_windows.go b/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_windows.go index ad30d79ef..8b090f49e 100644 --- a/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_windows.go +++ b/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/idispatch_func.go b/vendor/github.com/go-ole/go-ole/idispatch_func.go index b8fbbe319..5315505ae 100644 --- a/vendor/github.com/go-ole/go-ole/idispatch_func.go +++ b/vendor/github.com/go-ole/go-ole/idispatch_func.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/idispatch_windows.go b/vendor/github.com/go-ole/go-ole/idispatch_windows.go index b399f0479..ec2950aa0 100644 --- a/vendor/github.com/go-ole/go-ole/idispatch_windows.go +++ b/vendor/github.com/go-ole/go-ole/idispatch_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/ienumvariant_func.go b/vendor/github.com/go-ole/go-ole/ienumvariant_func.go index c14848199..f332e439b 100644 --- a/vendor/github.com/go-ole/go-ole/ienumvariant_func.go +++ b/vendor/github.com/go-ole/go-ole/ienumvariant_func.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/ienumvariant_windows.go b/vendor/github.com/go-ole/go-ole/ienumvariant_windows.go index 4781f3b8b..72e5f31d6 100644 --- a/vendor/github.com/go-ole/go-ole/ienumvariant_windows.go +++ b/vendor/github.com/go-ole/go-ole/ienumvariant_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iinspectable_func.go b/vendor/github.com/go-ole/go-ole/iinspectable_func.go index 348829bf0..cf0fba0dc 100644 --- a/vendor/github.com/go-ole/go-ole/iinspectable_func.go +++ b/vendor/github.com/go-ole/go-ole/iinspectable_func.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iinspectable_windows.go b/vendor/github.com/go-ole/go-ole/iinspectable_windows.go index 4519a4aa4..9a686d256 100644 --- a/vendor/github.com/go-ole/go-ole/iinspectable_windows.go +++ b/vendor/github.com/go-ole/go-ole/iinspectable_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iprovideclassinfo_func.go b/vendor/github.com/go-ole/go-ole/iprovideclassinfo_func.go index 7e3cb63ea..90109f557 100644 --- a/vendor/github.com/go-ole/go-ole/iprovideclassinfo_func.go +++ b/vendor/github.com/go-ole/go-ole/iprovideclassinfo_func.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iprovideclassinfo_windows.go b/vendor/github.com/go-ole/go-ole/iprovideclassinfo_windows.go index 2ad016394..c758acd9b 100644 --- a/vendor/github.com/go-ole/go-ole/iprovideclassinfo_windows.go +++ b/vendor/github.com/go-ole/go-ole/iprovideclassinfo_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/itypeinfo_func.go b/vendor/github.com/go-ole/go-ole/itypeinfo_func.go index 8364a659b..31c0677c6 100644 --- a/vendor/github.com/go-ole/go-ole/itypeinfo_func.go +++ b/vendor/github.com/go-ole/go-ole/itypeinfo_func.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/itypeinfo_windows.go b/vendor/github.com/go-ole/go-ole/itypeinfo_windows.go index 54782b3da..2abab8214 100644 --- a/vendor/github.com/go-ole/go-ole/itypeinfo_windows.go +++ b/vendor/github.com/go-ole/go-ole/itypeinfo_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iunknown_func.go b/vendor/github.com/go-ole/go-ole/iunknown_func.go index d0a62cfd7..247fccb3c 100644 --- a/vendor/github.com/go-ole/go-ole/iunknown_func.go +++ b/vendor/github.com/go-ole/go-ole/iunknown_func.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iunknown_windows.go b/vendor/github.com/go-ole/go-ole/iunknown_windows.go index ede5bb8c1..faf9c4c7f 100644 --- a/vendor/github.com/go-ole/go-ole/iunknown_windows.go +++ b/vendor/github.com/go-ole/go-ole/iunknown_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/oleutil/connection.go b/vendor/github.com/go-ole/go-ole/oleutil/connection.go index 60df73cda..4c52d55ef 100644 --- a/vendor/github.com/go-ole/go-ole/oleutil/connection.go +++ b/vendor/github.com/go-ole/go-ole/oleutil/connection.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package oleutil diff --git a/vendor/github.com/go-ole/go-ole/oleutil/connection_func.go b/vendor/github.com/go-ole/go-ole/oleutil/connection_func.go index 8818fb827..b00ac4a92 100644 --- a/vendor/github.com/go-ole/go-ole/oleutil/connection_func.go +++ b/vendor/github.com/go-ole/go-ole/oleutil/connection_func.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package oleutil diff --git a/vendor/github.com/go-ole/go-ole/oleutil/connection_windows.go b/vendor/github.com/go-ole/go-ole/oleutil/connection_windows.go index ab9c0d8dc..19fa27e51 100644 --- a/vendor/github.com/go-ole/go-ole/oleutil/connection_windows.go +++ b/vendor/github.com/go-ole/go-ole/oleutil/connection_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package oleutil diff --git a/vendor/github.com/go-ole/go-ole/oleutil/go-get.go b/vendor/github.com/go-ole/go-ole/oleutil/go-get.go index 58347628f..40bd9ff61 100644 --- a/vendor/github.com/go-ole/go-ole/oleutil/go-get.go +++ b/vendor/github.com/go-ole/go-ole/oleutil/go-get.go @@ -1,6 +1,7 @@ // This file is here so go get succeeds as without it errors with: // no buildable Go source files in ... // +//go:build !windows // +build !windows package oleutil diff --git a/vendor/github.com/go-ole/go-ole/safearray_func.go b/vendor/github.com/go-ole/go-ole/safearray_func.go index 0dee670ce..afb1d02d5 100644 --- a/vendor/github.com/go-ole/go-ole/safearray_func.go +++ b/vendor/github.com/go-ole/go-ole/safearray_func.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/safearray_windows.go b/vendor/github.com/go-ole/go-ole/safearray_windows.go index 0c1b3a10f..0a322f5da 100644 --- a/vendor/github.com/go-ole/go-ole/safearray_windows.go +++ b/vendor/github.com/go-ole/go-ole/safearray_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/safearrayconversion.go b/vendor/github.com/go-ole/go-ole/safearrayconversion.go index da737293d..dde3e17e0 100644 --- a/vendor/github.com/go-ole/go-ole/safearrayconversion.go +++ b/vendor/github.com/go-ole/go-ole/safearrayconversion.go @@ -84,7 +84,7 @@ func (sac *SafeArrayConversion) ToValueArray() (values []interface{}) { safeArrayGetElement(sac.Array, i, unsafe.Pointer(&v)) values[i] = v case VT_BSTR: - v , _ := safeArrayGetElementString(sac.Array, i) + v, _ := safeArrayGetElementString(sac.Array, i) values[i] = v case VT_VARIANT: var v VARIANT diff --git a/vendor/github.com/go-ole/go-ole/safearrayslices.go b/vendor/github.com/go-ole/go-ole/safearrayslices.go index a9fa885f1..063dbbfec 100644 --- a/vendor/github.com/go-ole/go-ole/safearrayslices.go +++ b/vendor/github.com/go-ole/go-ole/safearrayslices.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/variables.go b/vendor/github.com/go-ole/go-ole/variables.go index a6add1b00..056f844d9 100644 --- a/vendor/github.com/go-ole/go-ole/variables.go +++ b/vendor/github.com/go-ole/go-ole/variables.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_386.go b/vendor/github.com/go-ole/go-ole/variant_386.go index e73736bf3..2e3d3aa4a 100644 --- a/vendor/github.com/go-ole/go-ole/variant_386.go +++ b/vendor/github.com/go-ole/go-ole/variant_386.go @@ -1,3 +1,4 @@ +//go:build 386 // +build 386 package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_amd64.go b/vendor/github.com/go-ole/go-ole/variant_amd64.go index dccdde132..b48c3ce6f 100644 --- a/vendor/github.com/go-ole/go-ole/variant_amd64.go +++ b/vendor/github.com/go-ole/go-ole/variant_amd64.go @@ -1,3 +1,4 @@ +//go:build amd64 // +build amd64 package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_arm.go b/vendor/github.com/go-ole/go-ole/variant_arm.go index d47245444..5c8d492d6 100644 --- a/vendor/github.com/go-ole/go-ole/variant_arm.go +++ b/vendor/github.com/go-ole/go-ole/variant_arm.go @@ -1,3 +1,4 @@ +//go:build arm // +build arm package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_date_386.go b/vendor/github.com/go-ole/go-ole/variant_date_386.go index 1b970f63f..8c3d3085f 100644 --- a/vendor/github.com/go-ole/go-ole/variant_date_386.go +++ b/vendor/github.com/go-ole/go-ole/variant_date_386.go @@ -1,3 +1,4 @@ +//go:build windows && 386 // +build windows,386 package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_date_amd64.go b/vendor/github.com/go-ole/go-ole/variant_date_amd64.go index 6952f1f0d..8554d38d9 100644 --- a/vendor/github.com/go-ole/go-ole/variant_date_amd64.go +++ b/vendor/github.com/go-ole/go-ole/variant_date_amd64.go @@ -1,3 +1,4 @@ +//go:build windows && amd64 // +build windows,amd64 package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_date_arm.go b/vendor/github.com/go-ole/go-ole/variant_date_arm.go index 09ec7b5cf..7afe38b89 100644 --- a/vendor/github.com/go-ole/go-ole/variant_date_arm.go +++ b/vendor/github.com/go-ole/go-ole/variant_date_arm.go @@ -1,3 +1,4 @@ +//go:build windows && arm // +build windows,arm package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_ppc64le.go b/vendor/github.com/go-ole/go-ole/variant_ppc64le.go index 326427a7d..4ce060d8f 100644 --- a/vendor/github.com/go-ole/go-ole/variant_ppc64le.go +++ b/vendor/github.com/go-ole/go-ole/variant_ppc64le.go @@ -1,3 +1,4 @@ +//go:build ppc64le // +build ppc64le package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_s390x.go b/vendor/github.com/go-ole/go-ole/variant_s390x.go index 9874ca66b..f83731098 100644 --- a/vendor/github.com/go-ole/go-ole/variant_s390x.go +++ b/vendor/github.com/go-ole/go-ole/variant_s390x.go @@ -1,3 +1,4 @@ +//go:build s390x // +build s390x package ole diff --git a/vendor/github.com/go-ole/go-ole/winrt.go b/vendor/github.com/go-ole/go-ole/winrt.go index 4e9eca732..f503d685f 100644 --- a/vendor/github.com/go-ole/go-ole/winrt.go +++ b/vendor/github.com/go-ole/go-ole/winrt.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/winrt_doc.go b/vendor/github.com/go-ole/go-ole/winrt_doc.go index 52e6d74c9..a392928d2 100644 --- a/vendor/github.com/go-ole/go-ole/winrt_doc.go +++ b/vendor/github.com/go-ole/go-ole/winrt_doc.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/godbus/dbus/v5/conn_other.go b/vendor/github.com/godbus/dbus/v5/conn_other.go index 90289ca85..8d4e6bc41 100644 --- a/vendor/github.com/godbus/dbus/v5/conn_other.go +++ b/vendor/github.com/godbus/dbus/v5/conn_other.go @@ -1,3 +1,4 @@ +//go:build !darwin // +build !darwin package dbus diff --git a/vendor/github.com/godbus/dbus/v5/conn_unix.go b/vendor/github.com/godbus/dbus/v5/conn_unix.go index 58aee7d2a..1a0daa656 100644 --- a/vendor/github.com/godbus/dbus/v5/conn_unix.go +++ b/vendor/github.com/godbus/dbus/v5/conn_unix.go @@ -1,4 +1,5 @@ -//+build !windows,!solaris,!darwin +//go:build !windows && !solaris && !darwin +// +build !windows,!solaris,!darwin package dbus diff --git a/vendor/github.com/godbus/dbus/v5/conn_windows.go b/vendor/github.com/godbus/dbus/v5/conn_windows.go index 4291e4519..0515dd003 100644 --- a/vendor/github.com/godbus/dbus/v5/conn_windows.go +++ b/vendor/github.com/godbus/dbus/v5/conn_windows.go @@ -1,4 +1,5 @@ -//+build windows +//go:build windows +// +build windows package dbus diff --git a/vendor/github.com/godbus/dbus/v5/sequential_handler.go b/vendor/github.com/godbus/dbus/v5/sequential_handler.go index ef2fcdba1..886b5eb16 100644 --- a/vendor/github.com/godbus/dbus/v5/sequential_handler.go +++ b/vendor/github.com/godbus/dbus/v5/sequential_handler.go @@ -93,7 +93,7 @@ func (scd *sequentialSignalChannelData) bufferSignals() { var queue []*Signal for { if len(queue) == 0 { - signal, ok := <- scd.in + signal, ok := <-scd.in if !ok { return } diff --git a/vendor/github.com/godbus/dbus/v5/transport_nonce_tcp.go b/vendor/github.com/godbus/dbus/v5/transport_nonce_tcp.go index 697739efa..a61a82084 100644 --- a/vendor/github.com/godbus/dbus/v5/transport_nonce_tcp.go +++ b/vendor/github.com/godbus/dbus/v5/transport_nonce_tcp.go @@ -1,4 +1,5 @@ -//+build !windows +//go:build !windows +// +build !windows package dbus diff --git a/vendor/github.com/godbus/dbus/v5/transport_unix.go b/vendor/github.com/godbus/dbus/v5/transport_unix.go index 0a8c712eb..ffccff0c3 100644 --- a/vendor/github.com/godbus/dbus/v5/transport_unix.go +++ b/vendor/github.com/godbus/dbus/v5/transport_unix.go @@ -1,4 +1,5 @@ -//+build !windows,!solaris +//go:build !windows && !solaris +// +build !windows,!solaris package dbus diff --git a/vendor/github.com/google/uuid/node_js.go b/vendor/github.com/google/uuid/node_js.go index 24b78edc9..96090351a 100644 --- a/vendor/github.com/google/uuid/node_js.go +++ b/vendor/github.com/google/uuid/node_js.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build js // +build js package uuid diff --git a/vendor/github.com/google/uuid/node_net.go b/vendor/github.com/google/uuid/node_net.go index 0cbbcddbd..e91358f7d 100644 --- a/vendor/github.com/google/uuid/node_net.go +++ b/vendor/github.com/google/uuid/node_net.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build !js // +build !js package uuid diff --git a/vendor/github.com/gorilla/securecookie/fuzz.go b/vendor/github.com/gorilla/securecookie/fuzz.go index e4d0534e4..b8658e0ae 100644 --- a/vendor/github.com/gorilla/securecookie/fuzz.go +++ b/vendor/github.com/gorilla/securecookie/fuzz.go @@ -1,3 +1,4 @@ +//go:build gofuzz // +build gofuzz package securecookie diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_others.go b/vendor/github.com/inconshreveable/mousetrap/trap_others.go index 9d2d8a4ba..06a91f086 100644 --- a/vendor/github.com/inconshreveable/mousetrap/trap_others.go +++ b/vendor/github.com/inconshreveable/mousetrap/trap_others.go @@ -1,3 +1,4 @@ +//go:build !windows // +build !windows package mousetrap diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows.go index 336142a5e..2d2adac9e 100644 --- a/vendor/github.com/inconshreveable/mousetrap/trap_windows.go +++ b/vendor/github.com/inconshreveable/mousetrap/trap_windows.go @@ -1,5 +1,5 @@ -// +build windows -// +build !go1.4 +//go:build windows && !go1.4 +// +build windows,!go1.4 package mousetrap diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go index 9a28e57c3..c78a98fdc 100644 --- a/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go +++ b/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go @@ -1,5 +1,5 @@ -// +build windows -// +build go1.4 +//go:build windows && go1.4 +// +build windows,go1.4 package mousetrap diff --git a/vendor/github.com/james-barrow/golang-ipc/connect_other.go b/vendor/github.com/james-barrow/golang-ipc/connect_other.go index 187273c5d..4f4fbebe0 100644 --- a/vendor/github.com/james-barrow/golang-ipc/connect_other.go +++ b/vendor/github.com/james-barrow/golang-ipc/connect_other.go @@ -1,3 +1,4 @@ +//go:build linux || darwin // +build linux darwin package ipc diff --git a/vendor/github.com/json-iterator/go/any.go b/vendor/github.com/json-iterator/go/any.go index f6b8aeab0..4b7e1cf5c 100644 --- a/vendor/github.com/json-iterator/go/any.go +++ b/vendor/github.com/json-iterator/go/any.go @@ -3,11 +3,12 @@ package jsoniter import ( "errors" "fmt" - "github.com/modern-go/reflect2" "io" "reflect" "strconv" "unsafe" + + "github.com/modern-go/reflect2" ) // Any generic object representation. diff --git a/vendor/github.com/json-iterator/go/iter_skip_sloppy.go b/vendor/github.com/json-iterator/go/iter_skip_sloppy.go index 9303de41e..3d993f277 100644 --- a/vendor/github.com/json-iterator/go/iter_skip_sloppy.go +++ b/vendor/github.com/json-iterator/go/iter_skip_sloppy.go @@ -1,4 +1,5 @@ -//+build jsoniter_sloppy +//go:build jsoniter_sloppy +// +build jsoniter_sloppy package jsoniter diff --git a/vendor/github.com/json-iterator/go/iter_skip_strict.go b/vendor/github.com/json-iterator/go/iter_skip_strict.go index 6cf66d043..f1ad6591b 100644 --- a/vendor/github.com/json-iterator/go/iter_skip_strict.go +++ b/vendor/github.com/json-iterator/go/iter_skip_strict.go @@ -1,4 +1,5 @@ -//+build !jsoniter_sloppy +//go:build !jsoniter_sloppy +// +build !jsoniter_sloppy package jsoniter diff --git a/vendor/github.com/json-iterator/go/reflect_array.go b/vendor/github.com/json-iterator/go/reflect_array.go index 13a0b7b08..7eb5b1dc9 100644 --- a/vendor/github.com/json-iterator/go/reflect_array.go +++ b/vendor/github.com/json-iterator/go/reflect_array.go @@ -2,9 +2,10 @@ package jsoniter import ( "fmt" - "github.com/modern-go/reflect2" "io" "unsafe" + + "github.com/modern-go/reflect2" ) func decoderOfArray(ctx *ctx, typ reflect2.Type) ValDecoder { diff --git a/vendor/github.com/json-iterator/go/reflect_dynamic.go b/vendor/github.com/json-iterator/go/reflect_dynamic.go index 8b6bc8b43..71a0fe273 100644 --- a/vendor/github.com/json-iterator/go/reflect_dynamic.go +++ b/vendor/github.com/json-iterator/go/reflect_dynamic.go @@ -1,9 +1,10 @@ package jsoniter import ( - "github.com/modern-go/reflect2" "reflect" "unsafe" + + "github.com/modern-go/reflect2" ) type dynamicEncoder struct { diff --git a/vendor/github.com/json-iterator/go/reflect_extension.go b/vendor/github.com/json-iterator/go/reflect_extension.go index 74a97bfe5..a820f10ca 100644 --- a/vendor/github.com/json-iterator/go/reflect_extension.go +++ b/vendor/github.com/json-iterator/go/reflect_extension.go @@ -2,12 +2,13 @@ package jsoniter import ( "fmt" - "github.com/modern-go/reflect2" "reflect" "sort" "strings" "unicode" "unsafe" + + "github.com/modern-go/reflect2" ) var typeDecoders = map[string]ValDecoder{} diff --git a/vendor/github.com/json-iterator/go/reflect_json_number.go b/vendor/github.com/json-iterator/go/reflect_json_number.go index 98d45c1ec..52e11bf3f 100644 --- a/vendor/github.com/json-iterator/go/reflect_json_number.go +++ b/vendor/github.com/json-iterator/go/reflect_json_number.go @@ -2,9 +2,10 @@ package jsoniter import ( "encoding/json" - "github.com/modern-go/reflect2" "strconv" "unsafe" + + "github.com/modern-go/reflect2" ) type Number string diff --git a/vendor/github.com/json-iterator/go/reflect_json_raw_message.go b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go index eba434f2f..521e38a89 100644 --- a/vendor/github.com/json-iterator/go/reflect_json_raw_message.go +++ b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go @@ -2,8 +2,9 @@ package jsoniter import ( "encoding/json" - "github.com/modern-go/reflect2" "unsafe" + + "github.com/modern-go/reflect2" ) var jsonRawMessageType = reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem() diff --git a/vendor/github.com/json-iterator/go/reflect_map.go b/vendor/github.com/json-iterator/go/reflect_map.go index 582967130..696194bde 100644 --- a/vendor/github.com/json-iterator/go/reflect_map.go +++ b/vendor/github.com/json-iterator/go/reflect_map.go @@ -2,11 +2,12 @@ package jsoniter import ( "fmt" - "github.com/modern-go/reflect2" "io" "reflect" "sort" "unsafe" + + "github.com/modern-go/reflect2" ) func decoderOfMap(ctx *ctx, typ reflect2.Type) ValDecoder { diff --git a/vendor/github.com/json-iterator/go/reflect_optional.go b/vendor/github.com/json-iterator/go/reflect_optional.go index fa71f4748..112c110a2 100644 --- a/vendor/github.com/json-iterator/go/reflect_optional.go +++ b/vendor/github.com/json-iterator/go/reflect_optional.go @@ -1,8 +1,9 @@ package jsoniter import ( - "github.com/modern-go/reflect2" "unsafe" + + "github.com/modern-go/reflect2" ) func decoderOfOptional(ctx *ctx, typ reflect2.Type) ValDecoder { diff --git a/vendor/github.com/json-iterator/go/reflect_slice.go b/vendor/github.com/json-iterator/go/reflect_slice.go index 9441d79df..f363a7169 100644 --- a/vendor/github.com/json-iterator/go/reflect_slice.go +++ b/vendor/github.com/json-iterator/go/reflect_slice.go @@ -2,9 +2,10 @@ package jsoniter import ( "fmt" - "github.com/modern-go/reflect2" "io" "unsafe" + + "github.com/modern-go/reflect2" ) func decoderOfSlice(ctx *ctx, typ reflect2.Type) ValDecoder { diff --git a/vendor/github.com/json-iterator/go/reflect_struct_encoder.go b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go index 152e3ef5a..edf77bf59 100644 --- a/vendor/github.com/json-iterator/go/reflect_struct_encoder.go +++ b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go @@ -2,10 +2,11 @@ package jsoniter import ( "fmt" - "github.com/modern-go/reflect2" "io" "reflect" "unsafe" + + "github.com/modern-go/reflect2" ) func encoderOfStruct(ctx *ctx, typ reflect2.Type) ValEncoder { diff --git a/vendor/github.com/klauspost/compress/flate/gen_inflate.go b/vendor/github.com/klauspost/compress/flate/gen_inflate.go index b26d19ec2..25ba3c714 100644 --- a/vendor/github.com/klauspost/compress/flate/gen_inflate.go +++ b/vendor/github.com/klauspost/compress/flate/gen_inflate.go @@ -1,3 +1,4 @@ +//go:build generate // +build generate //go:generate go run $GOFILE && gofmt -w inflate_gen.go diff --git a/vendor/github.com/klauspost/compress/flate/regmask_other.go b/vendor/github.com/klauspost/compress/flate/regmask_other.go index f477a5d6e..1b7a2cbd7 100644 --- a/vendor/github.com/klauspost/compress/flate/regmask_other.go +++ b/vendor/github.com/klauspost/compress/flate/regmask_other.go @@ -1,4 +1,5 @@ -//+build !amd64 +//go:build !amd64 +// +build !amd64 package flate diff --git a/vendor/github.com/klauspost/cpuid/detect_intel.go b/vendor/github.com/klauspost/cpuid/detect_intel.go index a5f04dd6d..09f9d6c15 100644 --- a/vendor/github.com/klauspost/cpuid/detect_intel.go +++ b/vendor/github.com/klauspost/cpuid/detect_intel.go @@ -1,5 +1,6 @@ // Copyright (c) 2015 Klaus Post, released under MIT License. See LICENSE file. +//go:build (386 && !gccgo) || (amd64 && !gccgo) // +build 386,!gccgo amd64,!gccgo package cpuid diff --git a/vendor/github.com/klauspost/cpuid/detect_ref.go b/vendor/github.com/klauspost/cpuid/detect_ref.go index 909c5d9a7..8281367ac 100644 --- a/vendor/github.com/klauspost/cpuid/detect_ref.go +++ b/vendor/github.com/klauspost/cpuid/detect_ref.go @@ -1,5 +1,6 @@ // Copyright (c) 2015 Klaus Post, released under MIT License. See LICENSE file. +//go:build (!amd64 && !386) || gccgo // +build !amd64,!386 gccgo package cpuid diff --git a/vendor/github.com/klauspost/reedsolomon/galoisAvx512_amd64.go b/vendor/github.com/klauspost/reedsolomon/galoisAvx512_amd64.go index 720196fa5..0f240b7d6 100644 --- a/vendor/github.com/klauspost/reedsolomon/galoisAvx512_amd64.go +++ b/vendor/github.com/klauspost/reedsolomon/galoisAvx512_amd64.go @@ -1,6 +1,5 @@ -//+build !noasm -//+build !appengine -//+build !gccgo +//go:build !noasm && !appengine && !gccgo +// +build !noasm,!appengine,!gccgo // Copyright 2015, Klaus Post, see LICENSE for details. // Copyright 2019, Minio, Inc. diff --git a/vendor/github.com/klauspost/reedsolomon/galois_amd64.go b/vendor/github.com/klauspost/reedsolomon/galois_amd64.go index f757f9d6e..2db862193 100644 --- a/vendor/github.com/klauspost/reedsolomon/galois_amd64.go +++ b/vendor/github.com/klauspost/reedsolomon/galois_amd64.go @@ -1,6 +1,5 @@ -//+build !noasm -//+build !appengine -//+build !gccgo +//go:build !noasm && !appengine && !gccgo +// +build !noasm,!appengine,!gccgo // Copyright 2015, Klaus Post, see LICENSE for details. diff --git a/vendor/github.com/klauspost/reedsolomon/galois_arm64.go b/vendor/github.com/klauspost/reedsolomon/galois_arm64.go index 23a1dd26f..93acd747a 100644 --- a/vendor/github.com/klauspost/reedsolomon/galois_arm64.go +++ b/vendor/github.com/klauspost/reedsolomon/galois_arm64.go @@ -1,6 +1,5 @@ -//+build !noasm -//+build !appengine -//+build !gccgo +//go:build !noasm && !appengine && !gccgo +// +build !noasm,!appengine,!gccgo // Copyright 2015, Klaus Post, see LICENSE for details. // Copyright 2017, Minio, Inc. diff --git a/vendor/github.com/klauspost/reedsolomon/galois_gen_amd64.go b/vendor/github.com/klauspost/reedsolomon/galois_gen_amd64.go index edd6376a7..98c904596 100644 --- a/vendor/github.com/klauspost/reedsolomon/galois_gen_amd64.go +++ b/vendor/github.com/klauspost/reedsolomon/galois_gen_amd64.go @@ -1,9 +1,7 @@ // Code generated by command: go run gen.go -out galois_gen_amd64.s -stubs galois_gen_amd64.go. DO NOT EDIT. -// +build !appengine -// +build !noasm -// +build !nogen -// +build gc +//go:build !appengine && !noasm && !nogen && gc +// +build !appengine,!noasm,!nogen,gc package reedsolomon diff --git a/vendor/github.com/klauspost/reedsolomon/galois_gen_none.go b/vendor/github.com/klauspost/reedsolomon/galois_gen_none.go index b4917bc01..f11b6ee3c 100644 --- a/vendor/github.com/klauspost/reedsolomon/galois_gen_none.go +++ b/vendor/github.com/klauspost/reedsolomon/galois_gen_none.go @@ -1,4 +1,5 @@ -//+build !amd64 noasm appengine gccgo nogen +//go:build !amd64 || noasm || appengine || gccgo || nogen +// +build !amd64 noasm appengine gccgo nogen package reedsolomon diff --git a/vendor/github.com/klauspost/reedsolomon/galois_gen_switch_amd64.go b/vendor/github.com/klauspost/reedsolomon/galois_gen_switch_amd64.go index 0b49a1e66..5345af8e6 100644 --- a/vendor/github.com/klauspost/reedsolomon/galois_gen_switch_amd64.go +++ b/vendor/github.com/klauspost/reedsolomon/galois_gen_switch_amd64.go @@ -1,9 +1,7 @@ // Code generated by command: go generate gen.go. DO NOT EDIT. -// +build !appengine -// +build !noasm -// +build gc -// +build !nogen +//go:build !appengine && !noasm && gc && !nogen +// +build !appengine,!noasm,gc,!nogen package reedsolomon diff --git a/vendor/github.com/klauspost/reedsolomon/galois_noasm.go b/vendor/github.com/klauspost/reedsolomon/galois_noasm.go index 1d00e0632..6d3a5a785 100644 --- a/vendor/github.com/klauspost/reedsolomon/galois_noasm.go +++ b/vendor/github.com/klauspost/reedsolomon/galois_noasm.go @@ -1,6 +1,7 @@ -//+build !amd64 noasm appengine gccgo -//+build !arm64 noasm appengine gccgo -//+build !ppc64le noasm appengine gccgo +//go:build (!amd64 || noasm || appengine || gccgo) && (!arm64 || noasm || appengine || gccgo) && (!ppc64le || noasm || appengine || gccgo) +// +build !amd64 noasm appengine gccgo +// +build !arm64 noasm appengine gccgo +// +build !ppc64le noasm appengine gccgo // Copyright 2015, Klaus Post, see LICENSE for details. diff --git a/vendor/github.com/klauspost/reedsolomon/galois_notamd64.go b/vendor/github.com/klauspost/reedsolomon/galois_notamd64.go index bd15e3a23..e9472f776 100644 --- a/vendor/github.com/klauspost/reedsolomon/galois_notamd64.go +++ b/vendor/github.com/klauspost/reedsolomon/galois_notamd64.go @@ -1,4 +1,5 @@ -//+build !amd64 noasm appengine gccgo +//go:build !amd64 || noasm || appengine || gccgo +// +build !amd64 noasm appengine gccgo // Copyright 2020, Klaus Post, see LICENSE for details. diff --git a/vendor/github.com/klauspost/reedsolomon/galois_ppc64le.go b/vendor/github.com/klauspost/reedsolomon/galois_ppc64le.go index 70f93d678..52e8c23af 100644 --- a/vendor/github.com/klauspost/reedsolomon/galois_ppc64le.go +++ b/vendor/github.com/klauspost/reedsolomon/galois_ppc64le.go @@ -1,6 +1,5 @@ -//+build !noasm -//+build !appengine -//+build !gccgo +//go:build !noasm && !appengine && !gccgo +// +build !noasm,!appengine,!gccgo // Copyright 2015, Klaus Post, see LICENSE for details. // Copyright 2018, Minio, Inc. diff --git a/vendor/github.com/klauspost/reedsolomon/gen.go b/vendor/github.com/klauspost/reedsolomon/gen.go index 6fc545c47..416d4cc80 100644 --- a/vendor/github.com/klauspost/reedsolomon/gen.go +++ b/vendor/github.com/klauspost/reedsolomon/gen.go @@ -1,4 +1,5 @@ -//+build generate +//go:build generate +// +build generate //go:generate go run gen.go -out galois_gen_amd64.s -stubs galois_gen_amd64.go //go:generate gofmt -w galois_gen_switch_amd64.go diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go index ef18d8f97..953c5d984 100644 --- a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go +++ b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package sequences diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go index df61a6f2f..4c5817416 100644 --- a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go +++ b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go @@ -1,3 +1,4 @@ +//go:build linux || darwin // +build linux darwin package sequences diff --git a/vendor/github.com/modern-go/concurrent/go_above_19.go b/vendor/github.com/modern-go/concurrent/go_above_19.go index aeabf8c4f..7db701945 100644 --- a/vendor/github.com/modern-go/concurrent/go_above_19.go +++ b/vendor/github.com/modern-go/concurrent/go_above_19.go @@ -1,4 +1,5 @@ -//+build go1.9 +//go:build go1.9 +// +build go1.9 package concurrent diff --git a/vendor/github.com/modern-go/concurrent/go_below_19.go b/vendor/github.com/modern-go/concurrent/go_below_19.go index b9c8df7f4..64544f5b3 100644 --- a/vendor/github.com/modern-go/concurrent/go_below_19.go +++ b/vendor/github.com/modern-go/concurrent/go_below_19.go @@ -1,4 +1,5 @@ -//+build !go1.9 +//go:build !go1.9 +// +build !go1.9 package concurrent diff --git a/vendor/github.com/modern-go/concurrent/log.go b/vendor/github.com/modern-go/concurrent/log.go index 9756fcc75..4899eed02 100644 --- a/vendor/github.com/modern-go/concurrent/log.go +++ b/vendor/github.com/modern-go/concurrent/log.go @@ -1,13 +1,13 @@ package concurrent import ( - "os" - "log" "io/ioutil" + "log" + "os" ) // ErrorLogger is used to print out error, can be set to writer other than stderr var ErrorLogger = log.New(os.Stderr, "", 0) // InfoLogger is used to print informational message, default to off -var InfoLogger = log.New(ioutil.Discard, "", 0) \ No newline at end of file +var InfoLogger = log.New(ioutil.Discard, "", 0) diff --git a/vendor/github.com/modern-go/concurrent/unbounded_executor.go b/vendor/github.com/modern-go/concurrent/unbounded_executor.go index 05a77dceb..5ea18eb7b 100644 --- a/vendor/github.com/modern-go/concurrent/unbounded_executor.go +++ b/vendor/github.com/modern-go/concurrent/unbounded_executor.go @@ -3,11 +3,11 @@ package concurrent import ( "context" "fmt" + "reflect" "runtime" "runtime/debug" "sync" "time" - "reflect" ) // HandlePanic logs goroutine panic by default diff --git a/vendor/github.com/modern-go/reflect2/go_above_118.go b/vendor/github.com/modern-go/reflect2/go_above_118.go index 2b4116f6c..05f07835e 100644 --- a/vendor/github.com/modern-go/reflect2/go_above_118.go +++ b/vendor/github.com/modern-go/reflect2/go_above_118.go @@ -1,4 +1,5 @@ -//+build go1.18 +//go:build go1.18 +// +build go1.18 package reflect2 @@ -20,4 +21,4 @@ func (type2 *UnsafeMapType) UnsafeIterate(obj unsafe.Pointer) MapIterator { pKeyRType: type2.pKeyRType, pElemRType: type2.pElemRType, } -} \ No newline at end of file +} diff --git a/vendor/github.com/modern-go/reflect2/go_above_19.go b/vendor/github.com/modern-go/reflect2/go_above_19.go index 974f7685e..03ccb43c6 100644 --- a/vendor/github.com/modern-go/reflect2/go_above_19.go +++ b/vendor/github.com/modern-go/reflect2/go_above_19.go @@ -1,4 +1,5 @@ -//+build go1.9 +//go:build go1.9 +// +build go1.9 package reflect2 diff --git a/vendor/github.com/modern-go/reflect2/go_below_118.go b/vendor/github.com/modern-go/reflect2/go_below_118.go index 00003dbd7..3501097ad 100644 --- a/vendor/github.com/modern-go/reflect2/go_below_118.go +++ b/vendor/github.com/modern-go/reflect2/go_below_118.go @@ -1,4 +1,5 @@ -//+build !go1.18 +//go:build !go1.18 +// +build !go1.18 package reflect2 @@ -18,4 +19,4 @@ func (type2 *UnsafeMapType) UnsafeIterate(obj unsafe.Pointer) MapIterator { pKeyRType: type2.pKeyRType, pElemRType: type2.pElemRType, } -} \ No newline at end of file +} diff --git a/vendor/github.com/modern-go/reflect2/type_map.go b/vendor/github.com/modern-go/reflect2/type_map.go index 4b13c3155..0e2382b80 100644 --- a/vendor/github.com/modern-go/reflect2/type_map.go +++ b/vendor/github.com/modern-go/reflect2/type_map.go @@ -1,3 +1,4 @@ +//go:build !gccgo // +build !gccgo package reflect2 diff --git a/vendor/github.com/pkg/errors/go113.go b/vendor/github.com/pkg/errors/go113.go index be0d10d0c..2c83c7245 100644 --- a/vendor/github.com/pkg/errors/go113.go +++ b/vendor/github.com/pkg/errors/go113.go @@ -1,3 +1,4 @@ +//go:build go1.13 // +build go1.13 package errors diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin.go index 4c81e1bd8..0e4de6eb6 100644 --- a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin // +build darwin package cpu diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin_cgo.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin_cgo.go index 2a7d4a115..a71c7352b 100644 --- a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin_cgo.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin_cgo.go @@ -1,5 +1,5 @@ -// +build darwin -// +build cgo +//go:build darwin && cgo +// +build darwin,cgo package cpu diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin_nocgo.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin_nocgo.go index 3eaaf88f8..e067e99f9 100644 --- a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin_nocgo.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_darwin_nocgo.go @@ -1,5 +1,5 @@ -// +build darwin -// +build !cgo +//go:build darwin && !cgo +// +build darwin,!cgo package cpu diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_fallback.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_fallback.go index d659abe71..331436932 100644 --- a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_fallback.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_fallback.go @@ -1,3 +1,4 @@ +//go:build !darwin && !linux && !freebsd && !openbsd && !solaris && !windows && !dragonfly // +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows,!dragonfly package cpu diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_linux.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_linux.go index bf6cbcfc9..e9789951d 100644 --- a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_linux.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package cpu diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd.go index 8eb28db72..3159d9d03 100644 --- a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_openbsd.go @@ -1,3 +1,4 @@ +//go:build openbsd // +build openbsd package cpu diff --git a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_windows.go b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_windows.go index 8fd62ef55..f2c640a60 100644 --- a/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_windows.go +++ b/vendor/github.com/shirou/gopsutil/v3/cpu/cpu_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package cpu diff --git a/vendor/github.com/shirou/gopsutil/v3/internal/common/common_darwin.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_darwin.go index be46af3d9..3b2b8e0f4 100644 --- a/vendor/github.com/shirou/gopsutil/v3/internal/common/common_darwin.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin // +build darwin package common diff --git a/vendor/github.com/shirou/gopsutil/v3/internal/common/common_freebsd.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_freebsd.go index 85bda0e22..2510f9def 100644 --- a/vendor/github.com/shirou/gopsutil/v3/internal/common/common_freebsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_freebsd.go @@ -1,3 +1,4 @@ +//go:build freebsd || openbsd // +build freebsd openbsd package common diff --git a/vendor/github.com/shirou/gopsutil/v3/internal/common/common_linux.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_linux.go index 734998993..cd5f52353 100644 --- a/vendor/github.com/shirou/gopsutil/v3/internal/common/common_linux.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package common diff --git a/vendor/github.com/shirou/gopsutil/v3/internal/common/common_openbsd.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_openbsd.go index ba73a7eb5..cbd3d28f6 100644 --- a/vendor/github.com/shirou/gopsutil/v3/internal/common/common_openbsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_openbsd.go @@ -1,3 +1,4 @@ +//go:build openbsd // +build openbsd package common diff --git a/vendor/github.com/shirou/gopsutil/v3/internal/common/common_unix.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_unix.go index 9e393bcfa..a02f053e1 100644 --- a/vendor/github.com/shirou/gopsutil/v3/internal/common/common_unix.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_unix.go @@ -1,3 +1,4 @@ +//go:build linux || freebsd || darwin || openbsd // +build linux freebsd darwin openbsd package common diff --git a/vendor/github.com/shirou/gopsutil/v3/internal/common/common_windows.go b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_windows.go index 2471bae1f..6a1102b4b 100644 --- a/vendor/github.com/shirou/gopsutil/v3/internal/common/common_windows.go +++ b/vendor/github.com/shirou/gopsutil/v3/internal/common/common_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package common diff --git a/vendor/github.com/shirou/gopsutil/v3/mem/mem.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem.go index 08323f113..a721513c5 100644 --- a/vendor/github.com/shirou/gopsutil/v3/mem/mem.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem.go @@ -91,7 +91,7 @@ type SwapMemoryStat struct { // Linux specific numbers // https://www.kernel.org/doc/Documentation/cgroup-v2.txt - PgMajFault uint64 `json:"pgMajFault"` + PgMajFault uint64 `json:"pgMajFault"` } func (m VirtualMemoryStat) String() string { diff --git a/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin.go index fac748151..ec2f58236 100644 --- a/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin // +build darwin package mem diff --git a/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin_cgo.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin_cgo.go index 389f8cdf9..82c38245b 100644 --- a/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin_cgo.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin_cgo.go @@ -1,5 +1,5 @@ -// +build darwin -// +build cgo +//go:build darwin && cgo +// +build darwin,cgo package mem diff --git a/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin_nocgo.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin_nocgo.go index dd7c2e600..be926f291 100644 --- a/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin_nocgo.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_darwin_nocgo.go @@ -1,5 +1,5 @@ -// +build darwin -// +build !cgo +//go:build darwin && !cgo +// +build darwin,!cgo package mem diff --git a/vendor/github.com/shirou/gopsutil/v3/mem/mem_fallback.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_fallback.go index ada031902..1ac7b3ce7 100644 --- a/vendor/github.com/shirou/gopsutil/v3/mem/mem_fallback.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_fallback.go @@ -1,3 +1,4 @@ +//go:build !darwin && !linux && !freebsd && !openbsd && !solaris && !windows // +build !darwin,!linux,!freebsd,!openbsd,!solaris,!windows package mem diff --git a/vendor/github.com/shirou/gopsutil/v3/mem/mem_freebsd.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_freebsd.go index ad592136b..44543ef74 100644 --- a/vendor/github.com/shirou/gopsutil/v3/mem/mem_freebsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_freebsd.go @@ -1,3 +1,4 @@ +//go:build freebsd // +build freebsd package mem diff --git a/vendor/github.com/shirou/gopsutil/v3/mem/mem_linux.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_linux.go index dea5f9052..b40089798 100644 --- a/vendor/github.com/shirou/gopsutil/v3/mem/mem_linux.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package mem diff --git a/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd.go index 9dc3af1f2..4d9b6cce3 100644 --- a/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd.go @@ -1,3 +1,4 @@ +//go:build openbsd // +build openbsd package mem diff --git a/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_386.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_386.go index aacd4f61e..de2b26ca4 100644 --- a/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_386.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_386.go @@ -1,5 +1,6 @@ -// +build openbsd -// +build 386 +//go:build openbsd && 386 +// +build openbsd,386 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs mem/types_openbsd.go diff --git a/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_arm64.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_arm64.go index ad48fc30f..3661b16fb 100644 --- a/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_arm64.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_openbsd_arm64.go @@ -1,5 +1,6 @@ -// +build openbsd -// +build arm64 +//go:build openbsd && arm64 +// +build openbsd,arm64 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs mem/types_openbsd.go diff --git a/vendor/github.com/shirou/gopsutil/v3/mem/mem_windows.go b/vendor/github.com/shirou/gopsutil/v3/mem/mem_windows.go index 8e73433cd..f35258495 100644 --- a/vendor/github.com/shirou/gopsutil/v3/mem/mem_windows.go +++ b/vendor/github.com/shirou/gopsutil/v3/mem/mem_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package mem diff --git a/vendor/github.com/shirou/gopsutil/v3/net/net_aix.go b/vendor/github.com/shirou/gopsutil/v3/net/net_aix.go index e954d56b2..22a16da6c 100644 --- a/vendor/github.com/shirou/gopsutil/v3/net/net_aix.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_aix.go @@ -1,3 +1,4 @@ +//go:build aix // +build aix package net diff --git a/vendor/github.com/shirou/gopsutil/v3/net/net_darwin.go b/vendor/github.com/shirou/gopsutil/v3/net/net_darwin.go index 2327031dd..9badcf6ac 100644 --- a/vendor/github.com/shirou/gopsutil/v3/net/net_darwin.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin // +build darwin package net @@ -6,11 +7,12 @@ import ( "context" "errors" "fmt" - "github.com/shirou/gopsutil/v3/internal/common" "os/exec" "regexp" "strconv" "strings" + + "github.com/shirou/gopsutil/v3/internal/common" ) var ( diff --git a/vendor/github.com/shirou/gopsutil/v3/net/net_fallback.go b/vendor/github.com/shirou/gopsutil/v3/net/net_fallback.go index 6220e8340..58325f655 100644 --- a/vendor/github.com/shirou/gopsutil/v3/net/net_fallback.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_fallback.go @@ -1,3 +1,4 @@ +//go:build !aix && !darwin && !linux && !freebsd && !openbsd && !windows // +build !aix,!darwin,!linux,!freebsd,!openbsd,!windows package net diff --git a/vendor/github.com/shirou/gopsutil/v3/net/net_freebsd.go b/vendor/github.com/shirou/gopsutil/v3/net/net_freebsd.go index 739f8cc68..0a30423de 100644 --- a/vendor/github.com/shirou/gopsutil/v3/net/net_freebsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_freebsd.go @@ -1,3 +1,4 @@ +//go:build freebsd // +build freebsd package net diff --git a/vendor/github.com/shirou/gopsutil/v3/net/net_linux.go b/vendor/github.com/shirou/gopsutil/v3/net/net_linux.go index 19836ca78..e210b2eaa 100644 --- a/vendor/github.com/shirou/gopsutil/v3/net/net_linux.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package net diff --git a/vendor/github.com/shirou/gopsutil/v3/net/net_openbsd.go b/vendor/github.com/shirou/gopsutil/v3/net/net_openbsd.go index 4e09a66d0..3d7edf7a1 100644 --- a/vendor/github.com/shirou/gopsutil/v3/net/net_openbsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_openbsd.go @@ -1,3 +1,4 @@ +//go:build openbsd // +build openbsd package net diff --git a/vendor/github.com/shirou/gopsutil/v3/net/net_unix.go b/vendor/github.com/shirou/gopsutil/v3/net/net_unix.go index 924cfd115..0edee6fd6 100644 --- a/vendor/github.com/shirou/gopsutil/v3/net/net_unix.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_unix.go @@ -1,3 +1,4 @@ +//go:build freebsd || darwin // +build freebsd darwin package net diff --git a/vendor/github.com/shirou/gopsutil/v3/net/net_windows.go b/vendor/github.com/shirou/gopsutil/v3/net/net_windows.go index 691d01914..80a6730fd 100644 --- a/vendor/github.com/shirou/gopsutil/v3/net/net_windows.go +++ b/vendor/github.com/shirou/gopsutil/v3/net/net_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package net @@ -333,7 +334,6 @@ func ConntrackStatsWithContext(ctx context.Context, percpu bool) ([]ConntrackSta return nil, common.ErrNotImplementedError } - // NetProtoCounters returns network statistics for the entire system // If protocols is empty then all protocols are returned, otherwise // just the protocols in the list are returned. diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_bsd.go b/vendor/github.com/shirou/gopsutil/v3/process/process_bsd.go index da90e2070..adaa34028 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_bsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_bsd.go @@ -1,3 +1,4 @@ +//go:build darwin || freebsd || openbsd // +build darwin freebsd openbsd package process @@ -73,4 +74,3 @@ func parseKinfoProc(buf []byte) (KinfoProc, error) { err := common.Read(br, binary.LittleEndian, &k) return k, err } - diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_darwin.go b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin.go index 2b2b24297..e6d356dfc 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_darwin.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin.go @@ -1,3 +1,4 @@ +//go:build darwin // +build darwin package process diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_arm64.go b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_arm64.go index c0063e4e1..9696322ff 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_arm64.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_arm64.go @@ -1,5 +1,6 @@ -// +build darwin -// +build arm64 +//go:build darwin && arm64 +// +build darwin,arm64 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs process/types_darwin.go diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_cgo.go b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_cgo.go index a80817755..4033c282f 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_cgo.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_cgo.go @@ -1,5 +1,5 @@ -// +build darwin -// +build cgo +//go:build darwin && cgo +// +build darwin,cgo package process diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_nocgo.go b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_nocgo.go index 3583e1987..94f12ced8 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_nocgo.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_darwin_nocgo.go @@ -1,5 +1,5 @@ -// +build darwin -// +build !cgo +//go:build darwin && !cgo +// +build darwin,!cgo package process diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_fallback.go b/vendor/github.com/shirou/gopsutil/v3/process/process_fallback.go index 317148e7c..1baefab20 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_fallback.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_fallback.go @@ -1,3 +1,4 @@ +//go:build !darwin && !linux && !freebsd && !openbsd && !windows // +build !darwin,!linux,!freebsd,!openbsd,!windows package process diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd.go b/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd.go index 431a673df..5e47d569d 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd.go @@ -1,3 +1,4 @@ +//go:build freebsd // +build freebsd package process diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd_arm64.go b/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd_arm64.go index 99781d1a2..effd470a0 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd_arm64.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_freebsd_arm64.go @@ -1,201 +1,202 @@ -// +build freebsd -// +build arm64 +//go:build freebsd && arm64 +// +build freebsd,arm64 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs process/types_freebsd.go package process const ( - CTLKern = 1 - KernProc = 14 - KernProcPID = 1 - KernProcProc = 8 - KernProcPathname = 12 - KernProcArgs = 7 + CTLKern = 1 + KernProc = 14 + KernProcPID = 1 + KernProcProc = 8 + KernProcPathname = 12 + KernProcArgs = 7 ) const ( - sizeofPtr = 0x8 - sizeofShort = 0x2 - sizeofInt = 0x4 - sizeofLong = 0x8 - sizeofLongLong = 0x8 + sizeofPtr = 0x8 + sizeofShort = 0x2 + sizeofInt = 0x4 + sizeofLong = 0x8 + sizeofLongLong = 0x8 ) const ( - sizeOfKinfoVmentry = 0x488 - sizeOfKinfoProc = 0x440 + sizeOfKinfoVmentry = 0x488 + sizeOfKinfoProc = 0x440 ) const ( - SIDL = 1 - SRUN = 2 - SSLEEP = 3 - SSTOP = 4 - SZOMB = 5 - SWAIT = 6 - SLOCK = 7 + SIDL = 1 + SRUN = 2 + SSLEEP = 3 + SSTOP = 4 + SZOMB = 5 + SWAIT = 6 + SLOCK = 7 ) type ( - _C_short int16 - _C_int int32 - _C_long int64 - _C_long_long int64 + _C_short int16 + _C_int int32 + _C_long int64 + _C_long_long int64 ) type Timespec struct { - Sec int64 - Nsec int64 + Sec int64 + Nsec int64 } type Timeval struct { - Sec int64 - Usec int64 + Sec int64 + Usec int64 } type Rusage struct { - Utime Timeval - Stime Timeval - Maxrss int64 - Ixrss int64 - Idrss int64 - Isrss int64 - Minflt int64 - Majflt int64 - Nswap int64 - Inblock int64 - Oublock int64 - Msgsnd int64 - Msgrcv int64 - Nsignals int64 - Nvcsw int64 - Nivcsw int64 + Utime Timeval + Stime Timeval + Maxrss int64 + Ixrss int64 + Idrss int64 + Isrss int64 + Minflt int64 + Majflt int64 + Nswap int64 + Inblock int64 + Oublock int64 + Msgsnd int64 + Msgrcv int64 + Nsignals int64 + Nvcsw int64 + Nivcsw int64 } type Rlimit struct { - Cur int64 - Max int64 + Cur int64 + Max int64 } type KinfoProc struct { - Structsize int32 - Layout int32 - Args *int64 /* pargs */ - Paddr *int64 /* proc */ - Addr *int64 /* user */ - Tracep *int64 /* vnode */ - Textvp *int64 /* vnode */ - Fd *int64 /* filedesc */ - Vmspace *int64 /* vmspace */ - Wchan *byte - Pid int32 - Ppid int32 - Pgid int32 - Tpgid int32 - Sid int32 - Tsid int32 - Jobc int16 - Spare_short1 int16 - Tdev_freebsd11 uint32 - Siglist [16]byte /* sigset */ - Sigmask [16]byte /* sigset */ - Sigignore [16]byte /* sigset */ - Sigcatch [16]byte /* sigset */ - Uid uint32 - Ruid uint32 - Svuid uint32 - Rgid uint32 - Svgid uint32 - Ngroups int16 - Spare_short2 int16 - Groups [16]uint32 - Size uint64 - Rssize int64 - Swrss int64 - Tsize int64 - Dsize int64 - Ssize int64 - Xstat uint16 - Acflag uint16 - Pctcpu uint32 - Estcpu uint32 - Slptime uint32 - Swtime uint32 - Cow uint32 - Runtime uint64 - Start Timeval - Childtime Timeval - Flag int64 - Kiflag int64 - Traceflag int32 - Stat uint8 - Nice int8 - Lock uint8 - Rqindex uint8 - Oncpu_old uint8 - Lastcpu_old uint8 - Tdname [17]uint8 - Wmesg [9]uint8 - Login [18]uint8 - Lockname [9]uint8 - Comm [20]int8 - Emul [17]uint8 - Loginclass [18]uint8 - Moretdname [4]uint8 - Sparestrings [46]uint8 - Spareints [2]int32 - Tdev uint64 - Oncpu int32 - Lastcpu int32 - Tracer int32 - Flag2 int32 - Fibnum int32 - Cr_flags uint32 - Jid int32 - Numthreads int32 - Tid int32 - Pri Priority - Rusage Rusage - Rusage_ch Rusage - Pcb *int64 /* pcb */ - Kstack *byte - Udata *byte - Tdaddr *int64 /* thread */ - Spareptrs [6]*byte - Sparelongs [12]int64 - Sflag int64 - Tdflags int64 + Structsize int32 + Layout int32 + Args *int64 /* pargs */ + Paddr *int64 /* proc */ + Addr *int64 /* user */ + Tracep *int64 /* vnode */ + Textvp *int64 /* vnode */ + Fd *int64 /* filedesc */ + Vmspace *int64 /* vmspace */ + Wchan *byte + Pid int32 + Ppid int32 + Pgid int32 + Tpgid int32 + Sid int32 + Tsid int32 + Jobc int16 + Spare_short1 int16 + Tdev_freebsd11 uint32 + Siglist [16]byte /* sigset */ + Sigmask [16]byte /* sigset */ + Sigignore [16]byte /* sigset */ + Sigcatch [16]byte /* sigset */ + Uid uint32 + Ruid uint32 + Svuid uint32 + Rgid uint32 + Svgid uint32 + Ngroups int16 + Spare_short2 int16 + Groups [16]uint32 + Size uint64 + Rssize int64 + Swrss int64 + Tsize int64 + Dsize int64 + Ssize int64 + Xstat uint16 + Acflag uint16 + Pctcpu uint32 + Estcpu uint32 + Slptime uint32 + Swtime uint32 + Cow uint32 + Runtime uint64 + Start Timeval + Childtime Timeval + Flag int64 + Kiflag int64 + Traceflag int32 + Stat uint8 + Nice int8 + Lock uint8 + Rqindex uint8 + Oncpu_old uint8 + Lastcpu_old uint8 + Tdname [17]uint8 + Wmesg [9]uint8 + Login [18]uint8 + Lockname [9]uint8 + Comm [20]int8 + Emul [17]uint8 + Loginclass [18]uint8 + Moretdname [4]uint8 + Sparestrings [46]uint8 + Spareints [2]int32 + Tdev uint64 + Oncpu int32 + Lastcpu int32 + Tracer int32 + Flag2 int32 + Fibnum int32 + Cr_flags uint32 + Jid int32 + Numthreads int32 + Tid int32 + Pri Priority + Rusage Rusage + Rusage_ch Rusage + Pcb *int64 /* pcb */ + Kstack *byte + Udata *byte + Tdaddr *int64 /* thread */ + Spareptrs [6]*byte + Sparelongs [12]int64 + Sflag int64 + Tdflags int64 } type Priority struct { - Class uint8 - Level uint8 - Native uint8 - User uint8 + Class uint8 + Level uint8 + Native uint8 + User uint8 } type KinfoVmentry struct { - Structsize int32 - Type int32 - Start uint64 - End uint64 - Offset uint64 - Vn_fileid uint64 - Vn_fsid_freebsd11 uint32 - Flags int32 - Resident int32 - Private_resident int32 - Protection int32 - Ref_count int32 - Shadow_count int32 - Vn_type int32 - Vn_size uint64 - Vn_rdev_freebsd11 uint32 - Vn_mode uint16 - Status uint16 - Vn_fsid uint64 - Vn_rdev uint64 - X_kve_ispare [8]int32 - Path [1024]uint8 + Structsize int32 + Type int32 + Start uint64 + End uint64 + Offset uint64 + Vn_fileid uint64 + Vn_fsid_freebsd11 uint32 + Flags int32 + Resident int32 + Private_resident int32 + Protection int32 + Ref_count int32 + Shadow_count int32 + Vn_type int32 + Vn_size uint64 + Vn_rdev_freebsd11 uint32 + Vn_mode uint16 + Status uint16 + Vn_fsid uint64 + Vn_rdev uint64 + X_kve_ispare [8]int32 + Path [1024]uint8 } diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_linux.go b/vendor/github.com/shirou/gopsutil/v3/process/process_linux.go index 7a5e64391..3f51ac32d 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_linux.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_linux.go @@ -1,3 +1,4 @@ +//go:build linux // +build linux package process diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd.go b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd.go index 7325f093e..dc3abcdf2 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd.go @@ -1,3 +1,4 @@ +//go:build openbsd // +build openbsd package process diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_386.go b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_386.go index b89fb8dc2..f4ed02491 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_386.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_386.go @@ -1,5 +1,6 @@ -// +build openbsd -// +build 386 +//go:build openbsd && 386 +// +build openbsd,386 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs process/types_openbsd.go diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_arm64.go b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_arm64.go index 2d97fbc5c..a3291b8ca 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_arm64.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_openbsd_arm64.go @@ -1,5 +1,6 @@ -// +build openbsd -// +build arm64 +//go:build openbsd && arm64 +// +build openbsd,arm64 + // Code generated by cmd/cgo -godefs; DO NOT EDIT. // cgo -godefs process/types_openbsd.go diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_posix.go b/vendor/github.com/shirou/gopsutil/v3/process/process_posix.go index 130788fec..264475fb6 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_posix.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_posix.go @@ -1,3 +1,4 @@ +//go:build linux || freebsd || openbsd || darwin // +build linux freebsd openbsd darwin package process diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_windows.go b/vendor/github.com/shirou/gopsutil/v3/process/process_windows.go index f5d4402f8..22466a03a 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_windows.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_windows.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package process diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_windows_386.go b/vendor/github.com/shirou/gopsutil/v3/process/process_windows_386.go index f8a78ba7c..41b211e8c 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_windows_386.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_windows_386.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package process @@ -84,8 +85,8 @@ func readProcessMemory(h syscall.Handle, is32BitProcess bool, address uint64, si ret, _, _ := common.ProcNtWow64ReadVirtualMemory64.Call( uintptr(h), - uintptr(address & 0xFFFFFFFF), //the call expects a 64-bit value - uintptr(address >> 32), + uintptr(address&0xFFFFFFFF), //the call expects a 64-bit value + uintptr(address>>32), uintptr(unsafe.Pointer(&buffer[0])), uintptr(size), //the call expects a 64-bit value uintptr(0), //but size is 32-bit so pass zero as the high dword diff --git a/vendor/github.com/shirou/gopsutil/v3/process/process_windows_amd64.go b/vendor/github.com/shirou/gopsutil/v3/process/process_windows_amd64.go index 4191dd9bc..e73c772bc 100644 --- a/vendor/github.com/shirou/gopsutil/v3/process/process_windows_amd64.go +++ b/vendor/github.com/shirou/gopsutil/v3/process/process_windows_amd64.go @@ -1,3 +1,4 @@ +//go:build windows // +build windows package process diff --git a/vendor/github.com/sirupsen/logrus/hooks/syslog/syslog.go b/vendor/github.com/sirupsen/logrus/hooks/syslog/syslog.go index 02b8df380..0f7d15715 100644 --- a/vendor/github.com/sirupsen/logrus/hooks/syslog/syslog.go +++ b/vendor/github.com/sirupsen/logrus/hooks/syslog/syslog.go @@ -1,3 +1,4 @@ +//go:build !windows && !nacl && !plan9 // +build !windows,!nacl,!plan9 package syslog diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go b/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go index 2403de981..45de3e2b6 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go @@ -1,3 +1,4 @@ +//go:build appengine // +build appengine package logrus diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go index 499789984..e3fa38b71 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go @@ -1,3 +1,4 @@ +//go:build (darwin || dragonfly || freebsd || netbsd || openbsd) && !js // +build darwin dragonfly freebsd netbsd openbsd // +build !js diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_js.go b/vendor/github.com/sirupsen/logrus/terminal_check_js.go index ebdae3ec6..9e951f1b4 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_js.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_js.go @@ -1,3 +1,4 @@ +//go:build js // +build js package logrus diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go b/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go index 97af92c68..04232da19 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go @@ -1,3 +1,4 @@ +//go:build js || nacl || plan9 // +build js nacl plan9 package logrus diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go b/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go index 3293fb3ca..1b4a99e32 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go @@ -1,3 +1,4 @@ +//go:build !appengine && !js && !windows && !nacl && !plan9 // +build !appengine,!js,!windows,!nacl,!plan9 package logrus diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_unix.go b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go index 04748b851..f3154b17f 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_unix.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go @@ -1,3 +1,4 @@ +//go:build (linux || aix || zos) && !js // +build linux aix zos // +build !js diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_windows.go b/vendor/github.com/sirupsen/logrus/terminal_check_windows.go index 2879eb50e..893c62410 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_windows.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_windows.go @@ -1,3 +1,4 @@ +//go:build !appengine && !js && windows // +build !appengine,!js,windows package logrus diff --git a/vendor/github.com/skycoin/dmsg/internal/servermetrics/victoria_metrics.go b/vendor/github.com/skycoin/dmsg/internal/servermetrics/victoria_metrics.go index 1ba40bfb6..0de4a7763 100644 --- a/vendor/github.com/skycoin/dmsg/internal/servermetrics/victoria_metrics.go +++ b/vendor/github.com/skycoin/dmsg/internal/servermetrics/victoria_metrics.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/VictoriaMetrics/metrics" + "github.com/skycoin/skywire-utilities/pkg/metricsutil" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/disc/client.go b/vendor/github.com/skycoin/dmsg/pkg/disc/client.go index 709dfca1b..c3483676a 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/disc/client.go +++ b/vendor/github.com/skycoin/dmsg/pkg/disc/client.go @@ -11,6 +11,7 @@ import ( "time" jsoniter "github.com/json-iterator/go" + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsg/client_session.go b/vendor/github.com/skycoin/dmsg/pkg/dmsg/client_session.go index b6635bd26..f0e108642 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsg/client_session.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsg/client_session.go @@ -5,9 +5,10 @@ import ( "net" "time" + "github.com/skycoin/yamux" + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/netutil" - "github.com/skycoin/yamux" ) // ClientSession represents a session from the perspective of a dmsg client. diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsg/entity_common.go b/vendor/github.com/skycoin/dmsg/pkg/dmsg/entity_common.go index eb8d9f089..4c3f741f5 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsg/entity_common.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsg/entity_common.go @@ -8,6 +8,7 @@ import ( "time" "github.com/sirupsen/logrus" + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" "github.com/skycoin/skywire-utilities/pkg/netutil" diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsg/server.go b/vendor/github.com/skycoin/dmsg/pkg/dmsg/server.go index 168aee9de..7184f1c0b 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsg/server.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsg/server.go @@ -8,6 +8,7 @@ import ( "time" "github.com/sirupsen/logrus" + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" "github.com/skycoin/skywire-utilities/pkg/netutil" diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsg/server_session.go b/vendor/github.com/skycoin/dmsg/pkg/dmsg/server_session.go index 2839875c2..fda8216f6 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsg/server_session.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsg/server_session.go @@ -5,9 +5,10 @@ import ( "net" "github.com/sirupsen/logrus" - "github.com/skycoin/skywire-utilities/pkg/netutil" "github.com/skycoin/yamux" + "github.com/skycoin/skywire-utilities/pkg/netutil" + "github.com/skycoin/dmsg/internal/servermetrics" "github.com/skycoin/dmsg/pkg/noise" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsg/session_common.go b/vendor/github.com/skycoin/dmsg/pkg/dmsg/session_common.go index 74a0c8124..3ef1d3c48 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsg/session_common.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsg/session_common.go @@ -8,9 +8,10 @@ import ( "time" "github.com/sirupsen/logrus" - "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/yamux" + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/dmsg/pkg/noise" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsg/stream.go b/vendor/github.com/skycoin/dmsg/pkg/dmsg/stream.go index 9283ed538..7868f10de 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsg/stream.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsg/stream.go @@ -6,9 +6,10 @@ import ( "time" "github.com/sirupsen/logrus" - "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/yamux" + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/dmsg/pkg/noise" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsgget/dmsgget.go b/vendor/github.com/skycoin/dmsg/pkg/dmsgget/dmsgget.go index 9df685e53..6a45a68d9 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsgget/dmsgget.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsgget/dmsgget.go @@ -14,6 +14,7 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/sirupsen/logrus" + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/cli.go b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/cli.go index eb9ca0225..3497a6e06 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/cli.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/cli.go @@ -12,6 +12,7 @@ import ( "syscall" "github.com/sirupsen/logrus" + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/host.go b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/host.go index 0e88e6449..1720c143c 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/host.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/host.go @@ -12,6 +12,7 @@ import ( "sync/atomic" "github.com/sirupsen/logrus" + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/pty_client.go b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/pty_client.go index cb305c814..6f30521bc 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/pty_client.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/pty_client.go @@ -7,6 +7,7 @@ import ( "sync" "github.com/sirupsen/logrus" + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/ui.go b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/ui.go index 9e97ceda9..aeaad1895 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/ui.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/ui.go @@ -12,9 +12,10 @@ import ( "time" "github.com/sirupsen/logrus" + "nhooyr.io/websocket" + "github.com/skycoin/skywire-utilities/pkg/httputil" "github.com/skycoin/skywire-utilities/pkg/logging" - "nhooyr.io/websocket" ) const ( diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/whitelist.go b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/whitelist.go index a944d23b3..9c03b3863 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/whitelist.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/whitelist.go @@ -12,6 +12,7 @@ import ( "sync" jsoniter "github.com/json-iterator/go" + "github.com/skycoin/skywire-utilities/pkg/cipher" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsgtest/env.go b/vendor/github.com/skycoin/dmsg/pkg/dmsgtest/env.go index 2fe9e5f60..ae22c4c56 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsgtest/env.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsgtest/env.go @@ -7,9 +7,10 @@ import ( "testing" "time" - "github.com/skycoin/skywire-utilities/pkg/cipher" "golang.org/x/net/nettest" + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/dmsg/pkg/disc" dmsg "github.com/skycoin/dmsg/pkg/dmsg" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/noise/net.go b/vendor/github.com/skycoin/dmsg/pkg/noise/net.go index 94ad5e165..60bd26345 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/noise/net.go +++ b/vendor/github.com/skycoin/dmsg/pkg/noise/net.go @@ -8,6 +8,7 @@ import ( "time" "github.com/skycoin/noise" + "github.com/skycoin/skywire-utilities/pkg/cipher" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/noise/noise.go b/vendor/github.com/skycoin/dmsg/pkg/noise/noise.go index aa35d668f..e5ef11d67 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/noise/noise.go +++ b/vendor/github.com/skycoin/dmsg/pkg/noise/noise.go @@ -8,6 +8,7 @@ import ( "fmt" "github.com/skycoin/noise" + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" ) diff --git a/vendor/github.com/skycoin/noise/patterns.go b/vendor/github.com/skycoin/noise/patterns.go index 094cf38bf..7d29d5ba7 100644 --- a/vendor/github.com/skycoin/noise/patterns.go +++ b/vendor/github.com/skycoin/noise/patterns.go @@ -99,7 +99,7 @@ var HandshakeXX = HandshakePattern{ } var HandshakeXXfallback = HandshakePattern{ - Name: "XXfallback", + Name: "XXfallback", ResponderPreMessages: []MessagePattern{MessagePatternE}, Messages: [][]MessagePattern{ {MessagePatternE, MessagePatternDHEE, MessagePatternS, MessagePatternDHSE}, diff --git a/vendor/github.com/skycoin/skycoin/src/cipher/secp256k1-go/secp256k1-go2/secp256k1.go b/vendor/github.com/skycoin/skycoin/src/cipher/secp256k1-go/secp256k1-go2/secp256k1.go index 1cbb4ae33..db8f044ee 100644 --- a/vendor/github.com/skycoin/skycoin/src/cipher/secp256k1-go/secp256k1-go2/secp256k1.go +++ b/vendor/github.com/skycoin/skycoin/src/cipher/secp256k1-go/secp256k1-go2/secp256k1.go @@ -22,8 +22,8 @@ func initConstants() { 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41}) TheCurve.halfOrder.SetBytes([]byte{ - 0X7F, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, - 0X5D, 0X57, 0X6E, 0X73, 0X57, 0XA4, 0X50, 0X1D, 0XDF, 0XE9, 0X2F, 0X46, 0X68, 0X1B, 0X20, 0XA0}) + 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, + 0x5D, 0x57, 0x6E, 0x73, 0x57, 0xA4, 0x50, 0x1D, 0xDF, 0xE9, 0x2F, 0x46, 0x68, 0x1B, 0x20, 0xA0}) TheCurve.p.SetBytes([]byte{ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, diff --git a/vendor/github.com/skycoin/skywire-utilities/pkg/cmdutil/service_flags.go b/vendor/github.com/skycoin/skywire-utilities/pkg/cmdutil/service_flags.go index 77b0a35e5..8d8fcce15 100644 --- a/vendor/github.com/skycoin/skywire-utilities/pkg/cmdutil/service_flags.go +++ b/vendor/github.com/skycoin/skywire-utilities/pkg/cmdutil/service_flags.go @@ -10,8 +10,9 @@ import ( "unicode" jsoniter "github.com/json-iterator/go" - "github.com/skycoin/skywire-utilities/pkg/logging" "github.com/spf13/cobra" + + "github.com/skycoin/skywire-utilities/pkg/logging" ) // Associated errors. diff --git a/vendor/github.com/skycoin/skywire-utilities/pkg/cmdutil/sysloghook_unix.go b/vendor/github.com/skycoin/skywire-utilities/pkg/cmdutil/sysloghook_unix.go index eb2c421b3..0a871cb2b 100644 --- a/vendor/github.com/skycoin/skywire-utilities/pkg/cmdutil/sysloghook_unix.go +++ b/vendor/github.com/skycoin/skywire-utilities/pkg/cmdutil/sysloghook_unix.go @@ -9,6 +9,7 @@ import ( "github.com/sirupsen/logrus" logrussyslog "github.com/sirupsen/logrus/hooks/syslog" + "github.com/skycoin/skywire-utilities/pkg/logging" ) diff --git a/vendor/github.com/skycoin/skywire-utilities/pkg/cmdutil/sysloghook_windows.go b/vendor/github.com/skycoin/skywire-utilities/pkg/cmdutil/sysloghook_windows.go index 60462931d..0236737d0 100644 --- a/vendor/github.com/skycoin/skywire-utilities/pkg/cmdutil/sysloghook_windows.go +++ b/vendor/github.com/skycoin/skywire-utilities/pkg/cmdutil/sysloghook_windows.go @@ -7,6 +7,7 @@ import ( "strings" "github.com/sirupsen/logrus" + "github.com/skycoin/skywire-utilities/pkg/logging" ) diff --git a/vendor/github.com/skycoin/skywire-utilities/pkg/geo/geo.go b/vendor/github.com/skycoin/skywire-utilities/pkg/geo/geo.go index f53ed811f..99b82bb9f 100644 --- a/vendor/github.com/skycoin/skywire-utilities/pkg/geo/geo.go +++ b/vendor/github.com/skycoin/skywire-utilities/pkg/geo/geo.go @@ -9,6 +9,7 @@ import ( "net/http" "github.com/sirupsen/logrus" + "github.com/skycoin/skywire-utilities/pkg/logging" "github.com/skycoin/skywire-utilities/pkg/netutil" diff --git a/vendor/github.com/skycoin/skywire-utilities/pkg/httputil/httputil.go b/vendor/github.com/skycoin/skywire-utilities/pkg/httputil/httputil.go index 3976d3909..c9bdadcb8 100644 --- a/vendor/github.com/skycoin/skywire-utilities/pkg/httputil/httputil.go +++ b/vendor/github.com/skycoin/skywire-utilities/pkg/httputil/httputil.go @@ -10,6 +10,7 @@ import ( "github.com/go-chi/chi/v5/middleware" jsoniter "github.com/json-iterator/go" "github.com/sirupsen/logrus" + "github.com/skycoin/skywire-utilities/pkg/logging" ) diff --git a/vendor/github.com/songgao/water/params_others.go b/vendor/github.com/songgao/water/params_others.go index c5c4f6e31..e5bb0c9b5 100644 --- a/vendor/github.com/songgao/water/params_others.go +++ b/vendor/github.com/songgao/water/params_others.go @@ -1,3 +1,4 @@ +//go:build !linux && !darwin && !windows // +build !linux,!darwin,!windows package water diff --git a/vendor/github.com/songgao/water/syscalls_darwin_go1.11.go b/vendor/github.com/songgao/water/syscalls_darwin_go1.11.go index b02f734fe..752d7fcea 100644 --- a/vendor/github.com/songgao/water/syscalls_darwin_go1.11.go +++ b/vendor/github.com/songgao/water/syscalls_darwin_go1.11.go @@ -1,3 +1,4 @@ +//go:build darwin && go1.11 // +build darwin,go1.11 package water diff --git a/vendor/github.com/songgao/water/syscalls_darwin_legacy.go b/vendor/github.com/songgao/water/syscalls_darwin_legacy.go index d1745409a..7e80be5bc 100644 --- a/vendor/github.com/songgao/water/syscalls_darwin_legacy.go +++ b/vendor/github.com/songgao/water/syscalls_darwin_legacy.go @@ -1,3 +1,4 @@ +//go:build darwin && !go1.11 // +build darwin,!go1.11 package water diff --git a/vendor/github.com/songgao/water/syscalls_linux_go1.11.go b/vendor/github.com/songgao/water/syscalls_linux_go1.11.go index 90c47a123..780815cb6 100644 --- a/vendor/github.com/songgao/water/syscalls_linux_go1.11.go +++ b/vendor/github.com/songgao/water/syscalls_linux_go1.11.go @@ -1,3 +1,4 @@ +//go:build linux && go1.11 // +build linux,go1.11 package water diff --git a/vendor/github.com/songgao/water/syscalls_linux_legacy.go b/vendor/github.com/songgao/water/syscalls_linux_legacy.go index 6499b379a..8e8b2514e 100644 --- a/vendor/github.com/songgao/water/syscalls_linux_legacy.go +++ b/vendor/github.com/songgao/water/syscalls_linux_legacy.go @@ -1,3 +1,4 @@ +//go:build linux && !go1.11 // +build linux,!go1.11 package water diff --git a/vendor/github.com/songgao/water/syscalls_other.go b/vendor/github.com/songgao/water/syscalls_other.go index c5ed1b371..50d72dbf1 100644 --- a/vendor/github.com/songgao/water/syscalls_other.go +++ b/vendor/github.com/songgao/water/syscalls_other.go @@ -1,3 +1,4 @@ +//go:build !linux && !darwin && !windows // +build !linux,!darwin,!windows package water diff --git a/vendor/github.com/stretchr/testify/require/require.go b/vendor/github.com/stretchr/testify/require/require.go index 51820df2e..2900e9eb3 100644 --- a/vendor/github.com/stretchr/testify/require/require.go +++ b/vendor/github.com/stretchr/testify/require/require.go @@ -6,10 +6,11 @@ package require import ( - assert "github.com/stretchr/testify/assert" http "net/http" url "net/url" time "time" + + assert "github.com/stretchr/testify/assert" ) // Condition uses a Comparison to assert a complex condition. diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go b/vendor/github.com/stretchr/testify/require/require_forward.go index ed54a9d83..1b2152b65 100644 --- a/vendor/github.com/stretchr/testify/require/require_forward.go +++ b/vendor/github.com/stretchr/testify/require/require_forward.go @@ -6,10 +6,11 @@ package require import ( - assert "github.com/stretchr/testify/assert" http "net/http" url "net/url" time "time" + + assert "github.com/stretchr/testify/assert" ) // Condition uses a Comparison to assert a complex condition. diff --git a/vendor/github.com/syndtr/gocapability/capability/capability_noop.go b/vendor/github.com/syndtr/gocapability/capability/capability_noop.go index 9bb3070c5..21642feef 100644 --- a/vendor/github.com/syndtr/gocapability/capability/capability_noop.go +++ b/vendor/github.com/syndtr/gocapability/capability/capability_noop.go @@ -4,6 +4,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +//go:build !linux // +build !linux package capability diff --git a/vendor/github.com/templexxx/cpufeat/cpu_x86.go b/vendor/github.com/templexxx/cpufeat/cpu_x86.go index 19d6d22ca..741af3901 100644 --- a/vendor/github.com/templexxx/cpufeat/cpu_x86.go +++ b/vendor/github.com/templexxx/cpufeat/cpu_x86.go @@ -2,6 +2,7 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. +//go:build 386 || amd64 || amd64p32 // +build 386 amd64 amd64p32 package cpufeat diff --git a/vendor/github.com/templexxx/xor/xor_other.go b/vendor/github.com/templexxx/xor/xor_other.go index 4aa2967c4..5c39ea450 100644 --- a/vendor/github.com/templexxx/xor/xor_other.go +++ b/vendor/github.com/templexxx/xor/xor_other.go @@ -1,3 +1,4 @@ +//go:build !amd64 || noasm // +build !amd64 noasm package xor diff --git a/vendor/github.com/tjfoc/gmsm/sm4/sm4.go b/vendor/github.com/tjfoc/gmsm/sm4/sm4.go index a87484085..418128459 100644 --- a/vendor/github.com/tjfoc/gmsm/sm4/sm4.go +++ b/vendor/github.com/tjfoc/gmsm/sm4/sm4.go @@ -248,14 +248,10 @@ func (c *Sm4Cipher) Encrypt(dst, src []byte) { cryptBlock(c.subkeys, c.block1, c.block2, dst, src, false) } - - func (c *Sm4Cipher) Decrypt(dst, src []byte) { cryptBlock(c.subkeys, c.block1, c.block2, dst, src, true) } - - func xor(in, iv []byte) (out []byte) { if len(in) != len(iv) { return nil diff --git a/vendor/github.com/tjfoc/gmsm/sm4/sm4_gcm.go b/vendor/github.com/tjfoc/gmsm/sm4/sm4_gcm.go index 40b73f8d1..531999da1 100644 --- a/vendor/github.com/tjfoc/gmsm/sm4/sm4_gcm.go +++ b/vendor/github.com/tjfoc/gmsm/sm4/sm4_gcm.go @@ -22,34 +22,34 @@ import ( ) //Paper: The Galois/Counter Mode of Operation (GCM) David A. Mcgrew,John Viega .2004. -func Sm4GCM(key []byte, IV ,in, A []byte, mode bool) ([]byte, []byte, error) { +func Sm4GCM(key []byte, IV, in, A []byte, mode bool) ([]byte, []byte, error) { if len(key) != BlockSize { - return nil,nil, errors.New("SM4: invalid key size " + strconv.Itoa(len(key))) + return nil, nil, errors.New("SM4: invalid key size " + strconv.Itoa(len(key))) } if mode { - C,T:=GCMEncrypt(key,IV,in,A) - return C,T,nil - }else{ - P,_T:=GCMDecrypt(key,IV,in,A) - return P,_T,nil + C, T := GCMEncrypt(key, IV, in, A) + return C, T, nil + } else { + P, _T := GCMDecrypt(key, IV, in, A) + return P, _T, nil } } -func GetH(key []byte) (H []byte){ - c,err := NewCipher(key) +func GetH(key []byte) (H []byte) { + c, err := NewCipher(key) if err != nil { panic(err) } - zores:=make([]byte, BlockSize) - H =make([]byte, BlockSize) - c.Encrypt(H,zores) + zores := make([]byte, BlockSize) + H = make([]byte, BlockSize) + c.Encrypt(H, zores) return H } //ut = a + b -func addition(a ,b []byte) (out []byte){ - Len:=len(a) +func addition(a, b []byte) (out []byte) { + Len := len(a) if Len != len(b) { return nil } @@ -60,273 +60,271 @@ func addition(a ,b []byte) (out []byte){ return out } -func Rightshift(V []byte){ - n:=len(V) - for i:=n-1;i>=0;i-- { - V[i]=V[i]>>1 - if i!=0{ - V[i]=((V[i-1]&0x01)<<7)|V[i] +func Rightshift(V []byte) { + n := len(V) + for i := n - 1; i >= 0; i-- { + V[i] = V[i] >> 1 + if i != 0 { + V[i] = ((V[i-1] & 0x01) << 7) | V[i] } } } -func findYi( Y []byte,index int) int{ +func findYi(Y []byte, index int) int { var temp byte - temp=Y[index/8] - temp=temp>>(7-index%8) - if temp & 0x01 == 1{ + temp = Y[index/8] + temp = temp >> (7 - index%8) + if temp&0x01 == 1 { return 1 - }else{ + } else { return 0 } } +func multiplication(X, Y []byte) (Z []byte) { -func multiplication(X,Y []byte) (Z []byte){ - - R:=make([]byte,BlockSize) - R[0]=0xe1 - Z=make([]byte,BlockSize) - V:=make([]byte,BlockSize) - copy(V,X) - for i:=0;i<=127;i++{ - if findYi(Y,i)==1{ - Z=addition(Z,V) + R := make([]byte, BlockSize) + R[0] = 0xe1 + Z = make([]byte, BlockSize) + V := make([]byte, BlockSize) + copy(V, X) + for i := 0; i <= 127; i++ { + if findYi(Y, i) == 1 { + Z = addition(Z, V) } - if V[BlockSize-1]&0x01==0{ + if V[BlockSize-1]&0x01 == 0 { Rightshift(V) - }else{ + } else { Rightshift(V) - V=addition(V,R) + V = addition(V, R) } } return Z } -func GHASH(H []byte,A []byte,C []byte) (X[]byte){ - - calculm_v:=func(m ,v int) (int,int) { - if(m==0 && v!=0){ - m=1 - v=v*8 - }else if(m!=0 && v==0) { - v=BlockSize*8 - }else if(m!=0 && v!=0){ - m=m+1 - v=v*8 - }else { //m==0 && v==0 - m=1 - v=0 +func GHASH(H []byte, A []byte, C []byte) (X []byte) { + + calculm_v := func(m, v int) (int, int) { + if m == 0 && v != 0 { + m = 1 + v = v * 8 + } else if m != 0 && v == 0 { + v = BlockSize * 8 + } else if m != 0 && v != 0 { + m = m + 1 + v = v * 8 + } else { //m==0 && v==0 + m = 1 + v = 0 } - return m,v + return m, v } - m:=len(A)/BlockSize - v:=len(A)%BlockSize - m,v=calculm_v(m,v) + m := len(A) / BlockSize + v := len(A) % BlockSize + m, v = calculm_v(m, v) - n:=len(C)/BlockSize - u:=(len(C)%BlockSize) - n,u=calculm_v(n,u) + n := len(C) / BlockSize + u := (len(C) % BlockSize) + n, u = calculm_v(n, u) //i=0 - X=make([]byte,BlockSize*(m+n+2)) //X0 = 0 - for i:=0;im-1 对于数组来说是 0-->m-2 + for i := 1; i <= m-1; i++ { + copy(X[i*BlockSize:i*BlockSize+BlockSize], multiplication(addition(X[(i-1)*BlockSize:(i-1)*BlockSize+BlockSize], A[(i-1)*BlockSize:(i-1)*BlockSize+BlockSize]), H)) //A 1-->m-1 对于数组来说是 0-->m-2 } //i=m - zeros:=make([]byte,(128-v)/8) - Am:=make([]byte,v/8) - copy(Am[:],A[(m-1)*BlockSize:]) - Am=append(Am,zeros...) - copy(X[m*BlockSize:m*BlockSize+BlockSize],multiplication( addition(X[(m-1)*BlockSize:(m-1)*BlockSize+BlockSize],Am),H)) + zeros := make([]byte, (128-v)/8) + Am := make([]byte, v/8) + copy(Am[:], A[(m-1)*BlockSize:]) + Am = append(Am, zeros...) + copy(X[m*BlockSize:m*BlockSize+BlockSize], multiplication(addition(X[(m-1)*BlockSize:(m-1)*BlockSize+BlockSize], Am), H)) //i=m+1...m+n-1 - for i:=m+1;i<=(m+n-1);i++{ - copy(X[i*BlockSize:i*BlockSize+BlockSize],multiplication( addition(X[(i-1)*BlockSize:(i-1)*BlockSize+BlockSize],C[(i-m-1)*BlockSize:(i-m-1)*BlockSize+BlockSize]),H)) + for i := m + 1; i <= (m + n - 1); i++ { + copy(X[i*BlockSize:i*BlockSize+BlockSize], multiplication(addition(X[(i-1)*BlockSize:(i-1)*BlockSize+BlockSize], C[(i-m-1)*BlockSize:(i-m-1)*BlockSize+BlockSize]), H)) } //i=m+n - zeros =make([]byte,(128-u)/8) - Cn:=make([]byte,u/8) - copy(Cn[:],C[(n-1)*BlockSize:]) - Cn=append(Cn,zeros...) - copy(X[(m+n)*BlockSize:(m+n)*BlockSize+BlockSize],multiplication( addition(X[(m+n-1)*BlockSize:(m+n-1)*BlockSize+BlockSize],Cn),H)) + zeros = make([]byte, (128-u)/8) + Cn := make([]byte, u/8) + copy(Cn[:], C[(n-1)*BlockSize:]) + Cn = append(Cn, zeros...) + copy(X[(m+n)*BlockSize:(m+n)*BlockSize+BlockSize], multiplication(addition(X[(m+n-1)*BlockSize:(m+n-1)*BlockSize+BlockSize], Cn), H)) //i=m+n+1 var lenAB []byte - calculateLenToBytes :=func(len int) []byte{ - data:=make([]byte,8) - data[0]=byte((len>>56)&0xff) - data[1]=byte((len>>48)&0xff) - data[2]=byte((len>>40)&0xff) - data[3]=byte((len>>32)&0xff) - data[4]=byte((len>>24)&0xff) - data[5]=byte((len>>16)&0xff) - data[6]=byte((len>>8)&0xff) - data[7]=byte((len>>0)&0xff) + calculateLenToBytes := func(len int) []byte { + data := make([]byte, 8) + data[0] = byte((len >> 56) & 0xff) + data[1] = byte((len >> 48) & 0xff) + data[2] = byte((len >> 40) & 0xff) + data[3] = byte((len >> 32) & 0xff) + data[4] = byte((len >> 24) & 0xff) + data[5] = byte((len >> 16) & 0xff) + data[6] = byte((len >> 8) & 0xff) + data[7] = byte((len >> 0) & 0xff) return data } - lenAB=append(lenAB,calculateLenToBytes(len(A))...) - lenAB=append(lenAB,calculateLenToBytes(len(C))...) - copy(X[(m+n+1)*BlockSize:(m+n+1)*BlockSize+BlockSize],multiplication(addition(X[(m+n)*BlockSize:(m+n)*BlockSize+BlockSize],lenAB),H)) - return X[(m+n+1)*BlockSize:(m+n+1)*BlockSize+BlockSize] + lenAB = append(lenAB, calculateLenToBytes(len(A))...) + lenAB = append(lenAB, calculateLenToBytes(len(C))...) + copy(X[(m+n+1)*BlockSize:(m+n+1)*BlockSize+BlockSize], multiplication(addition(X[(m+n)*BlockSize:(m+n)*BlockSize+BlockSize], lenAB), H)) + return X[(m+n+1)*BlockSize : (m+n+1)*BlockSize+BlockSize] } - -func GetY0(H,IV []byte) []byte{ +func GetY0(H, IV []byte) []byte { if len(IV)*8 == 96 { - zero31one1:=[]byte{0x00,0x00,0x00,0x01} - IV=append(IV,zero31one1...) + zero31one1 := []byte{0x00, 0x00, 0x00, 0x01} + IV = append(IV, zero31one1...) return IV - }else{ - return GHASH(H,[]byte{},IV) + } else { + return GHASH(H, []byte{}, IV) } } -func incr(n int ,Y_i []byte) (Y_ii []byte) { +func incr(n int, Y_i []byte) (Y_ii []byte) { - Y_ii=make([]byte,BlockSize*n) - copy(Y_ii,Y_i) + Y_ii = make([]byte, BlockSize*n) + copy(Y_ii, Y_i) - addYone:=func(yi,yii []byte){ - copy(yii[:],yi[:]) + addYone := func(yi, yii []byte) { + copy(yii[:], yi[:]) - Len:=len(yi) - var rc byte=0x00 - for i:=Len-1;i>=0;i--{ - if(i==Len-1){ - if(yii[i]<0xff){ - yii[i]=yii[i]+0x01 - rc=0x00 - }else{ - yii[i]=0x00 - rc=0x01 + Len := len(yi) + var rc byte = 0x00 + for i := Len - 1; i >= 0; i-- { + if i == Len-1 { + if yii[i] < 0xff { + yii[i] = yii[i] + 0x01 + rc = 0x00 + } else { + yii[i] = 0x00 + rc = 0x01 } - }else{ - if yii[i]+rc<0xff { - yii[i]=yii[i]+rc - rc=0x00 - }else{ - yii[i]=0x00 - rc=0x01 + } else { + if yii[i]+rc < 0xff { + yii[i] = yii[i] + rc + rc = 0x00 + } else { + yii[i] = 0x00 + rc = 0x01 } } } } - for i:=1;i Date: Tue, 31 Jan 2023 18:17:58 +0100 Subject: [PATCH 23/72] commit --- .../app/chat/commands/add_local_room.go | 4 +- .../app/chat/commands/add_local_server.go | 11 +- .../commands/delete_local_room_by_route.go | 62 ---- .../commands/delete_remote_visor_by_pk.go | 58 ++- ...d_remote_route.go => join_remote_route.go} | 24 +- .../commands/leave_remote_room_by_route.go | 66 ---- .../app/chat/commands/leave_remote_route.go | 83 +++++ .../commands/leave_remote_server_by_route.go | 54 --- .../chat/commands/send_add_room_message.go | 39 ++ .../chat/commands/send_delete_room_message.go | 36 ++ .../app/chat/queries/get_room_by_route.go | 32 +- .../skychat/internal/app/chat/services.go | 36 +- .../internal/app/messenger/messenger.go | 5 +- .../internal/app/notification/notification.go | 25 +- .../internal/app/user/commands/set_info.go | 3 + cmd/apps/skychat/internal/domain/chat/room.go | 30 +- .../skychat/internal/domain/chat/server.go | 52 ++- .../skychat/internal/domain/chat/visor.go | 47 ++- .../skychat/internal/domain/client/client.go | 9 + cmd/apps/skychat/internal/domain/info/info.go | 3 +- .../internal/domain/message/message.go | 175 +++++++-- .../skychat/internal/domain/util/pkroute.go | 1 + .../skychat/internal/inputports/cli/cli.go | 4 - .../internal/inputports/http/chat/handler.go | 267 ++++++-------- .../http/notification.go/handler.go | 10 +- .../internal/inputports/http/server.go | 10 +- .../inputports/http/static/index.html | 2 +- .../internal/inputports/http/static/index.js | 139 +++++--- .../inputports/http/static/stylesheet.css | 2 +- .../messenger/netcon/messenger_service.go | 337 ++++++++++++------ .../netcon/messenger_service_local_server.go | 327 ++++++++++++----- .../messenger/netcon/messenger_service_p2p.go | 131 +++++-- .../netcon/messenger_service_remote_server.go | 104 +++--- .../notification/http/notification_service.go | 10 +- .../storage/memory/user_repo.go | 3 - cmd/apps/skychat/skychat.go | 2 +- 36 files changed, 1380 insertions(+), 823 deletions(-) delete mode 100644 cmd/apps/skychat/internal/app/chat/commands/delete_local_room_by_route.go rename cmd/apps/skychat/internal/app/chat/commands/{add_remote_route.go => join_remote_route.go} (51%) delete mode 100644 cmd/apps/skychat/internal/app/chat/commands/leave_remote_room_by_route.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go delete mode 100644 cmd/apps/skychat/internal/app/chat/commands/leave_remote_server_by_route.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/send_add_room_message.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/send_delete_room_message.go delete mode 100644 cmd/apps/skychat/internal/inputports/cli/cli.go diff --git a/cmd/apps/skychat/internal/app/chat/commands/add_local_room.go b/cmd/apps/skychat/internal/app/chat/commands/add_local_room.go index 6d937913d..3ab231c5b 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/add_local_room.go +++ b/cmd/apps/skychat/internal/app/chat/commands/add_local_room.go @@ -14,7 +14,7 @@ import ( type AddLocalRoomRequest struct { Route util.PKRoute Info info.Info - Type int64 + Type int } // AddLocalRoomRequestHandler struct that allows handling AddLocalRoomRequest @@ -60,7 +60,7 @@ func (h addLocalRoomRequestHandler) Handle(command AddLocalRoomRequest) error { //setup user as peer for room membership p := peer.NewPeer(*usr.GetInfo(), usr.GetInfo().Alias) - //Add user as member + //Add user as member to room err = r.AddMember(*p) if err != nil { return err diff --git a/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go b/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go index 5edbc85be..881c97ad6 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go +++ b/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go @@ -67,9 +67,16 @@ func (h addLocalServerRequestHandler) Handle(command AddLocalServerRequest) erro roomRoute := util.NewLocalRoomRoute(server.PKRoute.Visor, server.PKRoute.Server, roomBoolMap) r := chat.NewLocalRoom(roomRoute, command.Info, chat.DefaultRoomType) - //setup user as peer for room membership + //setup user as peer for memberships p := peer.NewPeer(*usr.GetInfo(), usr.GetInfo().Alias) - //Add user as member + + //Add user as member from server + //TODO: maybe also add user as server admin as we are sending all commands to the local server instance like it is a message from remote to only handle message from one point? + err = server.AddMember(*p) + if err != nil { + return err + } + //Add user as member from room err = r.AddMember(*p) if err != nil { return err diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_local_room_by_route.go b/cmd/apps/skychat/internal/app/chat/commands/delete_local_room_by_route.go deleted file mode 100644 index 025450744..000000000 --- a/cmd/apps/skychat/internal/app/chat/commands/delete_local_room_by_route.go +++ /dev/null @@ -1,62 +0,0 @@ -package commands - -import ( - "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" -) - -// DeleteLocalRoomRequest of DeleteLocalRoomRequestHandler -type DeleteLocalRoomRequest struct { - Route util.PKRoute -} - -// DeleteLocalRoomRequestHandler struct that allows handling DeleteLocalRoomRequest -type DeleteLocalRoomRequestHandler interface { - Handle(command DeleteLocalRoomRequest) error -} - -type deleteLocalRoomRequestHandler struct { - messengerService messenger.Service - visorRepo chat.Repository -} - -// NewDeleteLocalRoomRequestHandler Initializes an AddCommandHandler -func NewDeleteLocalRoomRequestHandler(messengerService messenger.Service, visorRepo chat.Repository) DeleteLocalRoomRequestHandler { - return deleteLocalRoomRequestHandler{messengerService: messengerService, visorRepo: visorRepo} -} - -// Handle Handles the DeleteLocalRoomRequest -func (h deleteLocalRoomRequestHandler) Handle(command DeleteLocalRoomRequest) error { - // Check if visor exists - visor, err := h.visorRepo.GetByPK(command.Route.Visor) - if err != nil { - return err - } - // Check if server exists - server, err := visor.GetServerByPK(command.Route.Server) - if err != nil { - return err - } - // Check if room exists - _, err = server.GetRoomByPK(command.Route.Room) - if err != nil { - return err - } - - // Delete room from server - err = server.DeleteRoom(command.Route.Room) - if err != nil { - return err - } - - //[]: Send 'Room-Deleted-Message' to room members (and to server members if room is public) - - // Update visor, and repository with changed server - err = visor.SetServer(*server) - if err != nil { - return err - } - - return h.visorRepo.Set(*visor) -} diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_remote_visor_by_pk.go b/cmd/apps/skychat/internal/app/chat/commands/delete_remote_visor_by_pk.go index e7e49e2a4..d5421f401 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/delete_remote_visor_by_pk.go +++ b/cmd/apps/skychat/internal/app/chat/commands/delete_remote_visor_by_pk.go @@ -5,8 +5,10 @@ import ( "fmt" "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) // DeleteRemoteVisorRequest Command Model @@ -20,13 +22,14 @@ type DeleteRemoteVisorRequestHandler interface { } type deleteRemoteVisorRequestHandler struct { - cliRepo client.Repository - visorRepo chat.Repository + cliRepo client.Repository + messengerService messenger.Service + visorRepo chat.Repository } // NewDeleteRemoteVisorRequestHandler Handler constructor -func NewDeleteRemoteVisorRequestHandler(cliRepo client.Repository, visorRepo chat.Repository) DeleteRemoteVisorRequestHandler { - return deleteRemoteVisorRequestHandler{cliRepo: cliRepo, visorRepo: visorRepo} +func NewDeleteRemoteVisorRequestHandler(cliRepo client.Repository, visorRepo chat.Repository, messengerService messenger.Service) DeleteRemoteVisorRequestHandler { + return deleteRemoteVisorRequestHandler{cliRepo: cliRepo, visorRepo: visorRepo, messengerService: messengerService} } // Handle Handles the DeleteRemoteVisorRequest request @@ -43,11 +46,48 @@ func (h deleteRemoteVisorRequestHandler) Handle(command DeleteRemoteVisorRequest return err } - //[]: Send 'Delete-Visor-Message' to remote visor so it can be notified about the deletion?? + // Send 'Leave-Visor-Message' to remote visor so it can be notified about the deletion + root := util.NewP2PRoute(pCli.GetAppClient().Config().VisorPK) + dest := util.NewP2PRoute(command.Pk) + err = h.messengerService.SendChatLeaveMessage(dest, root, dest) + if err != nil { + return err + } + + //get connection + conn, err := pCli.GetConnByPK(command.Pk) + if err != nil { + fmt.Printf("Error getting connection") + return err + } + + //close connection + err = conn.Close() + if err != nil { + fmt.Printf("Error closing connection") + return err + } - //close all routes - //TODO:this does not work as expected --> shouldnt only the routes be closed? - pCli.GetAppClient().Close() + //delete connection from client + err = pCli.DeleteConn(command.Pk) + if err != nil { + fmt.Printf("Error deleting connection") + return err + } + + //update client in repository + err = h.cliRepo.SetClient(*pCli) + if err != nil { + fmt.Printf("Error updating client") + return err + } + + //delete visor from visor repository + h.visorRepo.Delete(command.Pk) + if err != nil { + fmt.Printf("Error deleting visor") + return err + } - return h.visorRepo.Delete(command.Pk) + return nil } diff --git a/cmd/apps/skychat/internal/app/chat/commands/add_remote_route.go b/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go similarity index 51% rename from cmd/apps/skychat/internal/app/chat/commands/add_remote_route.go rename to cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go index d00901bc2..4557135f9 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/add_remote_route.go +++ b/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go @@ -9,30 +9,28 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) -// AddRemoteRouteRequest of AddRemoteRouteRequestHandler -type AddRemoteRouteRequest struct { +// JoinRemoteRouteRequest of JoinRemoteRouteRequestHandler +type JoinRemoteRouteRequest struct { Route util.PKRoute } -// AddRemoteRouteRequestHandler struct that allows handling AddRemoteRouteRequest -type AddRemoteRouteRequestHandler interface { - Handle(command AddRemoteRouteRequest) error +// JoinRemoteRouteRequestHandler struct that allows handling JoinRemoteRouteRequest +type JoinRemoteRouteRequestHandler interface { + Handle(command JoinRemoteRouteRequest) error } -type addRemoteRouteRequestHandler struct { +type joinRemoteRouteRequestHandler struct { messengerService messenger.Service visorRepo chat.Repository } -// NewAddRemoteRouteRequestHandler Initializes an AddCommandHandler -func NewAddRemoteRouteRequestHandler(visorRepo chat.Repository, messengerService messenger.Service) AddRemoteRouteRequestHandler { - return addRemoteRouteRequestHandler{visorRepo: visorRepo, messengerService: messengerService} +// NewJoinRemoteRouteRequestHandler Initializes an JoinCommandHandler +func NewJoinRemoteRouteRequestHandler(visorRepo chat.Repository, messengerService messenger.Service) JoinRemoteRouteRequestHandler { + return joinRemoteRouteRequestHandler{visorRepo: visorRepo, messengerService: messengerService} } -// Handle Handles the AddRemoteRouteRequest -func (h addRemoteRouteRequestHandler) Handle(command AddRemoteRouteRequest) error { - fmt.Println("AddRemoteRouteHandler - Request: " + command.Route.String()) - //1. check if the requested route is already in visor repo +// Handle Handles the JoinRemoteRouteRequest +func (h joinRemoteRouteRequestHandler) Handle(command JoinRemoteRouteRequest) error { visor, err := h.visorRepo.GetByPK(command.Route.Visor) if err == nil { server, err := visor.GetServerByPK(command.Route.Server) diff --git a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_room_by_route.go b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_room_by_route.go deleted file mode 100644 index 393ed987d..000000000 --- a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_room_by_route.go +++ /dev/null @@ -1,66 +0,0 @@ -// Package commands contains commands to leave remote room -package commands - -import ( - "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" -) - -// LeaveRemoteRoomRequest Command Model -type LeaveRemoteRoomRequest struct { - Route util.PKRoute -} - -// LeaveRemoteRoomRequestHandler Handler Struct with Dependencies -type LeaveRemoteRoomRequestHandler interface { - Handle(command LeaveRemoteRoomRequest) error -} - -type leaveRemoteRoomRequestHandler struct { - messengerService messenger.Service - visorRepo chat.Repository -} - -// NewLeaveRemoteRoomRequestHandler Handler constructor -func NewLeaveRemoteRoomRequestHandler(messengerService messenger.Service, visorRepo chat.Repository) LeaveRemoteRoomRequestHandler { - return leaveRemoteRoomRequestHandler{messengerService: messengerService, visorRepo: visorRepo} -} - -// Handle Handles the LeaveRemoteRoomRequest request -func (h leaveRemoteRoomRequestHandler) Handle(command LeaveRemoteRoomRequest) error { - // Check if visor exists - visor, err := h.visorRepo.GetByPK(command.Route.Visor) - if err != nil { - return err - } - // Check if server exists - server, err := visor.GetServerByPK(command.Route.Server) - if err != nil { - return err - } - // Check if room exists - _, err = server.GetRoomByPK(command.Route.Room) - if err != nil { - return err - } - - //[]: send 'Leave-Room-Message' to remote server so membership of room can be removed - //?: this command is nearly the same as delete_local_room_by_route.go -> maybe remove one and add this part here with if visorpk=localvisor - //! -> When the 'Leave-Room-Message' does not get recognized from the room, all 'Room-Messages' still get send -> How to solve? - - //?if this is the last Room maybe also leave server? -> and do everything that is done when a server is left - - // Delete room from server - err = server.DeleteRoom(command.Route.Room) - if err != nil { - return err - } - // Update visor, and repository with changed server - err = visor.SetServer(*server) - if err != nil { - return err - } - - return h.visorRepo.Set(*visor) -} diff --git a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go new file mode 100644 index 000000000..048d53520 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go @@ -0,0 +1,83 @@ +// Package commands contains commands to leave remote room +package commands + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// LeaveRemoteRouteRequest Command Model +type LeaveRemoteRouteRequest struct { + Route util.PKRoute +} + +// LeaveRemoteRouteRequestHandler Handler Struct with Dependencies +type LeaveRemoteRouteRequestHandler interface { + Handle(command LeaveRemoteRouteRequest) error +} + +type leaveRemoteRouteRequestHandler struct { + messengerService messenger.Service + visorRepo chat.Repository +} + +// NewLeaveRemoteRouteRequestHandler Handler constructor +func NewLeaveRemoteRouteRequestHandler(messengerService messenger.Service, visorRepo chat.Repository) LeaveRemoteRouteRequestHandler { + return leaveRemoteRouteRequestHandler{messengerService: messengerService, visorRepo: visorRepo} +} + +// Handle Handles the LeaveRemoteRouteRequest request +func (h leaveRemoteRouteRequestHandler) Handle(command LeaveRemoteRouteRequest) error { + // Check if visor exists + visor, err := h.visorRepo.GetByPK(command.Route.Visor) + if err != nil { + return err + } + // Check if server exists + server, err := visor.GetServerByPK(command.Route.Server) + if err != nil { + return err + } + + //leave room if the request server and room are the same + if command.Route.Server == command.Route.Room { + // Check if room exists + _, err = server.GetRoomByPK(command.Route.Room) + if err != nil { + return err + } + + //TODO: Send Leave-Room-Message + + // Delete room from server + err = server.DeleteRoom(command.Route.Room) + if err != nil { + return err + } + + // Update visor with changed server + err = visor.SetServer(*server) + if err != nil { + return err + } + + //TODO:check if this was the last room of the server, if so maybe also leave server + + // Update repository with changed visor + return h.visorRepo.Set(*visor) + } else { + + //TODO: Send Leave-Server-Message + + // Delete server from visor + err = visor.DeleteServer(command.Route.Server) + if err != nil { + return err + } + + // Update repository with changed visor + return h.visorRepo.Set(*visor) + } + +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_server_by_route.go b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_server_by_route.go deleted file mode 100644 index 615da7412..000000000 --- a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_server_by_route.go +++ /dev/null @@ -1,54 +0,0 @@ -// Package commands contains commands to leave remote room -package commands - -import ( - "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" -) - -// LeaveRemoteServerRequest Command Model -type LeaveRemoteServerRequest struct { - Route util.PKRoute -} - -// LeaveRemoteServerRequestHandler Handler Struct with Dependencies -type LeaveRemoteServerRequestHandler interface { - Handle(command LeaveRemoteServerRequest) error -} - -type leaveRemoteServerRequestHandler struct { - messengerService messenger.Service - visorRepo chat.Repository -} - -// NewLeaveRemoteServerRequestHandler Handler constructor -func NewLeaveRemoteServerRequestHandler(messengerService messenger.Service, visorRepo chat.Repository) LeaveRemoteServerRequestHandler { - return leaveRemoteServerRequestHandler{messengerService: messengerService, visorRepo: visorRepo} -} - -// Handle Handles the LeaveRemoteServerRequest request -func (h leaveRemoteServerRequestHandler) Handle(command LeaveRemoteServerRequest) error { - // Check if visor exists - visor, err := h.visorRepo.GetByPK(command.Route.Visor) - if err != nil { - return err - } - // Check if server exists - _, err = visor.GetServerByPK(command.Route.Server) - if err != nil { - return err - } - - //[]: Send 'Leave-Server-Message' to remote server so membership of it can be removed - //? this command is nearly the same as delete_local_server_by_route.go -> maybe remove one and add this part here with if visorpk=localvisor - //! -> When the 'Leave-Server-Message' does not get recognized from the server, all 'Server-Messages' still get send -> How to solve? - - // Delete server from visor - err = visor.DeleteServer(command.Route.Server) - if err != nil { - return err - } - - return h.visorRepo.Set(*visor) -} diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_add_room_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_add_room_message.go new file mode 100644 index 000000000..bedd7866d --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/send_add_room_message.go @@ -0,0 +1,39 @@ +// Package commands contains commands to send text message +package commands + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// SendAddRoomMessageRequest of SendAddRoomMessageRequestHandler +type SendAddRoomMessageRequest struct { + Route util.PKRoute + Info info.Info + Type int +} + +// SendAddRoomMessageRequestHandler struct that allows handling SendAddRoomMessageRequest +type SendAddRoomMessageRequestHandler interface { + Handle(command SendAddRoomMessageRequest) error +} + +type sendAddRoomMessageRequestHandler struct { + messengerService messenger.Service +} + +// NewSendAddRoomMessageRequestHandler Initializes an AddCommandHandler +func NewSendAddRoomMessageRequestHandler(messengerService messenger.Service) SendAddRoomMessageRequestHandler { + return sendAddRoomMessageRequestHandler{messengerService: messengerService} +} + +// Handle Handles the AddCragRequest +func (h sendAddRoomMessageRequestHandler) Handle(command SendAddRoomMessageRequest) error { + err := h.messengerService.SendAddRoomMessage(command.Route, command.Info) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_delete_room_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_delete_room_message.go new file mode 100644 index 000000000..f2e07355f --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/send_delete_room_message.go @@ -0,0 +1,36 @@ +// Package commands contains commands to send text message +package commands + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// SendDeleteRoomMessageRequest of SendDeleteRoomMessageRequestHandler +type SendDeleteRoomMessageRequest struct { + Route util.PKRoute +} + +// SendDeleteRoomMessageRequestHandler struct that allows handling SendDeleteRoomMessageRequest +type SendDeleteRoomMessageRequestHandler interface { + Handle(command SendDeleteRoomMessageRequest) error +} + +type sendDeleteRoomMessageRequestHandler struct { + messengerService messenger.Service +} + +// NewSendDeleteRoomMessageRequestHandler Initializes an AddCommandHandler +func NewSendDeleteRoomMessageRequestHandler(messengerService messenger.Service) SendDeleteRoomMessageRequestHandler { + return sendDeleteRoomMessageRequestHandler{messengerService: messengerService} +} + +// Handle Handles the AddCragRequest +func (h sendDeleteRoomMessageRequestHandler) Handle(command SendDeleteRoomMessageRequest) error { + err := h.messengerService.SendDeleteRoomMessage(command.Route) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go b/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go index 32fbd7ded..98736a258 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go @@ -21,8 +21,8 @@ type GetRoomByRouteResult struct { Info info.Info // P2P: send // Server: only send when room isVisible Msgs []message.Message // P2P: send // Server: only send to members when room isVisible - IsVisible bool //setting to make room visible for all server-members - Type int64 //roomType --> board,chat,voice + IsVisible bool //setting to make room visible for all server-members + Type int //roomType --> board,chat,voice Members map[cipher.PubKey]peer.Peer // all members Mods map[cipher.PubKey]bool // all moderators (can mute and unmute members, can 'delete' messages, can add pks to blacklist) @@ -55,19 +55,29 @@ func (h getRoomByRouteRequestHandler) Handle(query GetRoomByRouteRequest) (GetRo return result, err } - server, err := visor.GetServerByPK(query.Route.Server) + if query.Route.Visor == query.Route.Server { + p2p, err := visor.GetP2P() + if err != nil { + return result, err + } - if err != nil { - return result, err - } + result = GetRoomByRouteResult{PKRoute: p2p.PKRoute, Info: p2p.Info, Msgs: p2p.Msgs, IsVisible: p2p.IsVisible, Type: p2p.Type, Members: p2p.Members, Mods: p2p.Mods, Muted: p2p.Muted, Blacklist: p2p.Blacklist, Whitelist: p2p.Whitelist} - room, err := server.GetRoomByPK(query.Route.Room) + } else { - if err != nil { - return result, err - } + server, err := visor.GetServerByPK(query.Route.Server) + + if err != nil { + return result, err + } - result = GetRoomByRouteResult{PKRoute: room.PKRoute, Info: room.Info, Msgs: room.Msgs, IsVisible: room.IsVisible, Type: room.Type, Members: room.Members, Mods: room.Mods, Muted: room.Muted, Blacklist: server.Blacklist, Whitelist: server.Whitelist} + room, err := server.GetRoomByPK(query.Route.Room) + if err != nil { + return result, err + } + + result = GetRoomByRouteResult{PKRoute: room.PKRoute, Info: room.Info, Msgs: room.Msgs, IsVisible: room.IsVisible, Type: room.Type, Members: room.Members, Mods: room.Mods, Muted: room.Muted, Blacklist: server.Blacklist, Whitelist: server.Whitelist} + } return result, nil } diff --git a/cmd/apps/skychat/internal/app/chat/services.go b/cmd/apps/skychat/internal/app/chat/services.go index e887520a5..741a49241 100644 --- a/cmd/apps/skychat/internal/app/chat/services.go +++ b/cmd/apps/skychat/internal/app/chat/services.go @@ -22,15 +22,15 @@ type Queries struct { // Commands Contains all available command handlers of this app type Commands struct { - AddLocalRoomHandler commands.AddLocalRoomRequestHandler - AddLocalServerHandler commands.AddLocalServerRequestHandler - AddRemoteRouteHandler commands.AddRemoteRouteRequestHandler - DeleteLocalRoomHandler commands.DeleteLocalRoomRequestHandler - DeleteLocalServerHandler commands.DeleteLocalServerRequestHandler - LeaveRemoteRoomHandler commands.LeaveRemoteRoomRequestHandler - LeaveRemoteServerHandler commands.LeaveRemoteServerRequestHandler - DeleteRemoteVisorHandler commands.DeleteRemoteVisorRequestHandler - SendTextMessageHandler commands.SendTextMessageRequestHandler + AddLocalRoomHandler commands.AddLocalRoomRequestHandler + AddLocalServerHandler commands.AddLocalServerRequestHandler + JoinRemoteRouteHandler commands.JoinRemoteRouteRequestHandler + DeleteLocalServerHandler commands.DeleteLocalServerRequestHandler + LeaveRemoteRouteHandler commands.LeaveRemoteRouteRequestHandler + DeleteRemoteVisorHandler commands.DeleteRemoteVisorRequestHandler + SendAddRoomMessageHandler commands.SendAddRoomMessageRequestHandler + SendDeleteRoomMessageHandler commands.SendDeleteRoomMessageRequestHandler + SendTextMessageHandler commands.SendTextMessageRequestHandler } // ChatServices Contains the grouped queries and commands of the app layer @@ -50,15 +50,15 @@ func NewServices(cliRepo client.Repository, visorRepo chat.Repository, userRepo GetAllMessagesFromRoomHandler: queries.NewGetAllMessagesFromRoomRequestHandler(visorRepo), }, Commands: Commands{ - AddLocalRoomHandler: commands.NewAddLocalRoomRequestHandler(visorRepo,userRepo, ns), - AddLocalServerHandler: commands.NewAddLocalServerRequestHandler(visorRepo, userRepo, ns), - AddRemoteRouteHandler: commands.NewAddRemoteRouteRequestHandler(visorRepo, ms), - DeleteLocalRoomHandler: commands.NewDeleteLocalRoomRequestHandler(ms, visorRepo), - DeleteLocalServerHandler: commands.NewDeleteLocalServerRequestHandler(ms, visorRepo), - LeaveRemoteRoomHandler: commands.NewLeaveRemoteRoomRequestHandler(ms, visorRepo), - LeaveRemoteServerHandler: commands.NewLeaveRemoteServerRequestHandler(ms, visorRepo), - DeleteRemoteVisorHandler: commands.NewDeleteRemoteVisorRequestHandler(cliRepo, visorRepo), - SendTextMessageHandler: commands.NewSendTextMessageRequestHandler(ms), + AddLocalRoomHandler: commands.NewAddLocalRoomRequestHandler(visorRepo, userRepo, ns), + AddLocalServerHandler: commands.NewAddLocalServerRequestHandler(visorRepo, userRepo, ns), + JoinRemoteRouteHandler: commands.NewJoinRemoteRouteRequestHandler(visorRepo, ms), + DeleteLocalServerHandler: commands.NewDeleteLocalServerRequestHandler(ms, visorRepo), + LeaveRemoteRouteHandler: commands.NewLeaveRemoteRouteRequestHandler(ms, visorRepo), + DeleteRemoteVisorHandler: commands.NewDeleteRemoteVisorRequestHandler(cliRepo, visorRepo, ms), + SendAddRoomMessageHandler: commands.NewSendAddRoomMessageRequestHandler(ms), + SendDeleteRoomMessageHandler: commands.NewSendDeleteRoomMessageRequestHandler(ms), + SendTextMessageHandler: commands.NewSendTextMessageRequestHandler(ms), }, } } diff --git a/cmd/apps/skychat/internal/app/messenger/messenger.go b/cmd/apps/skychat/internal/app/messenger/messenger.go index 1fa3e976b..f414d3e75 100644 --- a/cmd/apps/skychat/internal/app/messenger/messenger.go +++ b/cmd/apps/skychat/internal/app/messenger/messenger.go @@ -13,5 +13,8 @@ type Service interface { Listen() SendTextMessage(route util.PKRoute, msg []byte) error SendRouteRequestMessage(route util.PKRoute) error - SendInfoMessage(root util.PKRoute, dest util.PKRoute, info info.Info) error + SendInfoMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute, info info.Info) error + SendChatLeaveMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute) error + SendAddRoomMessage(route util.PKRoute, info info.Info) error + SendDeleteRoomMessage(route util.PKRoute) error } diff --git a/cmd/apps/skychat/internal/app/notification/notification.go b/cmd/apps/skychat/internal/app/notification/notification.go index c7b487aec..f293947c7 100644 --- a/cmd/apps/skychat/internal/app/notification/notification.go +++ b/cmd/apps/skychat/internal/app/notification/notification.go @@ -26,18 +26,21 @@ const ( // Notification provides a struct to send messages via the Service type Notification struct { - Type int64 `json:"type"` + Type int `json:"type"` Message string `json:"message"` } // NewMsgNotification notifies the user of a new message func NewMsgNotification(route util.PKRoute, msg message.Message) Notification { - Msg, err := json.Marshal(message.NewJSONMessage(msg)) + /*Msg, err := json.Marshal(message.NewJSONMessage(msg)) if err != nil { fmt.Printf("Failed to marshal json: %v", err) } clientMsg, err := json.Marshal(map[string]string{"visorpk": route.Visor.Hex(), "serverpk": route.Server.Hex(), "roompk": route.Room.Hex(), "message": string(Msg)}) + */ + clientMsg, err := json.Marshal(map[string]string{"visorpk": route.Visor.Hex(), "serverpk": route.Server.Hex(), "roompk": route.Room.Hex()}) + if err != nil { fmt.Printf("Failed to marshal json: %v", err) } @@ -59,9 +62,21 @@ func NewAddRouteNotification(route util.PKRoute) Notification { } } -// NewChatNotification notifies the user about new chat -func NewChatNotification(pk cipher.PubKey) Notification { - clientMsg, err := json.Marshal(map[string]string{"pk": pk.Hex()}) +// NewP2PChatNotification notifies the user about new infos in p2p chat +func NewP2PChatNotification(pk cipher.PubKey) Notification { + clientMsg, err := json.Marshal(map[string]string{"visorpk": pk.Hex(), "serverpk": pk.Hex(), "roompk": pk.Hex()}) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + } + return Notification{ + Type: NewChatNotifyType, + Message: string(clientMsg), + } +} + +// NewGroupChatNotification notifies the user about new chat +func NewGroupChatNotification(route util.PKRoute) Notification { + clientMsg, err := json.Marshal(map[string]string{"visorpk": route.Visor.Hex(), "serverpk": route.Server.Hex(), "roompk": route.Room.Hex()}) if err != nil { fmt.Printf("Failed to marshal json: %v", err) } diff --git a/cmd/apps/skychat/internal/app/user/commands/set_info.go b/cmd/apps/skychat/internal/app/user/commands/set_info.go index b6572d6fe..85a0054f7 100644 --- a/cmd/apps/skychat/internal/app/user/commands/set_info.go +++ b/cmd/apps/skychat/internal/app/user/commands/set_info.go @@ -44,6 +44,9 @@ func (h setInfoRequestHandler) Handle(req SetInfoRequest) error { pUsr.SetInfo(i) //TODO:Send info to peers and servers that the info was updated + //get all visors + //for each visor get all servers and p2p + //send info to them return h.usrRepo.SetUser(pUsr) } diff --git a/cmd/apps/skychat/internal/domain/chat/room.go b/cmd/apps/skychat/internal/domain/chat/room.go index d89842d7c..65596bdee 100644 --- a/cmd/apps/skychat/internal/domain/chat/room.go +++ b/cmd/apps/skychat/internal/domain/chat/room.go @@ -43,8 +43,8 @@ type Room struct { Msgs []message.Message // P2P: send // Server: only send to members when room isVisible //Server - IsVisible bool //setting to make room visible for all server-members - Type int64 //roomType --> board,chat,voice + IsVisible bool //setting to make room visible for all server-members + Type int //roomType --> board,chat,voice //Private (only send to room members) Members map[cipher.PubKey]peer.Peer // all members @@ -74,6 +74,7 @@ func (r *Room) GetInfo() info.Info { // AddMessage adds the given message to the messages func (r *Room) AddMessage(m message.Message) { + fmt.Printf("Added Message to route: %s \n", &r.PKRoute) r.Msgs = append(r.Msgs, m) } @@ -95,12 +96,12 @@ func (r *Room) SetIsVisible(isVisible bool) { } // GetType returns the room's type -func (r *Room) GetType() int64 { +func (r *Room) GetType() int { return r.Type } // SetType sets the room's type -func (r *Room) SetType(t int64) { +func (r *Room) SetType(t int) { r.Type = t } @@ -266,6 +267,25 @@ func NewDefaultLocalRoom(roomRoute util.PKRoute) Room { return r } +// NewDefaultRemoteRoom returns a new default remote room +func NewDefaultRemoteRoom(roomRoute util.PKRoute) Room { + r := Room{} + r.PKRoute = roomRoute + r.Info = info.NewDefaultInfo() + //Msgs + r.IsVisible = true + r.Type = ChatRoomType + + r.Members = make(map[cipher.PubKey]peer.Peer) + r.Mods = make(map[cipher.PubKey]bool) + r.Muted = make(map[cipher.PubKey]bool) + r.Blacklist = make(map[cipher.PubKey]bool) + r.Whitelist = make(map[cipher.PubKey]bool) + r.Conns = make(map[cipher.PubKey]net.Conn) + + return r +} + // NewDefaultP2PRoom returns a new default p2p room func NewDefaultP2PRoom(pk cipher.PubKey) Room { r := Room{} @@ -285,7 +305,7 @@ func NewDefaultP2PRoom(pk cipher.PubKey) Room { } // NewLocalRoom returns a new local room -func NewLocalRoom(roomRoute util.PKRoute, i info.Info, t int64) Room { +func NewLocalRoom(roomRoute util.PKRoute, i info.Info, t int) Room { r := Room{} r.PKRoute = roomRoute r.Info = i diff --git a/cmd/apps/skychat/internal/domain/chat/server.go b/cmd/apps/skychat/internal/domain/chat/server.go index 2eb4fc36f..6441d6d04 100644 --- a/cmd/apps/skychat/internal/domain/chat/server.go +++ b/cmd/apps/skychat/internal/domain/chat/server.go @@ -31,9 +31,10 @@ type Server struct { } // AddMessage adds a message to the server -func (s *Server) AddMessage(m message.Message) { - r := s.Rooms[m.Dest.Room] +func (s *Server) AddMessage(pkroute util.PKRoute, m message.Message) { + r := s.Rooms[pkroute.Room] r.AddMessage(m) + s.Rooms[pkroute.Room] = r } // GetPKRoute returns the PKRoute @@ -110,10 +111,12 @@ func (s *Server) GetAllRoomsBoolMap() map[cipher.PubKey]bool { func (s *Server) AddMember(peer peer.Peer) error { _, err := s.GetMemberByPK(peer.GetPK()) if err != nil { - return fmt.Errorf("peer already member of server") + s.Members[peer.GetPK()] = peer + return nil + } - s.Members[peer.GetPK()] = peer - return nil + return fmt.Errorf("peer already member of server") + } // DeleteMember deletes the member with the given pk @@ -123,7 +126,8 @@ func (s *Server) DeleteMember(pk cipher.PubKey) error { delete(s.Members, pk) return nil } - return fmt.Errorf("member does not exist") //? handle as error? + delete(s.Members, pk) + return nil } // GetMemberByPK returns the the member mapped by pk if available and returns err if no member with given pk exists @@ -152,27 +156,28 @@ func (s *Server) GetAllMembers() map[cipher.PubKey]peer.Peer { // SetMemberInfo sets the given info of the member inside the server and all rooms func (s *Server) SetMemberInfo(i info.Info) error { //set member info in server - member, err := s.GetMemberByPK(i.GetPK()) + sMember, err := s.GetMemberByPK(i.GetPK()) if err != nil { return err } - member.SetInfo(i) - err = s.SetMember(*member) + sMember.SetInfo(i) + err = s.SetMember(*sMember) if err != nil { return err } - //set member info in rooms + //set info in rooms if the pk is member for _, room := range s.Rooms { - room.GetMemberByPK(i.GetPK()) + rMember, err := room.GetMemberByPK(i.GetPK()) if err != nil { - return err + continue } - member.SetInfo(i) - err = room.SetMember(*member) + rMember.SetInfo(i) + err = room.SetMember(*rMember) if err != nil { return err } + s.SetRoom(room) } return nil @@ -342,3 +347,22 @@ func NewServer(route util.PKRoute, info info.Info, members map[cipher.PubKey]pee return &s } + +// NewDefaultServer returns a default server +func NewDefaultServer(route util.PKRoute) Server { + s := Server{} + s.PKRoute = route + s.Info = info.NewDefaultInfo() + + s.Members = make(map[cipher.PubKey]peer.Peer) + s.Admins = make(map[cipher.PubKey]bool) + s.Muted = make(map[cipher.PubKey]bool) + s.Blacklist = make(map[cipher.PubKey]bool) + s.Whitelist = make(map[cipher.PubKey]bool) + s.Rooms = make(map[cipher.PubKey]Room) + s.Conns = make(map[cipher.PubKey]net.Conn) + + s.AddRoom(NewDefaultRemoteRoom(route)) + + return s +} diff --git a/cmd/apps/skychat/internal/domain/chat/visor.go b/cmd/apps/skychat/internal/domain/chat/visor.go index c75e09012..0886e1648 100644 --- a/cmd/apps/skychat/internal/domain/chat/visor.go +++ b/cmd/apps/skychat/internal/domain/chat/visor.go @@ -2,16 +2,15 @@ package chat import ( "fmt" - "net" "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) // Visor defines a remote or the local visor with all its servers type Visor struct { - PK cipher.PubKey - Conn net.Conn + PK cipher.PubKey //P2P or direct chat P2P Room @@ -25,11 +24,6 @@ func (v *Visor) GetPK() cipher.PubKey { return v.PK } -// GetConnection returns net.Conn -func (v *Visor) GetConnection() net.Conn { - return v.Conn -} - // GetP2P returns peer to peer Room func (v *Visor) GetP2P() (Room, error) { //TODO: check if p2p is empty @@ -89,7 +83,7 @@ func (v *Visor) SetP2P(p2p Room) error { if err != nil { v.P2P = p2p } - return fmt.Errorf("p2p does not exist in visor") //? should this be treaded as an error like now? -> or maybe even call AddP2P when p2p does not exist? + return fmt.Errorf("setp2p: p2p does not exist in visor") //? should this be treaded as an error like now? -> or maybe even call AddP2P when p2p does not exist? } // DeleteP2P removes the p2p-chat-room from the visor @@ -99,7 +93,7 @@ func (v *Visor) DeleteP2P() error { if err != nil { v.P2P = Room{} } - return fmt.Errorf("p2p does not exist in visor") //? should this be treaded as an error like now? + return fmt.Errorf("deletep2p: p2p does not exist in visor") //? should this be treaded as an error like now? } // GetAllServer returns all mapped server @@ -124,24 +118,15 @@ func (v *Visor) GetServerByPK(pk cipher.PubKey) (*Server, error) { return nil, fmt.Errorf("no server with pk %s found in visor %s", pk.Hex(), v.PK) } -// SetConnection sets the connection type used -func (v *Visor) SetConnection(conn net.Conn) { - v.Conn = conn -} - -// DeleteConnection clears the connection -func (v *Visor) DeleteConnection() { - v.Conn = nil -} - // AddMessage Adds the given message to the given visor depending on the destination of the message -func (v *Visor) AddMessage(m message.Message) { - if m.Dest.Server == m.Dest.Visor { +func (v *Visor) AddMessage(pkroute util.PKRoute, m message.Message) { + if pkroute.Server == pkroute.Visor { v.P2P.AddMessage(m) return } - s := v.Server[m.Dest.Server] - s.AddMessage(m) + s := v.Server[pkroute.Server] + s.AddMessage(pkroute, m) + v.Server[pkroute.Server] = s } // Constructors @@ -150,7 +135,6 @@ func (v *Visor) AddMessage(m message.Message) { func NewUndefinedVisor(pk cipher.PubKey) Visor { v := Visor{} v.PK = pk - v.Conn = nil v.Server = make(map[cipher.PubKey]Server) return v @@ -160,7 +144,6 @@ func NewUndefinedVisor(pk cipher.PubKey) Visor { func NewVisor(pk cipher.PubKey, p2p Room, server map[cipher.PubKey]Server) Visor { v := Visor{} v.PK = pk - v.Conn = nil v.P2P = p2p v.Server = server return v @@ -170,9 +153,19 @@ func NewVisor(pk cipher.PubKey, p2p Room, server map[cipher.PubKey]Server) Visor func NewDefaultP2PVisor(pk cipher.PubKey) Visor { v := Visor{} v.PK = pk - v.Conn = nil v.P2P = NewDefaultP2PRoom(pk) v.Server = make(map[cipher.PubKey]Server) return v } + +// NewDefaultVisor creates a new default visor +func NewDefaultVisor(route util.PKRoute) Visor { + v := Visor{} + v.PK = route.Visor + v.Server = make(map[cipher.PubKey]Server) + + v.AddServer(NewDefaultServer(route)) + + return v +} diff --git a/cmd/apps/skychat/internal/domain/client/client.go b/cmd/apps/skychat/internal/domain/client/client.go index 06ec0581d..2f0cf798d 100644 --- a/cmd/apps/skychat/internal/domain/client/client.go +++ b/cmd/apps/skychat/internal/domain/client/client.go @@ -54,6 +54,15 @@ func (c *Client) GetConns() map[cipher.PubKey]net.Conn { return c.conns } +// GetConnByPK returns the conn of the given visor pk or an error if there is no open connection to the requested visor +func (c *Client) GetConnByPK(pk cipher.PubKey) (net.Conn, error) { + //check if conn already added + if conn, ok := c.conns[pk]; ok { + return conn, nil + } + return nil, fmt.Errorf("no conn available with the requested visor") +} + // AddConn adds the given net.Conn to the map to keep track of active connections func (c *Client) AddConn(pk cipher.PubKey, conn net.Conn) error { //check if conn already added diff --git a/cmd/apps/skychat/internal/domain/info/info.go b/cmd/apps/skychat/internal/domain/info/info.go index 4ca19fb2a..887816348 100644 --- a/cmd/apps/skychat/internal/domain/info/info.go +++ b/cmd/apps/skychat/internal/domain/info/info.go @@ -76,7 +76,8 @@ func NewDefaultInfo() Info { return info } -const DefaultImage = "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAIAAAAHjs1qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5OTMyNUUzOTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjY5OTMyNUU0OTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6Njk5MzI1RTE5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Njk5MzI1RTI5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7FIRCzAAAPn0lEQVR42uyd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" +//const DefaultImage = "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAIAAAAHjs1qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5OTMyNUUzOTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjY5OTMyNUU0OTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6Njk5MzI1RTE5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Njk5MzI1RTI5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7FIRCzAAAPn0lEQVR42uyd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" +const DefaultImage = "0" // IsEmpty checks if info is empty func (i *Info) IsEmpty() bool { diff --git a/cmd/apps/skychat/internal/domain/message/message.go b/cmd/apps/skychat/internal/domain/message/message.go index e8c8e5cd3..85a867668 100644 --- a/cmd/apps/skychat/internal/domain/message/message.go +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -3,6 +3,7 @@ package message import ( "encoding/json" + "fmt" "time" "github.com/skycoin/skywire-utilities/pkg/cipher" @@ -23,16 +24,31 @@ const ( CmdMsgType ) -// subtypes of connMsgType +// subtypes of ConnMsgType const ( - // ErrConnMsg is used to handle connection errors message + // ErrConnMsg is used to handle connection error messages ErrConnMsg = iota - // ConnMsgTypeRequest is used handle connection message of type Request + // ConnMsgTypeRequest is used to handle connection message of type Request ConnMsgTypeRequest - // ConnMsgTypeAccept is used handle connection message of type Accept + // ConnMsgTypeAccept is used to handle connection message of type Accept ConnMsgTypeAccept - // ConnMsgTypeReject is used handle connection message of type Reject + // ConnMsgTypeReject is used to handle connection message of type Reject ConnMsgTypeReject + // ConnMsgTypeLeave is used to handle connection message of type Leave + ConnMsgTypeLeave +) + +// subtypes of InfoMsgType +const ( + //ErrInfoMsgType is used to handle info error messages + ErrInfoMsgType = iota + //InfoMsgTypeUser is used to handle the info of a single user or server + InfoMsgTypeUser + //InfoMsgTypeServerMembers is used to update the list of members of a server + InfoMsgTypeServerMembers + //InfoMsgTypeRoomMembers is used to update the list of members of a room + InfoMsgTypeRoomMembers + //TODO: Admins, Moderators, Muted, Blacklist, Whitelist, Rooms from Server that are visible ) // types of messageStatus @@ -45,23 +61,55 @@ const ( MsgStatusReceived ) +// types fo CmdMsgType +const ( + // ErrCmdMsg is used to handle command error messages + ErrCmdMsg = iota + // CmdMsgTypeAddRoom is used to add a room + CmdMsgTypeAddRoom + // CmdMsgTypeDeleteRoom is used to delete a room + CmdMsgTypeDeleteRoom + /*CmdMsgTypeMutePeer + CmdMsgTypeUnmutePeer + CmdMsgTypeBanPeer + CmdMsgTypeUnbanPeer + CmdMsgTypeHireAdmin + CmdMsgTypeFireAdmin + CmdMsgTypeHireModerator + CmdMsgTypeFireModerator*/ +) + // Message defines a message type Message struct { - ID int64 //an identifier for p2p chats and groups, Id is set by the receiver/server - Origin cipher.PubKey //the originator of the Message - Time time.Time //the utc+0 timestamp of the Message - Root util.PKRoute //the root from where the Message was received (e.g. peer/group) - Dest util.PKRoute //the destination where the message should be sent. - MsgType int //see const above - MsgSubtype int //see const above - Message []byte //the actual Message - Status int //"Sent" or "Received" - Seen bool //flag to save whether the Message was read or not by the receiver (only for local notifications) -> online feedback will be implemented in future versions + ID int `json:"Id"` //an identifier for p2p chats and groups, Id is set by the receiver/server + Origin cipher.PubKey `json:"Origin"` //the originator of the Message + Time time.Time `json:"Time"` //the utc+0 timestamp of the Message + Root util.PKRoute `json:"Root"` //the root from where the Message was received (e.g. peer/group) + Dest util.PKRoute `json:"Dest"` //the destination where the message should be sent. + MsgType int `json:"Msgtype"` //see const above + MsgSubtype int `json:"MsgSubtype"` //see const above + Message []byte `json:"Message"` //the actual Message + Status int `json:"Status"` //"Sent" or "Received" + Seen bool `json:"Seen"` //flag to save whether the Message was read or not by the receiver (only for local notifications) -> online feedback will be implemented in future versions +} + +// RAWMessage defines a raw json message +type RAWMessage struct { + ID int `json:"Id"` + Origin cipher.PubKey `json:"Origin"` + Time time.Time `json:"Time"` + Root util.PKRoute `json:"Root"` + Dest util.PKRoute `json:"Dest"` + MsgType int `json:"Msgtype"` + MsgSubtype int `json:"MsgSubtype"` + Message json.RawMessage `json:"Message"` + Status int `json:"Status"` + Seen bool `json:"Seen"` } // JSONMessage defines a json message type JSONMessage struct { - ID int64 `json:"Id"` + ID int `json:"Id"` Origin cipher.PubKey `json:"Origin"` Time time.Time `json:"Time"` Root util.PKRoute `json:"Root"` @@ -89,8 +137,38 @@ func NewJSONMessage(m Message) JSONMessage { } } +// NewRAWMessage return a RAWMessage from a message +func NewRAWMessage(m Message) RAWMessage { + + bytes, err := json.Marshal(m.Message) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + } + + return RAWMessage{ + m.ID, + m.Origin, + m.Time, + m.Root, + m.Dest, + m.MsgType, + m.MsgSubtype, + bytes, + m.Status, + m.Seen, + } +} + // NewMessage returns a message from a JSONMessage -func NewMessage(m JSONMessage) Message { +func NewMessage(m RAWMessage) Message { + + var data []byte + Source := (*json.RawMessage)(&m.Message) + err := json.Unmarshal(*Source, &data) + if err != nil { + fmt.Printf("%v", err) + } + return Message{ m.ID, m.Origin, @@ -99,7 +177,7 @@ func NewMessage(m JSONMessage) Message { m.Dest, m.MsgType, m.MsgSubtype, - []byte(m.Message), + data, m.Status, m.Seen, } @@ -114,7 +192,7 @@ func (m Message) MarshalJSON() ([]byte, error) { func NewTextMessage(pkOrigin cipher.PubKey, routeDestination util.PKRoute, msg []byte) Message { m := Message{} m.Origin = pkOrigin - m.Root = util.NewVisorOnlyRoute(pkOrigin) + m.Root = util.NewP2PRoute(pkOrigin) m.Dest = routeDestination m.MsgType = TxtMsgType m.MsgSubtype = 0 @@ -128,10 +206,11 @@ func NewTextMessage(pkOrigin cipher.PubKey, routeDestination util.PKRoute, msg [ func NewRouteRequestMessage(pkOrigin cipher.PubKey, routeDestination util.PKRoute) Message { m := Message{} m.Origin = pkOrigin - m.Root = util.NewVisorOnlyRoute(pkOrigin) + m.Root = util.NewP2PRoute(pkOrigin) m.Dest = routeDestination m.MsgType = ConnMsgType m.MsgSubtype = ConnMsgTypeRequest + m.Message = []byte("Chat Request") m.Status = MsgStatusInitial m.Time = time.Now() return m @@ -148,6 +227,7 @@ func NewChatAcceptMessage(root util.PKRoute, dest util.PKRoute) Message { m.MsgType = ConnMsgType m.MsgSubtype = ConnMsgTypeAccept m.Status = MsgStatusInitial + m.Message = []byte("Chat Accepted") m.Time = time.Now() return m } @@ -160,6 +240,21 @@ func NewChatRejectMessage(root util.PKRoute, dest util.PKRoute) Message { m.Dest = dest m.MsgType = ConnMsgType m.MsgSubtype = ConnMsgTypeReject + m.Message = []byte("Chat Rejected") + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + +// NewChatLeaveMessage returns new chat leave message +func NewChatLeaveMessage(root util.PKRoute, dest util.PKRoute) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = ConnMsgType + m.MsgSubtype = ConnMsgTypeLeave + m.Message = []byte("Chat Left") m.Status = MsgStatusInitial m.Time = time.Now() return m @@ -178,8 +273,36 @@ func NewChatInfoMessage(root util.PKRoute, dest util.PKRoute, info []byte) Messa return m } +// NewAddRoomMessage returns a Message +func NewAddRoomMessage(root util.PKRoute, dest util.PKRoute, info []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = CmdMsgType + m.MsgSubtype = CmdMsgTypeAddRoom + m.Message = info + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + +// NewDeleteRoomMessage returns a Message +func NewDeleteRoomMessage(root util.PKRoute, dest util.PKRoute) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = CmdMsgType + m.MsgSubtype = CmdMsgTypeDeleteRoom + m.Message = []byte("Room Deleted") + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + // GetID returns message ID -func (m *Message) GetID() int64 { +func (m *Message) GetID() int { return m.ID } @@ -198,6 +321,16 @@ func (m *Message) GetRootVisor() cipher.PubKey { return m.Root.Visor } +// GetRootServer returns the root server public key +func (m *Message) GetRootServer() cipher.PubKey { + return m.Root.Server +} + +// GetRootRoom returns the root room public key +func (m *Message) GetRootRoom() cipher.PubKey { + return m.Root.Room +} + // GetDestinationVisor returns the destination visor func (m *Message) GetDestinationVisor() cipher.PubKey { return m.Dest.Visor diff --git a/cmd/apps/skychat/internal/domain/util/pkroute.go b/cmd/apps/skychat/internal/domain/util/pkroute.go index 4abcf3815..421c2d9d7 100644 --- a/cmd/apps/skychat/internal/domain/util/pkroute.go +++ b/cmd/apps/skychat/internal/domain/util/pkroute.go @@ -24,6 +24,7 @@ func NewP2PRoute(visorpk cipher.PubKey) PKRoute { pkr := PKRoute{} pkr.Visor = visorpk pkr.Server = visorpk + pkr.Room = visorpk return pkr } diff --git a/cmd/apps/skychat/internal/inputports/cli/cli.go b/cmd/apps/skychat/internal/inputports/cli/cli.go deleted file mode 100644 index b89c35676..000000000 --- a/cmd/apps/skychat/internal/inputports/cli/cli.go +++ /dev/null @@ -1,4 +0,0 @@ -// Package cli is an api for cli-commands -package cli - -//[] add cli functionality with cobra & viper --> Talk to Moses on what is needed and how to implement it diff --git a/cmd/apps/skychat/internal/inputports/http/chat/handler.go b/cmd/apps/skychat/internal/inputports/http/chat/handler.go index d4f4b0175..9846da29e 100644 --- a/cmd/apps/skychat/internal/inputports/http/chat/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/chat/handler.go @@ -28,27 +28,22 @@ func NewHandler(cs chatservices.ChatServices) *Handler { return &Handler{chatServices: cs} } -//[]: change to AddRoom -> as this also can be used to add a room at a remote server (when being admin) - -// AddLocalRoomURLParam contains the parameter identifier to be parsed by the handler -const AddLocalRoomURLParam = "addLocalRoom" +// AddLocalServerURLParam contains the parameter identifier to be parsed by the handler +const AddLocalServerURLParam = "addLocalServer" -// AddLocalRoomRequestModel represents the request model expected for Add request -type AddLocalRoomRequestModel struct { +// AddLocalServerRequestModel represents the request model expected for Add request +type AddLocalServerRequestModel struct { //PKRoute - VisorPk string `json:"visorpk"` - ServerPk string `json:"serverpk"` + VisorPk string `json:"visorpk"` //Info Alias string `json:"alias"` Desc string `json:"desc"` Img string `json:"img"` - //Type - Type string `json:"type"` } -// AddLocalRoom adds a room to the local visor/server -func (c Handler) AddLocalRoom(w http.ResponseWriter, r *http.Request) { - var requestModel AddLocalRoomRequestModel +// AddLocalServer adds a room to the local visor/server +func (c Handler) AddLocalServer(w http.ResponseWriter, r *http.Request) { + var requestModel AddLocalServerRequestModel decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) if decodeErr != nil { w.WriteHeader(http.StatusBadRequest) @@ -66,39 +61,15 @@ func (c Handler) AddLocalRoom(w http.ResponseWriter, r *http.Request) { return } route.Visor = visorpk - if requestModel.ServerPk != "" { - serverpk := cipher.PubKey{} - err = serverpk.Set(requestModel.ServerPk) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprint(w, err.Error()) - return - } - route.Server = serverpk - } info := info.Info{} info.SetAlias(requestModel.Alias) info.SetDescription(requestModel.Desc) info.SetImg(requestModel.Img) - var roomType int64 - - if requestModel.Type != "" { - roomType, err = strconv.ParseInt(requestModel.Type, 10, 64) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprint(w, err.Error()) - return - } - } else { - roomType = 1 - } - - err = c.chatServices.Commands.AddLocalRoomHandler.Handle(commands.AddLocalRoomRequest{ + err = c.chatServices.Commands.AddLocalServerHandler.Handle(commands.AddLocalServerRequest{ Route: route, Info: info, - Type: roomType, }) if err != nil { w.WriteHeader(http.StatusInternalServerError) @@ -108,25 +79,21 @@ func (c Handler) AddLocalRoom(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -//[]: change to AddServer -> as this also can be used to add a server at a remote visor (when being admin) - -// AddLocalServerURLParam contains the parameter identifier to be parsed by the handler -const AddLocalServerURLParam = "addLocalServer" +// JoinRemoteRouteURLParam contains the parameter identifier to be parsed by the handler +const JoinRemoteRouteURLParam = "joinRemoteRoute" -// AddLocalServerRequestModel represents the request model expected for Add request -type AddLocalServerRequestModel struct { - //PKRoute - VisorPk string `json:"visorpk"` - //Info - Alias string `json:"alias"` - Desc string `json:"desc"` - Img string `json:"img"` +// JoinRemoteRouteRequestModel represents the request model expected for Join request +type JoinRemoteRouteRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` } -// AddLocalServer adds a room to the local visor/server -func (c Handler) AddLocalServer(w http.ResponseWriter, r *http.Request) { - var requestModel AddLocalServerRequestModel - decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) +// JoinRemoteRoute adds the provided route +func (c Handler) JoinRemoteRoute(w http.ResponseWriter, r *http.Request) { + //fmt.Println(formatRequest(r)) + var routeToJoin JoinRemoteRouteRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&routeToJoin) if decodeErr != nil { w.WriteHeader(http.StatusBadRequest) fmt.Fprint(w, decodeErr.Error()) @@ -136,22 +103,36 @@ func (c Handler) AddLocalServer(w http.ResponseWriter, r *http.Request) { route := util.PKRoute{} visorpk := cipher.PubKey{} - err := visorpk.Set(requestModel.VisorPk) + err := visorpk.Set(routeToJoin.VisorPk) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, err.Error()) return } route.Visor = visorpk + if routeToJoin.ServerPk != "" { + serverpk := cipher.PubKey{} + err = serverpk.Set(routeToJoin.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + if routeToJoin.RoomPk != "" { + roompk := cipher.PubKey{} + err = roompk.Set(routeToJoin.RoomPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Room = roompk + } + } - info := info.Info{} - info.SetAlias(requestModel.Alias) - info.SetDescription(requestModel.Desc) - info.SetImg(requestModel.Img) - - err = c.chatServices.Commands.AddLocalServerHandler.Handle(commands.AddLocalServerRequest{ + err = c.chatServices.Commands.JoinRemoteRouteHandler.Handle(commands.JoinRemoteRouteRequest{ Route: route, - Info: info, }) if err != nil { w.WriteHeader(http.StatusInternalServerError) @@ -161,50 +142,48 @@ func (c Handler) AddLocalServer(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -// AddRemoteRouteURLParam contains the parameter identifier to be parsed by the handler -const AddRemoteRouteURLParam = "addRemoteRoute" +// SendDeleteRoomMessageURLParam contains the parameter identifier to be parsed by the handler +const SendDeleteRoomMessageURLParam = "sendDeleteRoomMessage" -// AddRemoteRouteRequestModel represents the request model expected for Add request -type AddRemoteRouteRequestModel struct { +// SendDeleteRoomMessageRequestModel represents the request model expected for Delete request +type SendDeleteRoomMessageRequestModel struct { VisorPk string `json:"visorpk"` ServerPk string `json:"serverpk"` RoomPk string `json:"roompk"` } -// AddRemoteRoute adds the provided route -func (c Handler) AddRemoteRoute(w http.ResponseWriter, r *http.Request) { - //fmt.Println(formatRequest(r)) - var routeToAdd AddRemoteRouteRequestModel - decodeErr := json.NewDecoder(r.Body).Decode(&routeToAdd) +// SendDeleteRoomMessage adds a room to the local visor/server +func (c Handler) SendDeleteRoomMessage(w http.ResponseWriter, r *http.Request) { + var requestModel SendDeleteRoomMessageRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) if decodeErr != nil { w.WriteHeader(http.StatusBadRequest) fmt.Fprint(w, decodeErr.Error()) return } - fmt.Println("HTTPHandler - Add - Route: " + routeToAdd.VisorPk + "," + routeToAdd.ServerPk + "," + routeToAdd.RoomPk) route := util.PKRoute{} visorpk := cipher.PubKey{} - err := visorpk.Set(routeToAdd.VisorPk) + err := visorpk.Set(requestModel.VisorPk) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, err.Error()) return } route.Visor = visorpk - if routeToAdd.ServerPk != "" { + if requestModel.ServerPk != "" { serverpk := cipher.PubKey{} - err = serverpk.Set(routeToAdd.ServerPk) + err = serverpk.Set(requestModel.ServerPk) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, err.Error()) return } route.Server = serverpk - if routeToAdd.RoomPk != "" { + if requestModel.RoomPk != "" { roompk := cipher.PubKey{} - err = roompk.Set(routeToAdd.RoomPk) + err = roompk.Set(requestModel.RoomPk) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, err.Error()) @@ -214,7 +193,7 @@ func (c Handler) AddRemoteRoute(w http.ResponseWriter, r *http.Request) { } } - err = c.chatServices.Commands.AddRemoteRouteHandler.Handle(commands.AddRemoteRouteRequest{ + err = c.chatServices.Commands.SendDeleteRoomMessageHandler.Handle(commands.SendDeleteRoomMessageRequest{ Route: route, }) if err != nil { @@ -225,19 +204,27 @@ func (c Handler) AddRemoteRoute(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -// DeleteLocalRoomByRouteURLParam contains the parameter identifier to be parsed by the handler -const DeleteLocalRoomByRouteURLParam = "deleteLocalRoom" +// SendAddRoomMessageURLParam contains the parameter identifier to be parsed by the handler +const SendAddRoomMessageURLParam = "sendAddRoomMessage" -// DeleteLocalRoomByRouteRequestModel represents the request model expected for Delete request -type DeleteLocalRoomByRouteRequestModel struct { +// SendAddRoomMessageRequestModel represents the request model expected for Delete request +type SendAddRoomMessageRequestModel struct { VisorPk string `json:"visorpk"` ServerPk string `json:"serverpk"` RoomPk string `json:"roompk"` + + //Info + Alias string `json:"alias"` + Desc string `json:"desc"` + Img string `json:"img"` + + //Type + Type string `json:"type"` } -// DeleteLocalRoomByRoute adds a room to the local visor/server -func (c Handler) DeleteLocalRoomByRoute(w http.ResponseWriter, r *http.Request) { - var requestModel DeleteLocalRoomByRouteRequestModel +// SendAddRoomMessage adds a room to the local visor/server +func (c Handler) SendAddRoomMessage(w http.ResponseWriter, r *http.Request) { + var requestModel SendAddRoomMessageRequestModel decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) if decodeErr != nil { w.WriteHeader(http.StatusBadRequest) @@ -255,29 +242,44 @@ func (c Handler) DeleteLocalRoomByRoute(w http.ResponseWriter, r *http.Request) return } route.Visor = visorpk - if requestModel.ServerPk != "" { - serverpk := cipher.PubKey{} - err = serverpk.Set(requestModel.ServerPk) + serverpk := cipher.PubKey{} + err = serverpk.Set(requestModel.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + if requestModel.RoomPk != "" { + roompk := cipher.PubKey{} + err = roompk.Set(requestModel.RoomPk) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprint(w, err.Error()) return } - route.Server = serverpk - if requestModel.RoomPk != "" { - roompk := cipher.PubKey{} - err = roompk.Set(requestModel.RoomPk) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprint(w, err.Error()) - return - } - route.Room = roompk + route.Room = roompk + } + + info := info.NewInfo(route.Room, requestModel.Alias, requestModel.Desc, requestModel.Img) + + var roomType int + + if requestModel.Type != "" { + roomType, err = strconv.Atoi(requestModel.Type) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return } + } else { + roomType = 1 } - err = c.chatServices.Commands.DeleteLocalRoomHandler.Handle(commands.DeleteLocalRoomRequest{ + err = c.chatServices.Commands.SendAddRoomMessageHandler.Handle(commands.SendAddRoomMessageRequest{ Route: route, + Info: info, + Type: roomType, }) if err != nil { w.WriteHeader(http.StatusInternalServerError) @@ -360,19 +362,19 @@ func (c Handler) DeleteVisorByPK(w http.ResponseWriter, r *http.Request) { } } -// LeaveRemoteRoomByRouteURLParam contains the parameter identifier to be parsed by the handler -const LeaveRemoteRoomByRouteURLParam = "leaveRemoteRoom" +// LeaveRemoteRouteURLParam contains the parameter identifier to be parsed by the handler +const LeaveRemoteRouteURLParam = "leaveRemoteRoute" -// LeaveRemoteRoomByRouteRequestModel represents the request model expected for Leave request -type LeaveRemoteRoomByRouteRequestModel struct { +// LeaveRemoteRouteRequestModel represents the request model expected for Leave request +type LeaveRemoteRouteRequestModel struct { VisorPk string `json:"visorpk"` ServerPk string `json:"serverpk"` RoomPk string `json:"roompk"` } -// LeaveRemoteRoomByRoute adds a room to the local visor/server -func (c Handler) LeaveRemoteRoomByRoute(w http.ResponseWriter, r *http.Request) { - var requestModel LeaveRemoteRoomByRouteRequestModel +// LeaveRemoteRoute adds a room to the local visor/server +func (c Handler) LeaveRemoteRoute(w http.ResponseWriter, r *http.Request) { + var requestModel LeaveRemoteRouteRequestModel decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) if decodeErr != nil { w.WriteHeader(http.StatusBadRequest) @@ -411,58 +413,7 @@ func (c Handler) LeaveRemoteRoomByRoute(w http.ResponseWriter, r *http.Request) } } - err = c.chatServices.Commands.LeaveRemoteRoomHandler.Handle(commands.LeaveRemoteRoomRequest{ - Route: route, - }) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprint(w, err.Error()) - return - } - w.WriteHeader(http.StatusOK) -} - -// LeaveRemoteServerByRouteURLParam contains the parameter identifier to be parsed by the handler -const LeaveRemoteServerByRouteURLParam = "leaveRemoteRoom" - -// LeaveRemoteServerByRouteRequestModel represents the request model expected for Leave request -type LeaveRemoteServerByRouteRequestModel struct { - VisorPk string `json:"visorpk"` - ServerPk string `json:"serverpk"` -} - -// LeaveRemoteServerByRoute adds a room to the local visor/server -func (c Handler) LeaveRemoteServerByRoute(w http.ResponseWriter, r *http.Request) { - var requestModel LeaveRemoteServerByRouteRequestModel - decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) - if decodeErr != nil { - w.WriteHeader(http.StatusBadRequest) - fmt.Fprint(w, decodeErr.Error()) - return - } - - route := util.PKRoute{} - - visorpk := cipher.PubKey{} - err := visorpk.Set(requestModel.VisorPk) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprint(w, err.Error()) - return - } - route.Visor = visorpk - if requestModel.ServerPk != "" { - serverpk := cipher.PubKey{} - err = serverpk.Set(requestModel.ServerPk) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprint(w, err.Error()) - return - } - route.Server = serverpk - } - - err = c.chatServices.Commands.LeaveRemoteServerHandler.Handle(commands.LeaveRemoteServerRequest{ + err = c.chatServices.Commands.LeaveRemoteRouteHandler.Handle(commands.LeaveRemoteRouteRequest{ Route: route, }) if err != nil { diff --git a/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go b/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go index 5a293c761..7577a2393 100644 --- a/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go @@ -21,19 +21,26 @@ func NewHandler(ns notification.Service) *Handler { // SubscribeNotifications sends all received msgs from channel to http func (c Handler) SubscribeNotifications(w http.ResponseWriter, r *http.Request) { + fmt.Println("Get handshake from client") + + // prepare the flusher f, ok := w.(http.Flusher) if !ok { http.Error(w, "Streaming unsupported!", http.StatusInternalServerError) return } + // prepare the header w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") w.Header().Set("Transfer-Encoding", "chunked") w.Header().Set("Access-Control-Allow-Origin", "*") + // instantiate the channel c.ns.InitChannel() + + // close the channel after exit the function defer func() { c.ns.DeferChannel() }() @@ -41,12 +48,13 @@ func (c Handler) SubscribeNotifications(w http.ResponseWriter, r *http.Request) for { select { case <-r.Context().Done(): - fmt.Println("SSE connection were closed.") + fmt.Println("SSE: connection was closed.") return default: msg, ok := <-c.ns.GetChannel() if !ok { + fmt.Println("GetChannel not ok") return } fmt.Fprintf(w, "data: %s\n\n", msg) diff --git a/cmd/apps/skychat/internal/inputports/http/server.go b/cmd/apps/skychat/internal/inputports/http/server.go index 0de0ae0b8..679561460 100644 --- a/cmd/apps/skychat/internal/inputports/http/server.go +++ b/cmd/apps/skychat/internal/inputports/http/server.go @@ -56,14 +56,12 @@ func (httpServer *Server) AddChatHTTPRoutes() { httpServer.router.HandleFunc(chatsHTTPRoutePath+"/{"+chat.GetVisorByPKURLParam+"}", chat.NewHandler(httpServer.appServices.ChatServices).GetVisorByPK).Methods("GET") //Commands - httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.AddLocalRoomURLParam, chat.NewHandler(httpServer.appServices.ChatServices).AddLocalRoom).Methods("POST") httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.AddLocalServerURLParam, chat.NewHandler(httpServer.appServices.ChatServices).AddLocalServer).Methods("POST") - httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.AddRemoteRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).AddRemoteRoute).Methods("POST") - httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.DeleteLocalRoomByRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).DeleteLocalRoomByRoute).Methods("POST") - httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.DeleteLocalServerByRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).DeleteLocalServerByRoute).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.JoinRemoteRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).JoinRemoteRoute).Methods("POST") httpServer.router.HandleFunc(chatsHTTPRoutePath+"/{"+chat.DeleteVisorByPKURLParam+"}", chat.NewHandler(httpServer.appServices.ChatServices).DeleteVisorByPK).Methods("DELETE") - httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.LeaveRemoteRoomByRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).LeaveRemoteRoomByRoute).Methods("POST") - httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.LeaveRemoteServerByRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).LeaveRemoteServerByRoute).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.LeaveRemoteRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).LeaveRemoteRoute).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendAddRoomMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendAddRoomMessage).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendDeleteRoomMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendDeleteRoomMessage).Methods("POST") httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendTextMessagePKURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendTextMessage).Methods("POST") } diff --git a/cmd/apps/skychat/internal/inputports/http/static/index.html b/cmd/apps/skychat/internal/inputports/http/static/index.html index cac713162..38222a640 100644 --- a/cmd/apps/skychat/internal/inputports/http/static/index.html +++ b/cmd/apps/skychat/internal/inputports/http/static/index.html @@ -13,7 +13,7 @@ diff --git a/cmd/apps/skychat/internal/inputports/http/static/index.js b/cmd/apps/skychat/internal/inputports/http/static/index.js index c9d463b53..a0ea5afc9 100644 --- a/cmd/apps/skychat/internal/inputports/http/static/index.js +++ b/cmd/apps/skychat/internal/inputports/http/static/index.js @@ -409,9 +409,9 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa } addAddRemote(c){ - document.getElementById('addRemote').innerHTML += - ` -
              Add Remote Server and Rooms
              + document.getElementById('joinRemote').innerHTML += + `
              +
              Join Remote Server and Rooms
              `; } @@ -432,6 +432,23 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa `; } + _getRoomPrefix(r){ + let prefix = "" + if (r.route.visor == r.route.room) { + //P2P + prefix = "P2P" + } else { + //GroupChat / Room + prefix = "G" + } + + if (r.route.visor == this.user.info.pk){ + //Hosted on localhost + prefix += String.fromCharCode(0x2302) + } + return prefix + } + _addChat(r) { if (!this.chats.includes(r)) { this.chats.push(r); @@ -440,10 +457,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa let lastMsg = this.getLastMessageFromRoute(r.route) - let local = "" - if (r.route.visor == this.user.info.pk){ - local = String.fromCharCode(0x2302) - } + let prefix = this._getRoomPrefix(r) document.getElementById('chatList').innerHTML += `
              @@ -451,7 +465,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa
              - ${local} ${r.info.alias} + ${prefix} ${r.info.alias}
              ${r.pk} @@ -475,17 +489,14 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa let lastMsg = this.getLastMessageFromRoute(r.route) - let local = "" - if (r.route.visor == this.user.info.pk){ - local = String.fromCharCode(0x2302) - } + let prefix = this._getRoomPrefix(r) document.getElementById('chat_'+ r.pk).innerHTML = `
            • - ${local} ${r.info.alias} + ${prefix} ${r.info.alias}
              ${r.pk} @@ -593,12 +604,12 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa document.getElementById('form').innerHTML += `
              -
              X
              +
              X
              To add a local Server or Group you have to insert the right Public Keys
            • For new server you can leave server pk empty but have to give an info
            • For a new group you have to give the PK of the server where you want to add the room to and an info
            • ServerPK
              -
              +
              Info
              @@ -617,7 +628,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa _showAddRemote(){ - this.user.inAddRemote = true; + this.user.inJoinRemote = true; //unselect chats in sidebar document.querySelectorAll('.destination').forEach(item => @@ -637,11 +648,11 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa document.getElementById('form').innerHTML += `
              -
              X
              -
              To add a remote P2P or Group you have to insert the right Public Keys
              -
            • P2P: VisorPK
            • +
              X
              +
              To join a remote P2P or Group you have to insert the right Public Keys
              +
            • P2P: VisorPK & ServerPK & RoomPK = RemotePK
            • Group/Server: VisorPK & ServerPK & RoomPK
            • - + @@ -652,8 +663,8 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa
              `; } - _hideInAddRemote(){ - this.user.inAddRemote = false; + _hideInJoinRemote(){ + this.user.inJoinRemote = false; document.getElementById('form').innerHTML = ``; } @@ -665,7 +676,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa switch(msg.type) { case 1: let connMsgOrigin - if (msg.sender == c.info.pk){ + if (msg.origin == c.info.pk){ connMsgOrigin = "user" } else { connMsgOrigin = "peer" @@ -680,6 +691,9 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa else if (msg.subtype == 3){ connMsg = "chat rejected" } + else if (msg.subtype == 4){ + connMsg = "remote deleted chat" + } else { connMsg = "undefined chat type message" } @@ -734,7 +748,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa this._hideSettings(); this._hideInAddLocal(); - this._hideInAddRemote(); + this._hideInJoinRemote(); this.chat = pk; document.querySelectorAll('.destination').forEach(item => { @@ -770,9 +784,9 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa ///////////////////////////////////////////////////////////// //// GET //returns [Info] from [User] - getUserInfo(){ + async getUserInfo(){ return fetch('user/getInfo', { method: 'GET', body: null }) - .then(res => { + .then(async res => { if (res.ok) { return res.json().then(i => { var info = new Info(i.Pk,i.Alias,i.Desc,i.Img); @@ -784,10 +798,10 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa }); } //returns [Settings] from [User] - getUserSettings(){ + async getUserSettings(){ return fetch('user/getSettings', { method: 'GET', body: null }) - .then(res => { + .then(async res => { if (res.ok) { return res.json().then(s => { var settings = new Settings(s.Blacklist); @@ -810,6 +824,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa fetch('user/setInfo', { method: 'PUT', body: JSON.stringify({ alias: info.alias, desc: info.desc, img: info.img}) }) .then(res => { if (res.ok) { + res.text() this.getUserInfo().then(info => { this._updateUser(new User(info, this.user.settings)); }); @@ -828,6 +843,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa fetch('user/setSettings', { method: 'PUT', body: JSON.stringify({ blacklist: settings.blacklist}) }) .then(res => { if (res.ok) { + res.text() this.getUserSettings().then(settings => { this._updateUser(new User(this.user.info, settings)); }); @@ -902,7 +918,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa } //returns an array of [Chat] - getChatAll(){ + async getChatAll(){ return fetch('chats', { method: 'GET', body: null }) .then(res => { @@ -910,13 +926,13 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa return res.json().then(visors => { var v_ = [] - console.log(visors) if (visors != null){ visors.forEach( v => { console.log(v) - if (v.P2P != null) { + var p2p + if (v.P2P != null && v.P2P.Type != 0) { if (Object.keys(v.P2P).length){ - var p2p = this.getRoomHTTP(v.P2P) + p2p = this.getRoomHTTP(v.P2P) } } else { p2p = null @@ -927,7 +943,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa s_.push(this.getServerHTTP(v.Server[s])) }) } - v_.push(new Visor(v.PK,p2p,s_)) + v_.push(new Visor(v.Pk,p2p,s_)) }) return this.getSortedChats(v_) @@ -947,7 +963,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa //for the first working skychat there is no sorting var cs = [] Object.keys(visors).forEach(v => { - if (visors[v].pk != undefined){ + if (visors[v].p2p != null){ cs.push(visors[v].p2p) } Object.keys(visors[v].server).forEach(s => { @@ -960,7 +976,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa } //returns the [Room] with the given route - getRoomByRoute(route){ + async getRoomByRoute(route){ const visorpk = route.visor const serverpk = route.server const roompk = route.room @@ -968,7 +984,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa const params = new URLSearchParams({visor: visorpk, server: serverpk,room: roompk}) return fetch('chats/'+ 'getRoom?' + params, { method: 'GET', body: null}) - .then(res => { + .then( async res => { if (res.ok) { return res.json().then(r => { console.log(r) @@ -982,8 +998,8 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa } //// POST - //adLocalRoute adds a new Server or Room in dependency on the given info - addLocalRoute(el){ + //addRoute adds a new Server or Room in dependency on the given info + addRoute(el){ const visorpk = this.user.info.pk const serverpk = this.processPk(el[0].value.trim()); const alias = el[1].value.trim(); @@ -1010,19 +1026,19 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa return; } - fetch('chats/' + "addLocalRoom", { method: 'POST', body: JSON.stringify({ visorpk: visorpk, serverpk: serverpk, alias: alias, desc: description, img: null, type:null}) }) + fetch('chats/' + "sendAddRoomMessage", { method: 'POST', body: JSON.stringify({ visorpk: visorpk, serverpk: serverpk, alias: alias, desc: description, img: null, type:null}) }) .then(res => { if (res.ok) { - res.text().then(); + res.text() } else { - res.text().then(text => alert(`Failed to add local room: ${text}`)); + res.text().then(text => alert(`Failed to add room: ${text}`)); } }).catch(e => alert(e.message)); }else{ fetch('chats/' + "addLocalServer", { method: 'POST', body: JSON.stringify({ visorpk: visorpk, alias: alias, desc: description, img: ""}) }) .then(res => { if (res.ok) { - res.text().then(); + res.text() } else { res.text().then(text => alert(`Failed to add local server: ${text}`)); } @@ -1032,7 +1048,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa //tries to add the given route //returns nothing - addRemoteRoute(el) { + joinRemoteRoute(el) { const visorpk = this.processPk(el[0].value.trim()); const serverpk = this.processPk(el[1].value.trim()); const roompk = this.processPk(el[2].value.trim()); @@ -1088,10 +1104,10 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa //TODO: Make if or switch case -> when visorpk is same as userpk and serverpk and roompk is empty then make new server with one room //and if visorpk and serverpk is defined but roompk is empty then add new room to server - fetch('chats/' + "addRemoteRoute", { method: 'POST', body: JSON.stringify({ visorpk: visorpk, serverpk: serverpk, roompk: roompk}) }) + fetch('chats/' + "joinRemoteRoute", { method: 'POST', body: JSON.stringify({ visorpk: visorpk, serverpk: serverpk, roompk: roompk}) }) .then(res => { if (res.ok) { - res.text().then(); + res.text() } else { res.text().then(text => alert(`Failed to add chat: ${text}`)); } @@ -1117,7 +1133,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa fetch('chats/' + "sendTxtMsg", { method: 'POST', body: JSON.stringify({ visorpk: visorpk, serverpk: serverpk, roompk: roompk, message: msg}) }) .then(res => { if (res.ok) { - res.text().then(); + res.text() el[0].value = ''; } else { res.text().then(text => alert(`Failed to send message: ${text}`)); @@ -1172,20 +1188,22 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa //// Subscribe notificationsSubscribe() { const source = new EventSource('/notifications'); - source.onmessage = (event) => { + source.onmessage = async(event) => { const data = JSON.parse(event.data); console.log(data) + console.log("Notification DataType: " + data.type) const notifMessage = JSON.parse(data.message) let visorpk = notifMessage.visorpk let serverpk = notifMessage.serverpk let roompk = notifMessage.roompk let route = new Route(visorpk,serverpk,roompk) + switch(data.type) { //NewAddRouteNotifyType case 1: console.log("new add route notification") - this.getRoomByRoute(route).then(c => { + await this.getRoomByRoute(route).then(c => { if (this.chats == null){ this.chats = [] } @@ -1196,7 +1214,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa //NewChatNotifType case 2: console.log("new peer chat notification") - this.getRoomByRoute(route).then(chat => { + await this.getRoomByRoute(route).then(chat => { if (this.chats == null){ this.chats = [] } @@ -1208,14 +1226,18 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa //Fetch data of chat with new message from HTTP console.log("new message notification") - const message = JSON.parse(notifMessage.message) - visorpk = message.Dest.Visor - serverpk = message.Dest.Server - roompk = message.Dest.Room - route = new Route(visorpk,serverpk,roompk) - console.log(message) - - this.getRoomByRoute(route).then(c => { + //const message = JSON.parse(notifMessage.message) + //visorpk = message.Root.Visor + //serverpk = message.Root.Server + //roompk = message.Root.Room + //route = new Route(visorpk,serverpk,roompk) + //console.log(message) + + await this.getRoomByRoute(route).then(c => { + if (this.chats == null){ + this.chats = [] + this._addChat(c) + } this._updateChat(c) }) break; @@ -1224,6 +1246,9 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa break; } } + source.onerror = async(event) => { + console.error("EventSource failed:", event) + } }; ///////////////////////////////////////////////////////////// diff --git a/cmd/apps/skychat/internal/inputports/http/static/stylesheet.css b/cmd/apps/skychat/internal/inputports/http/static/stylesheet.css index b15441ebb..de1c5dfa8 100644 --- a/cmd/apps/skychat/internal/inputports/http/static/stylesheet.css +++ b/cmd/apps/skychat/internal/inputports/http/static/stylesheet.css @@ -261,7 +261,7 @@ html { /*Stolen from https://codepen.io/danimerida2000/pen/wVXegX */ .showLeft { - text-shadow: white !important; + /* text-shadow: white !important; */ color: black !important; padding: 10px; } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index f4c247242..1e55a42da 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -63,6 +63,7 @@ func (ms MessengerService) Handle(pk cipher.PubKey) { localPK := pCli.GetAppClient().Config().VisorPK for { + //read packets buf := make([]byte, 32*1024) n, err := conn.Read(buf) @@ -80,89 +81,79 @@ func (ms MessengerService) Handle(pk cipher.PubKey) { } //unmarshal the received bytes to a message.Message - m := message.Message{} + m := message.RAWMessage{} + fmt.Println("---------------------------------------------------------------------------------------------------") + fmt.Println("New Raw Message") + fmt.Println("---------------------------------------------------------------------------------------------------") err = json.Unmarshal(buf[:n], &m) if err != nil { - fmt.Printf("Failed to unmarshal json message: %v", err) + fmt.Printf("Failed to unmarshal json message: %v \n", err) } else { - //unmarshal the received bytes to a message.JSONMessage{} - buf := make([]byte, 32*1024) - n, err := conn.Read(buf) - if err != nil { - fmt.Println("Failed to read packet:", err) - continue + jm := message.NewMessage(m) + fmt.Println("---------------------------------------------------------------------------------------------------") + fmt.Printf("Message: \n") + fmt.Printf("ID: %d \n", jm.ID) + fmt.Printf("Origin: %s \n", jm.Origin) + fmt.Printf("Time: %s \n", jm.Time) + fmt.Printf("Root: %s \n", jm.Root.String()) + fmt.Printf("Dest: %s \n", jm.Dest.String()) + fmt.Printf("MsgType: %d \n", jm.MsgType) + fmt.Printf("MsgSubType: %d \n", jm.MsgSubtype) + fmt.Printf("Message: %s \n", string(jm.Message)) + fmt.Printf("Status: %d \n", jm.Status) + fmt.Printf("Seen: %t \n", jm.Seen) + fmt.Println("---------------------------------------------------------------------------------------------------") + + if jm.GetDestinationVisor() == localPK && jm.GetDestinationServer() == localPK && jm.GetDestinationRoom() == localPK && jm.GetRootVisor() == jm.GetRootServer() && jm.GetRootServer() == jm.GetRootRoom() { + err = ms.handleP2PMessage(jm) + } else if jm.GetRootVisor() != jm.GetRootServer() && jm.GetRootServer() != jm.GetRootRoom() { + err = ms.handleRemoteServerMessage(jm) + } else if jm.GetDestinationVisor() == localPK && jm.GetDestinationVisor() != jm.GetDestinationServer() && jm.GetDestinationServer() != jm.GetDestinationRoom() { + err = ms.handleLocalServerMessage(jm) + } else { + fmt.Println("received message that can't be matched to remote or local server or p2p chat") } - jm := message.JSONMessage{} - err = json.Unmarshal(buf[:n], &jm) if err != nil { - fmt.Printf("Failed to unmarshal json jsonMessage: %v", err) + fmt.Println(err) continue } - m = message.NewMessage(jm) - - //handle messages in dependency of destination - if m.GetDestinationVisor() == localPK { - if m.GetDestinationServer() == localPK { - err = ms.handleP2PMessage(m) - } else { - err = ms.handleLocalServerMessage(m) - } - if err != nil { - fmt.Println(err) - continue - } - } else { - err = ms.handleRemoteServerMessage(m) - if err != nil { - fmt.Println(err) - continue - } - - } } } } -//TODO: think about how to handle this -//If the received message has status MsgSTatusInitial it was just send and we have to send it back to let the -//peer know that we received it. -//if m.GetStatus() == message.MsgStatusInitial { -// m.SetStatus(message.MsgStatusReceived) -// ms.sendMessage(pk, m) -//} -//notify that a new message has been received -//save message to chatrepo -//TODO: make NewReceivedTextMessage -//! Can also be a message of the remote that the own send message has been received - // Dial dials the remote chat func (ms MessengerService) Dial(pk cipher.PubKey) (net.Conn, error) { - c, err := ms.visorRepo.GetByPK(pk) - if err != nil { - //Should not happen as before dial chats get added to repo - return nil, err - } - pCli, err := ms.cliRepo.GetClient() if err != nil { fmt.Printf("Error Getting client") return nil, err } - conn := c.GetConnection() - /*if conn != nil { - //TODO: maybe delete old connection and reconnect? - //TODO: or skip dialing if connection alive - //pCli.GetAppClient().Close() - - }*/ + conn, err := pCli.GetConnByPK(pk) + if err == nil { + //? is this necessary + fmt.Printf("Connection already available, so delete old connection \n") + err = conn.Close() + if err != nil { + return nil, err + } + err = pCli.DeleteConn(pk) + if err != nil { + return nil, err + } + //save client in repo + err = ms.cliRepo.SetClient(*pCli) + if err != nil { + fmt.Println(err) + } + } addr := appnet.Addr{ Net: pCli.GetNetType(), - PubKey: c.GetPK(), + PubKey: pk, Port: pCli.GetPort(), } @@ -177,7 +168,7 @@ func (ms MessengerService) Dial(pk cipher.PubKey) (net.Conn, error) { //TODO: notify that dialing is happening? conn, err = pCli.GetAppClient().Dial(addr) //could not find a valid connection to a chat, so delete it. - err2 := ms.visorRepo.Delete(c.PK) + err2 := ms.visorRepo.Delete(pk) if err2 != nil { return err2 } @@ -188,55 +179,132 @@ func (ms MessengerService) Dial(pk cipher.PubKey) (net.Conn, error) { return nil, err } - c.SetConnection(conn) - err = ms.visorRepo.Set(*c) + //save connection in pCli + err = pCli.AddConn(pk, conn) if err != nil { return nil, err } + //save client in repo + err = ms.cliRepo.SetClient(*pCli) + if err != nil { + fmt.Println(err) + } + return conn, nil } // sendMessage sends a message to the given route -func (ms MessengerService) sendMessage(dest util.PKRoute, m message.Message) error { - v, err := ms.visorRepo.GetByPK(dest.Visor) +func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, addToDatabase bool) error { + //check if visor exists + v, err := ms.visorRepo.GetByPK(pkroute.Visor) if err != nil { - ch := chat.NewUndefinedVisor(dest.Visor) - err2 := ms.visorRepo.Add(ch) + v2 := chat.Visor{} + //visor doesn't exist so we add a new remote route + if pkroute.Visor == pkroute.Server { // --> P2P remote route + v2 = chat.NewDefaultP2PVisor(pkroute.Visor) + } else { + v2 = chat.NewDefaultVisor(pkroute) + } + err2 := ms.visorRepo.Add(v2) if err2 != nil { return err2 } - v = &ch - fmt.Printf("New skychat added: %s\n", dest.Visor) + v = &v2 + fmt.Printf("New skychat added: %s\n", pkroute.String()) + } + + // if the message is a p2p message we have to check if the p2p room exists in the sever + if pkroute.Visor == pkroute.Server { + //maybe we already have a visor, but not yet a p2p-room so check if we have that. + _, err = v.GetP2P() + if err != nil { + p2p := chat.NewDefaultP2PRoom(pkroute.Visor) + err = v.AddP2P(p2p) + if err != nil { + return err + } + fmt.Printf("New P2P room added: %s\n", pkroute.String()) + } + } else { + // the message we want to send is a server / room message + server, err := v.GetServerByPK(pkroute.Server) + if err != nil { + s := chat.NewDefaultServer(pkroute) + err = v.AddServer(s) + if err != nil { + return err + } + fmt.Printf("New Server added: %s\n", pkroute.String()) + } else { + //the server exists so we have to check if the room already exists + _, err := server.GetRoomByPK(pkroute.Room) + if err != nil { + r := chat.NewDefaultRemoteRoom(pkroute) + err = server.AddRoom(r) + if err != nil { + return err + } + err = v.SetServer(*server) + if err != nil { + return err + } + fmt.Printf("New Room added: %s\n", pkroute.String()) + } + } + } - m.Dest = dest + pCli, err := ms.cliRepo.GetClient() + if err != nil { + fmt.Printf("Error Getting client") + return err + } - bytes, err := json.Marshal(m) + fmt.Println("---------------------------------------------------------------------------------------------------") + fmt.Println("Sending Message:") + fmt.Printf("%s \n", pkroute.String()) + fmt.Println("---------------------------------------------------------------------------------------------------") + fmt.Printf("Message: \n") + fmt.Printf("ID: %d \n", m.ID) + fmt.Printf("Origin: %s \n", m.Origin) + fmt.Printf("Time: %s \n", m.Time) + fmt.Printf("Root: %s \n", m.Root.String()) + fmt.Printf("Dest: %s \n", m.Dest.String()) + fmt.Printf("MsgType: %d \n", m.MsgType) + fmt.Printf("MsgSubType: %d \n", m.MsgSubtype) + fmt.Printf("Message: %s \n", string(m.Message)) + fmt.Printf("Status: %d \n", m.Status) + fmt.Printf("Seen: %t \n", m.Seen) + fmt.Println("---------------------------------------------------------------------------------------------------") + + rm := message.NewRAWMessage(m) + + bytes, err := json.Marshal(rm) if err != nil { fmt.Printf("Failed to marshal json: %v", err) } - conn := v.GetConnection() - if conn == nil { - conn, err = ms.Dial(dest.Visor) + //Get connection from remote/destination visor of message + conn, err := pCli.GetConnByPK(m.Dest.Visor) + if err != nil { + conn, err = ms.Dial(m.Dest.Visor) if err != nil { return err } } + fmt.Printf("Write Bytes to Conn: %s \n", conn.LocalAddr()) _, err = conn.Write(bytes) if err != nil { return err } - v, err = ms.visorRepo.GetByPK(dest.Visor) - if err != nil { - return err - } - v.AddMessage(m) - err = ms.visorRepo.Set(*v) - if err != nil { - return err + if addToDatabase { + v.AddMessage(pkroute, m) + err = ms.visorRepo.Set(*v) + if err != nil { + return err + } } return nil @@ -274,9 +342,8 @@ func (ms MessengerService) sendMessageNirvana(route util.PKRoute, m message.Mess } // SendRouteRequestMessage sends a request message to join the specified route -// if route.Visor == route.Server -> P2P request -// if route.Visor + (route.Server == nil) -> P2P request -// if route.Visor + route.Server -> ServerJoinRequest +// if route.Visor == route.Server == route.Room -> P2P request +// if route.Visor + route.Server == route.Room -> ServerJoinRequest // if route.Visor + route.Server + route.Room -> RoomRequest func (ms MessengerService) SendRouteRequestMessage(route util.PKRoute) error { @@ -288,41 +355,90 @@ func (ms MessengerService) SendRouteRequestMessage(route util.PKRoute) error { m := message.NewRouteRequestMessage(usr.GetInfo().GetPK(), route) - err = ms.sendMessage(route, m) + err = ms.sendMessage(route, m, true) if err != nil { return err } - //TODO: think about putting this notification in add_chat use case //notify about the added route an := notification.NewAddRouteNotification(route) err = ms.ns.Notify(an) if err != nil { return err } + return nil +} - //notify about sent chat request message - n := notification.NewMsgNotification(route, m) - err = ms.ns.Notify(n) +// SendTextMessage sends a text message to the given route +func (ms MessengerService) SendTextMessage(route util.PKRoute, msg []byte) error { + + usr, err := ms.usrRepo.GetUser() if err != nil { + fmt.Printf("Error getting user from repository: %s", err) return err } + m := message.NewTextMessage(usr.GetInfo().GetPK(), route, msg) + + if m.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(m) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(m) + if err != nil { + return err + } + } + return nil } -// SendTextMessage sends a text message to the given route -//[]: root and destination!! -func (ms MessengerService) SendTextMessage(route util.PKRoute, msg []byte) error { - fmt.Println("MessengerService - SendTextMessage") +// SendAddRoomMessage sends a command message to add a room to the given route +func (ms MessengerService) SendAddRoomMessage(route util.PKRoute, info info.Info) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + bytes, err := json.Marshal(info) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) + + m := message.NewAddRoomMessage(root, route, bytes) + + if m.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(m) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(m) + if err != nil { + return err + } + } + + return nil +} + +// SendDeleteRoomMessage sends a command message to delete a room of the given route +func (ms MessengerService) SendDeleteRoomMessage(route util.PKRoute) error { usr, err := ms.usrRepo.GetUser() if err != nil { fmt.Printf("Error getting user from repository: %s", err) return err } - m := message.NewTextMessage(usr.GetInfo().GetPK(), route, msg) + root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) + + m := message.NewDeleteRoomMessage(root, route) if m.Dest.Visor == usr.GetInfo().GetPK() { err = ms.sendMessageToLocalRoute(m) @@ -341,7 +457,10 @@ func (ms MessengerService) SendTextMessage(route util.PKRoute, msg []byte) error // sendMessageToRemoteRoute sends the given message to a remote route func (ms MessengerService) sendMessageToRemoteRoute(msg message.Message) error { - err := ms.sendMessage(msg.Dest, msg) + //if the message goes to p2p we save it in database, if not we wait for the remote server to send us our message + //this way we can see that the message was received by the remote server + saveInDatabase := (msg.Dest.Visor == msg.Dest.Server) + err := ms.sendMessage(msg.Dest, msg, saveInDatabase) if err != nil { return err } @@ -368,15 +487,16 @@ func (ms MessengerService) sendMessageToLocalRoute(msg message.Message) error { } // SendInfoMessage sends an info message to the given chat and notifies about sent message -func (ms MessengerService) SendInfoMessage(root util.PKRoute, dest util.PKRoute, info info.Info) error { +func (ms MessengerService) SendInfoMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute, info info.Info) error { bytes, err := json.Marshal(info) if err != nil { fmt.Printf("Failed to marshal json: %v", err) + return err } m := message.NewChatInfoMessage(root, dest, bytes) - err = ms.sendMessage(dest, m) + err = ms.sendMessage(pkroute, m, true) if err != nil { return err } @@ -392,9 +512,9 @@ func (ms MessengerService) SendInfoMessage(root util.PKRoute, dest util.PKRoute, } // SendChatAcceptMessage sends an accept-message from the root to the destination -func (ms MessengerService) SendChatAcceptMessage(root util.PKRoute, dest util.PKRoute) error { +func (ms MessengerService) SendChatAcceptMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute) error { m := message.NewChatAcceptMessage(root, dest) - err := ms.sendMessage(dest, m) + err := ms.sendMessage(pkroute, m, true) if err != nil { return err } @@ -411,6 +531,16 @@ func (ms MessengerService) SendChatRejectMessage(root util.PKRoute, dest util.PK return nil } +// SendChatLeaveMessage sends a leave-message from the root to the destination +func (ms MessengerService) SendChatLeaveMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute) error { + m := message.NewChatLeaveMessage(root, dest) + err := ms.sendMessage(pkroute, m, true) + if err != nil { + return err + } + return nil +} + // Listen is used to listen for new incoming connections and pass them to the connection_handle routine func (ms MessengerService) Listen() { pCli, err := ms.cliRepo.GetClient() @@ -424,6 +554,12 @@ func (ms MessengerService) Listen() { return } + go func() { + if err := <-ms.errs; err != nil { + fmt.Printf("Error in go handle function: %s ", err) + } + }() + for { fmt.Println("Accepting skychat conn...") conn, err := l.Accept() @@ -446,11 +582,8 @@ func (ms MessengerService) Listen() { fmt.Println(err) } + //error handling in anonymous go func above go ms.Handle(raddr.PubKey) - if err := <-ms.errs; err != nil { - fmt.Printf("Error in go handle function: %s ", err) - } - } } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go index 74354914a..da9b95ffb 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go @@ -3,6 +3,7 @@ package netcon import ( "encoding/json" "fmt" + "time" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" @@ -15,49 +16,65 @@ import ( // handleLocalServerMessage handles messages received to a local route (server/room) // these can also be locally sent messages from the user to his own local route func (ms MessengerService) handleLocalServerMessage(m message.Message) error { - //first check if the message is of type ConnMsgType - //we need to handle this first, as we first have to accept or reject a message - if m.GetMessageType() == message.ConnMsgType { - err := ms.handleLocalRoomConnMsgType(m) - if err != nil { - return err - } - } + fmt.Println("handleLocalServerMessage") - //if the message is not of type ConnMsgType check if the remote pk is blacklisted - // to prevent a peer from sending other messages before a connection-request message + pkroute := util.NewRoomRoute(m.GetDestinationVisor(), m.GetDestinationServer(), m.GetDestinationRoom()) + + //Check if visor exists visor, err := ms.visorRepo.GetByPK(m.Dest.Visor) if err != nil { return err } + + //Check if server exists server, err := visor.GetServerByPK(m.Dest.Server) if err != nil { return err } - r, err := server.GetRoomByPK(m.Dest.Room) - if err != nil { - return err - } - //save room as local variable - room := *r + //check if the message is of type ConnMsgType + //we need to handle this first, as we first have to accept or reject a message + if m.GetMessageType() == message.ConnMsgType { + err := ms.handleLocalServerConnMsgType(visor, m) + if err != nil { + return err + } + return nil + } - //the root route of this server (== the Destination of the message) - root := m.Dest + //the root route of this server + root := pkroute //the destination route of a message to send back to the root dest := m.Root - //check if in blacklist of server //TODO: or not a member !! add always local as member + //check if origin of message is a member or in blacklist of server //TODO: or not a member !! add always local as member if _, ok := server.GetBlacklist()[m.Root.Visor]; ok { err = ms.SendChatRejectMessage(root, dest) if err != nil { + //?:Maybe better continue than throwing an error as we don't care if the sending didnt work? return err } + //? Maybe better continue and log the event? return fmt.Errorf("Message rejected from " + m.Root.Visor.String()) } - //check if in blacklist of room //TODO: or ot a member - if _, ok := room.GetBlacklist()[m.Root.Visor]; ok { + //handle Command Messages + if m.GetMessageType() == message.CmdMsgType { + err := ms.handleLocalServerCmdMsgType(visor, m) + if err != nil { + return err + } + return nil + } + + //Check if room exists + r, err := server.GetRoomByPK(pkroute.Room) + if err != nil { + return err + } + + //check if origin of message is member or in blacklist of room //TODO: or not a member + if _, ok := r.GetBlacklist()[m.Root.Visor]; ok { err = ms.SendChatRejectMessage(root, dest) if err != nil { return err @@ -65,44 +82,23 @@ func (ms MessengerService) handleLocalServerMessage(m message.Message) error { return fmt.Errorf("Message rejected from " + m.Root.Visor.String()) } - //check if in muted of server - //TODO: - //check if in muted of room - //TODO: - //now we can handle all other message-types switch m.GetMessageType() { case message.InfoMsgType: - //add the message to the room and update server, visor & repository - room.AddMessage(m) - err = server.SetRoom(room) - if err != nil { - return err - } - err = visor.SetServer(*server) - if err != nil { - return err - } + //add the message to the visor and update repository + visor.AddMessage(pkroute, m) err = ms.visorRepo.Set(*visor) if err != nil { return err } //handle the message - err = ms.handleLocalRoomInfoMsgType(visor, m) + err = ms.handleLocalServerInfoMsgType(visor, m) if err != nil { fmt.Println(err) } case message.TxtMsgType: - //add the message to the room and update server, visor & repository - room.AddMessage(m) - err = server.SetRoom(room) - if err != nil { - return err - } - err = visor.SetServer(*server) - if err != nil { - return err - } + //add the message to the visor and update repository + visor.AddMessage(pkroute, m) err = ms.visorRepo.Set(*visor) if err != nil { return err @@ -112,8 +108,6 @@ func (ms MessengerService) handleLocalServerMessage(m message.Message) error { if err != nil { return err } - case message.CmdMsgType: - return fmt.Errorf("commands are not allowed on p2p chats") default: return fmt.Errorf("incorrect data received") @@ -121,13 +115,13 @@ func (ms MessengerService) handleLocalServerMessage(m message.Message) error { return nil } -// handleRoomConnMsgType handles an incoming connection message and either accepts it and sends back the own info as message +// handleLocalServerConnMsgType handles an incoming connection message and either accepts it and sends back the own info as message // or if the public key is in the blacklist rejects the chat request. -func (ms MessengerService) handleLocalRoomConnMsgType(m message.Message) error { - visor, err := ms.visorRepo.GetByPK(m.Dest.Visor) - if err != nil { - return err - } +func (ms MessengerService) handleLocalServerConnMsgType(visor *chat.Visor, m message.Message) error { + fmt.Println("handleLocalServerConnMsgType") + + pkroute := util.NewRoomRoute(m.GetDestinationVisor(), m.GetDestinationServer(), m.GetDestinationRoom()) + server, err := visor.GetServerByPK(m.Dest.Server) if err != nil { return err @@ -137,11 +131,8 @@ func (ms MessengerService) handleLocalRoomConnMsgType(m message.Message) error { return err } - //save room as local variable - room := *r - //the root route of this server (== the Destination of the message) - root := m.Dest + root := pkroute //the destination route of a message to send back to the root dest := m.Root @@ -149,38 +140,31 @@ func (ms MessengerService) handleLocalRoomConnMsgType(m message.Message) error { case message.ConnMsgTypeRequest: //check if sender is in blacklist, if not send accept and info messages back, else send reject message if _, ok := server.GetBlacklist()[m.Root.Visor]; !ok { - if _, ok2 := room.GetBlacklist()[m.Root.Visor]; !ok2 { + if _, ok2 := r.GetBlacklist()[m.Root.Visor]; !ok2 { - //TODO: Add chat request message to room + //add request message to room + r.AddMessage(m) - //send a chat-accept-message to the remote peer - err = ms.SendChatAcceptMessage(root, dest) - if err != nil { - return err - } - - //send the rooms info to the remote peer - err = ms.SendInfoMessage(root, dest, room.GetInfo()) - if err != nil { - return err - } + //send request message to peers + ms.sendMessageToPeers(visor, m) //add remote peer to members so he is able to send other messages than connMsgType info := info.NewDefaultInfo() info.Pk = m.Root.Visor dummyPeer := peer.NewPeer(info, "") - //add remote peer to room - err = room.AddMember(*dummyPeer) + + //add remote peer to server + err = server.AddMember(*dummyPeer) if err != nil { return err } - //update room inside server - err = server.SetRoom(room) + //add remote peer to room + err = r.AddMember(*dummyPeer) if err != nil { return err } - //add remote peer to server - err = server.AddMember(*dummyPeer) + //update room inside server + err = server.SetRoom(*r) if err != nil { return err } @@ -189,15 +173,36 @@ func (ms MessengerService) handleLocalRoomConnMsgType(m message.Message) error { if err != nil { return err } - //update visor inside repository + //update visorRepo err = ms.visorRepo.Set(*visor) if err != nil { return err } - //TODO: send new member-list to members + //notify about a new messages/infos inside a group chat + n := notification.NewGroupChatNotification(pkroute) + err = ms.ns.Notify(n) + if err != nil { + return err + } - //TODO: notify about new member + //send a chat-accept-message to the remote peer + err = ms.SendChatAcceptMessage(pkroute, root, dest) + if err != nil { + return err + } + + //!! FIXME + //This sleep is necessary, as it looks like the transport hangs up when sending two messages in a short time frame + time.Sleep(1 * time.Second) + + //send the rooms info to the remote peer + err = ms.SendInfoMessage(pkroute, root, dest, r.GetInfo()) + if err != nil { + return err + } + + //TODO: send new member-list to members } else { //sends a chat-reject-message to the remote peer @@ -223,28 +228,125 @@ func (ms MessengerService) handleLocalRoomConnMsgType(m message.Message) error { return nil } -// handleLocalRoomInfoMsgType handles messages of type info of peers -func (ms MessengerService) handleLocalRoomInfoMsgType(v *chat.Visor, m message.Message) error { +// handleLocalServerCmdMsgType handles messages of type cmd of peers(admins/moderators) +func (ms MessengerService) handleLocalServerCmdMsgType(visor *chat.Visor, m message.Message) error { + fmt.Println("handleLocalServerCmdMsgType") + + pkroute := util.NewRoomRoute(m.GetDestinationVisor(), m.GetDestinationServer(), m.GetDestinationRoom()) + + //check if server exists + server, err := visor.GetServerByPK(m.Dest.Server) + if err != nil { + return err + } + + //get user + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + //unmarshal the received message bytes to info.Info + i := info.Info{} + err = json.Unmarshal(m.Message, &i) + if err != nil { + return fmt.Errorf("failed to unmarshal json message: %v", err) + } + + switch m.MsgSubtype { + case message.CmdMsgTypeAddRoom: + //TODO: First check if origin of msg is admin + // make a new route + rr := util.NewLocalRoomRoute(m.Dest.Visor, m.Dest.Server, server.GetAllRoomsBoolMap()) + + // setup room for repository + r := chat.NewLocalRoom(rr, i, chat.DefaultRoomType) + + //setup user as peer for room membership + p := peer.NewPeer(*usr.GetInfo(), usr.GetInfo().Alias) + //Add user as member + err = r.AddMember(*p) + if err != nil { + return err + } + + //TODO:: if room is visible/public also add messengerService and send 'Room-Added' Message to Members of server + + // add room to server, update visor and then update repository + err = server.AddRoom(r) + if err != nil { + return err + } + err = visor.SetServer(*server) + if err != nil { + return err + } + + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + + //notify about the added route + n := notification.NewAddRouteNotification(pkroute) + err = ms.ns.Notify(n) + if err != nil { + return err + } + return nil + case message.CmdMsgTypeDeleteRoom: + //TODO: First check if origin of msg is admin + //TODO: handle message + return nil + //TODO: add other cmd messages + default: + return fmt.Errorf("incorrect data received") + } +} + +// handleLocalServerInfoMsgType handles messages of type info of peers +func (ms MessengerService) handleLocalServerInfoMsgType(v *chat.Visor, m message.Message) error { + fmt.Println("handleLocalServerInfoMsgType") + + pkroute := util.NewRoomRoute(m.GetDestinationVisor(), m.GetDestinationServer(), m.GetDestinationRoom()) + //unmarshal the received message bytes to info.Info i := info.Info{} err := json.Unmarshal(m.Message, &i) if err != nil { return fmt.Errorf("failed to unmarshal json message: %v", err) } - s, err := v.GetServerByPK(m.GetDestinationServer()) + fmt.Println("---------------------------------------------------------------------------------------------------") + fmt.Printf("InfoMessage: \n") + fmt.Printf("Pk: %s \n", i.Pk.Hex()) + fmt.Printf("Alias: %s \n", i.Alias) + fmt.Printf("Desc: %s \n", i.Desc) + fmt.Printf("Img: %s \n", i.Img) + fmt.Println("---------------------------------------------------------------------------------------------------") + + //get server from visor + s, err := v.GetServerByPK(pkroute.Server) if err != nil { return err } //update the info of the member in the server and all rooms - s.SetMemberInfo(i) + err = s.SetMemberInfo(i) + if err != nil { + return err + } + err = v.SetServer(*s) + if err != nil { + return err + } err = ms.visorRepo.Set(*v) if err != nil { return err } //notify about new info message - n := notification.NewMsgNotification(util.NewP2PRoute(v.GetPK()), m) + n := notification.NewMsgNotification(pkroute, m) err = ms.ns.Notify(n) if err != nil { return err @@ -256,16 +358,63 @@ func (ms MessengerService) handleLocalRoomInfoMsgType(v *chat.Visor, m message.M } // handleLocalRoomTextMstType handles messages of type text of the p2p chat -func (ms MessengerService) handleLocalRoomTextMsgType(c *chat.Visor, m message.Message) error { +func (ms MessengerService) handleLocalRoomTextMsgType(v *chat.Visor, m message.Message) error { + fmt.Println("handleLocalRoomTextMsgType") + + pkroute := util.NewRoomRoute(m.GetDestinationVisor(), m.GetDestinationServer(), m.GetDestinationRoom()) + + //check if in muted of server + //TODO: + //check if in muted of room + //TODO: //notify about a new TextMessage - n := notification.NewMsgNotification(util.NewP2PRoute(c.GetPK()), message.NewTextMessage(m.Root.Visor, m.Dest, m.Message)) + n := notification.NewMsgNotification(pkroute, m) err := ms.ns.Notify(n) if err != nil { return err } - //TODO: send message to all members + err = ms.sendMessageToPeers(v, m) + if err != nil { + return err + } + + return nil +} + +// +func (ms MessengerService) sendMessageToPeers(v *chat.Visor, m message.Message) error { + fmt.Println("sendMessageToPeers") + pkroute := util.NewRoomRoute(m.GetDestinationVisor(), m.GetDestinationServer(), m.GetDestinationRoom()) + + server, err := v.GetServerByPK(m.Dest.Server) + if err != nil { + return err + } + + r, err := server.GetRoomByPK(m.Dest.Room) + if err != nil { + return err + } + + members := r.GetAllMembers() + + for _, peer := range members { + + //only send to remote peers and not to ourself + if peer.GetPK() != pkroute.Visor { + + m.Root = pkroute + m.Dest = util.NewP2PRoute(peer.GetPK()) + + err := ms.sendMessage(pkroute, m, false) + if err != nil { + fmt.Printf("error sending group message to peer: %v", err) + continue + } + } + } return nil } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go index 8d79db64a..3bfb3ff5c 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go @@ -3,6 +3,7 @@ package netcon import ( "encoding/json" "fmt" + "time" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" @@ -11,8 +12,11 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) -// handleP2PMessage handles messages sent as direct message +// handleP2PMessage handles messages received as direct message func (ms MessengerService) handleP2PMessage(m message.Message) error { + fmt.Println("handleP2PMessage") + + pkroute := util.NewP2PRoute(m.Root.Visor) //first check if the message is of type ConnMsgType //we need to handle this first, as we first have to accept or reject a message @@ -21,6 +25,7 @@ func (ms MessengerService) handleP2PMessage(m message.Message) error { if err != nil { return err } + return nil } //if the message is not of type ConnMsgType check if the remote pk is blacklisted // to prevent a peer from sending other messages before a connection-request message @@ -32,9 +37,9 @@ func (ms MessengerService) handleP2PMessage(m message.Message) error { //the p2p route of the user root := util.NewP2PRoute(usr.GetInfo().GetPK()) //the p2p route of the peer - dest := util.NewP2PRoute(m.Root.Visor) + dest := pkroute - if usr.GetSettings().InBlacklist(m.Root.Visor) { + if usr.GetSettings().InBlacklist(pkroute.Visor) { err = ms.SendChatRejectMessage(root, dest) if err != nil { return err @@ -47,20 +52,12 @@ func (ms MessengerService) handleP2PMessage(m message.Message) error { if err != nil { return err } - p2p, err := visor.GetP2P() - if err != nil { - return err - } //now we can handle all other message-types switch m.GetMessageType() { case message.InfoMsgType: //add the message to the p2p chat and update visor & repository - p2p.AddMessage(m) - err = visor.SetP2P(p2p) - if err != nil { - return err - } + visor.AddMessage(pkroute, m) err = ms.visorRepo.Set(*visor) if err != nil { return err @@ -72,11 +69,7 @@ func (ms MessengerService) handleP2PMessage(m message.Message) error { } case message.TxtMsgType: //add the message to the p2p chat and update visor & repository - p2p.AddMessage(m) - err = visor.SetP2P(p2p) - if err != nil { - return err - } + visor.AddMessage(pkroute, m) err = ms.visorRepo.Set(*visor) if err != nil { return err @@ -98,6 +91,10 @@ func (ms MessengerService) handleP2PMessage(m message.Message) error { // handleP2PConnMsgType handles an incoming connection message and either accepts it and sends back the own info as message // or if the public key is in the blacklist rejects the chat request. func (ms MessengerService) handleP2PConnMsgType(m message.Message) error { + fmt.Println("handleP2PConnMsgType") + + pkroute := util.NewP2PRoute(m.Root.Visor) + usr, err := ms.usrRepo.GetUser() if err != nil { return err @@ -106,36 +103,64 @@ func (ms MessengerService) handleP2PConnMsgType(m message.Message) error { //the p2p route of the user root := util.NewP2PRoute(usr.GetInfo().GetPK()) //the p2p route of the peer - dest := util.NewP2PRoute(m.Root.Visor) + dest := pkroute switch m.MsgSubtype { case message.ConnMsgTypeRequest: //check if sender is in blacklist, if not send accetp and info messages back, else send reject message - if !usr.GetSettings().InBlacklist(m.Root.Visor) { - //make new default visor with a default p2p-room and save it in the visor repository - v := chat.NewDefaultP2PVisor(m.Root.Visor) - err = ms.visorRepo.Add(v) + if !usr.GetSettings().InBlacklist(pkroute.Visor) { + // check if visor exists in repository -> it is possible that we already have got the peer visor saved as a host of a server + v, err := ms.visorRepo.GetByPK(pkroute.Visor) if err != nil { - return err + //make new default visor with a default p2p-room and save it in the visor repository + fmt.Println("Make new P2P visor") + v2 := chat.NewDefaultP2PVisor(pkroute.Visor) + err = ms.visorRepo.Add(v2) + if err != nil { + return err + } + v = &v2 } - //TODO: Add request message to p2p + //check if p2p already exists in repository + _, err = v.GetP2P() + if err != nil { + //make new default p2p room and add it to the visor + fmt.Println("Make new P2P room") + p2p := chat.NewDefaultP2PRoom(pkroute.Visor) + err = v.AddP2P(p2p) + if err != nil { + return err + } + } + + //add request message to p2p + v.AddMessage(pkroute, m) + //update repo with visor + err = ms.visorRepo.Set(*v) + if err != nil { + return err + } //notify about the new chat initiated by a remote visor - n := notification.NewChatNotification(m.Root.Visor) + n := notification.NewP2PChatNotification(pkroute.Visor) err = ms.ns.Notify(n) if err != nil { return err } - //sends a chat-accept-message to the remote peer - err = ms.SendChatAcceptMessage(root, dest) + //send a chat-accept-message to the remote peer + err = ms.SendChatAcceptMessage(pkroute, root, dest) if err != nil { return err } - //sends the users info to the remote peer - err = ms.SendInfoMessage(root, dest, *usr.GetInfo()) + //!! FIXME + //This sleep is necessary, as it looks like the transport hangs up when sending two messages in a short time frame + time.Sleep(1 * time.Second) + + //send the users info to the remote peer + err = ms.SendInfoMessage(pkroute, root, dest, *usr.GetInfo()) if err != nil { return err } @@ -146,32 +171,48 @@ func (ms MessengerService) handleP2PConnMsgType(m message.Message) error { if err != nil { return err } + //TODO: !! we first have to check whether we don't have got servers of this visor saved //deletes the visor from the repository - err = ms.visorRepo.Delete(m.Root.Visor) + err = ms.visorRepo.Delete(pkroute.Visor) if err != nil { return err } return fmt.Errorf("pk in blacklist rejected") } case message.ConnMsgTypeAccept: + //get the visor + v, err := ms.visorRepo.GetByPK(pkroute.Visor) + if err != nil { + return err + } + + //add request message to visor route + v.AddMessage(pkroute, m) + err = ms.visorRepo.Set(*v) + if err != nil { + return err + } + //notify that we received an accept message - n := notification.NewMsgNotification(m.Root, m) + n := notification.NewMsgNotification(pkroute, m) err = ms.ns.Notify(n) if err != nil { return err } //as the peer has accepted the chat request we now can send our info - err = ms.SendInfoMessage(root, dest, *usr.GetInfo()) + err = ms.SendInfoMessage(pkroute, root, dest, *usr.GetInfo()) if err != nil { return err } case message.ConnMsgTypeReject: - n := notification.NewMsgNotification(m.Root, m) + n := notification.NewMsgNotification(pkroute, m) err = ms.ns.Notify(n) if err != nil { return err } + case message.ConnMsgTypeLeave: + return fmt.Errorf("commands are not allowed on p2p chats") default: return fmt.Errorf("incorrect data received") } @@ -181,12 +222,24 @@ func (ms MessengerService) handleP2PConnMsgType(m message.Message) error { // handleP2PInfoMsgType handles messages of type info of the p2p chat func (ms MessengerService) handleP2PInfoMsgType(v *chat.Visor, m message.Message) error { + fmt.Println("handleP2PInfoMsgType") + + pkroute := util.NewP2PRoute(m.Root.Visor) + //unmarshal the received message bytes to info.Info i := info.Info{} err := json.Unmarshal(m.Message, &i) if err != nil { return fmt.Errorf("failed to unmarshal json message: %v", err) } + fmt.Println("---------------------------------------------------------------------------------------------------") + fmt.Printf("InfoMessage: \n") + fmt.Printf("Pk: %s \n", i.Pk.Hex()) + fmt.Printf("Alias: %s \n", i.Alias) + fmt.Printf("Desc: %s \n", i.Desc) + fmt.Printf("Img: %s \n", i.Img) + fmt.Println("---------------------------------------------------------------------------------------------------") + //update the info of the p2p v.P2P.Info = i err = ms.visorRepo.Set(*v) @@ -195,7 +248,7 @@ func (ms MessengerService) handleP2PInfoMsgType(v *chat.Visor, m message.Message } //notify about new info message - n := notification.NewMsgNotification(util.NewP2PRoute(v.GetPK()), m) + n := notification.NewMsgNotification(pkroute, m) err = ms.ns.Notify(n) if err != nil { return err @@ -206,9 +259,17 @@ func (ms MessengerService) handleP2PInfoMsgType(v *chat.Visor, m message.Message // handleP2PTextMstType handles messages of type text of the p2p chat func (ms MessengerService) handleP2PTextMsgType(c *chat.Visor, m message.Message) error { + fmt.Println("handleP2PTextMsgType") + + pkroute := util.NewP2PRoute(m.Root.Visor) + + fmt.Println("---------------------------------------------------------------------------------------------------") + fmt.Printf("TextMessage: \n") + fmt.Printf("Text: %s \n", m.Message) + fmt.Println("---------------------------------------------------------------------------------------------------") //notify about a new TextMessage - n := notification.NewMsgNotification(util.NewP2PRoute(c.GetPK()), message.NewTextMessage(m.Root.Visor, m.Dest, m.Message)) + n := notification.NewMsgNotification(pkroute, m) err := ms.ns.Notify(n) if err != nil { return err diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go index e8b0b0c6b..4efc6f42a 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go @@ -13,36 +13,21 @@ import ( // handleRemoteServerMessage handles all messages from a remote server/room func (ms MessengerService) handleRemoteServerMessage(m message.Message) error { + fmt.Println("handleRemoteServerMessage") + + pkroute := util.NewRoomRoute(m.GetRootVisor(), m.GetRootServer(), m.GetRootRoom()) + //TODO: check if we are member -> if not ignore message - visor, err := ms.visorRepo.GetByPK(m.Dest.Visor) - if err != nil { - return err - } - server, err := visor.GetServerByPK(m.Dest.Server) - if err != nil { - return err - } - r, err := server.GetRoomByPK(m.Dest.Room) + visor, err := ms.visorRepo.GetByPK(m.Root.Visor) if err != nil { return err } - //save room as local variable - room := *r - switch m.GetMessageType() { case message.ConnMsgType: - //add the message to the room and update server, visor & repository - room.AddMessage(m) - err = server.SetRoom(room) - if err != nil { - return err - } - err = visor.SetServer(*server) - if err != nil { - return err - } + //add the message to the visor and update repository + visor.AddMessage(pkroute, m) err = ms.visorRepo.Set(*visor) if err != nil { return err @@ -53,16 +38,8 @@ func (ms MessengerService) handleRemoteServerMessage(m message.Message) error { fmt.Println(err) } case message.InfoMsgType: - //add the message to the room and update server, visor & repository - room.AddMessage(m) - err = server.SetRoom(room) - if err != nil { - return err - } - err = visor.SetServer(*server) - if err != nil { - return err - } + //add the message to the visor and update repository + visor.AddMessage(pkroute, m) err = ms.visorRepo.Set(*visor) if err != nil { return err @@ -73,16 +50,8 @@ func (ms MessengerService) handleRemoteServerMessage(m message.Message) error { fmt.Println(err) } case message.TxtMsgType: - //add the message to the room and update server, visor & repository - room.AddMessage(m) - err = server.SetRoom(room) - if err != nil { - return err - } - err = visor.SetServer(*server) - if err != nil { - return err - } + //add the message to the visor and update repository + visor.AddMessage(pkroute, m) err = ms.visorRepo.Set(*visor) if err != nil { return err @@ -103,6 +72,9 @@ func (ms MessengerService) handleRemoteServerMessage(m message.Message) error { // handleRemoteRoomConnMsgType handles all messages of type ConnMsgtype of remote servers func (ms MessengerService) handleRemoteRoomConnMsgType(m message.Message) error { + fmt.Println("handleRemoteRoomConnMsgType") + + pkroute := util.NewRoomRoute(m.GetRootVisor(), m.GetRootServer(), m.GetRootRoom()) //Get user to get the info user, err := ms.usrRepo.GetUser() @@ -110,10 +82,10 @@ func (ms MessengerService) handleRemoteRoomConnMsgType(m message.Message) error return err } - //the root route of this server (== the Destination of the message) - root := m.Dest + //the root route of this user + root := util.NewP2PRoute(user.GetInfo().GetPK()) //the destination route of a message to send back to the root - dest := m.Root + dest := pkroute switch m.MsgSubtype { case message.ConnMsgTypeAccept: @@ -124,7 +96,7 @@ func (ms MessengerService) handleRemoteRoomConnMsgType(m message.Message) error return err } //as the remote route has accepted the chat request we now can send our info - err = ms.SendInfoMessage(root, dest, *user.GetInfo()) + err = ms.SendInfoMessage(pkroute, root, dest, *user.GetInfo()) if err != nil { return err } @@ -147,26 +119,52 @@ func (ms MessengerService) handleRemoteRoomConnMsgType(m message.Message) error // handleRemoteRoomInfoMsgType handles messages of type info of peers func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message.Message) error { + fmt.Println("handleRemoteRoomInfoMsgType") //unmarshal the received message bytes to info.Info i := info.Info{} err := json.Unmarshal(m.Message, &i) if err != nil { return fmt.Errorf("failed to unmarshal json message: %v", err) } - s, err := v.GetServerByPK(m.GetDestinationServer()) + fmt.Println("---------------------------------------------------------------------------------------------------") + fmt.Printf("InfoMessage: \n") + fmt.Printf("Pk: %s \n", i.Pk.Hex()) + fmt.Printf("Alias: %s \n", i.Alias) + fmt.Printf("Desc: %s \n", i.Desc) + fmt.Printf("Img: %s \n", i.Img) + fmt.Println("---------------------------------------------------------------------------------------------------") + + //TODO: ?? Put something like SetRoomInfo into visor as method so only a call of visor.SetRoomInfo etc. is needed everywhere and not getting server and then getting room?? + //get server from visor + s, err := v.GetServerByPK(m.GetRootServer()) + if err != nil { + return err + } + + //get room from server + r, err := s.GetRoomByPK(m.GetRootRoom()) + if err != nil { + return err + } + + //update the info of the remote server + r.SetInfo(i) //TODO: return error? + err = s.SetRoom(*r) + if err != nil { + return err + } + err = v.SetServer(*s) if err != nil { return err } - //update the info of the member in the server and all rooms - s.SetMemberInfo(i) err = ms.visorRepo.Set(*v) if err != nil { return err } //notify about new info message - n := notification.NewMsgNotification(util.NewP2PRoute(v.GetPK()), m) + n := notification.NewMsgNotification(m.Root, m) err = ms.ns.Notify(n) if err != nil { return err @@ -177,6 +175,12 @@ func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message. // handleRemoteRoomTextMstType handles messages of type text of the remote chat func (ms MessengerService) handleRemoteRoomTextMsgType(c *chat.Visor, m message.Message) error { + fmt.Println("handleRemoteRoomTextMsgType") + + fmt.Println("---------------------------------------------------------------------------------------------------") + fmt.Printf("TextMessage: \n") + fmt.Printf("Text: %s \n", m.Message) + fmt.Println("---------------------------------------------------------------------------------------------------") //notify about a new TextMessage n := notification.NewMsgNotification(util.NewP2PRoute(c.GetPK()), message.NewTextMessage(m.Root.Visor, m.Dest, m.Message)) diff --git a/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go b/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go index 575a3f5db..ebe27ce58 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go @@ -3,6 +3,7 @@ package channel import ( "encoding/json" + "fmt" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" ) @@ -15,7 +16,6 @@ type NotificationService struct { // NewNotificationService constructor for NotificationService func NewNotificationService() *NotificationService { n := NotificationService{} - //n.notifCh = make(chan string) return &n } @@ -26,12 +26,13 @@ func (ns *NotificationService) Notify(notification notification.Notification) er if err != nil { return err } - + fmt.Printf("Notify: \n") + fmt.Printf("%s \n", jsonNotification) ns.GetChannel() <- string(jsonNotification) return nil } -//TODO: +//InitChannel inits the channel with make func (ns *NotificationService) InitChannel() { ns.notifCh = make(chan string) } @@ -41,8 +42,9 @@ func (ns *NotificationService) GetChannel() chan string { return ns.notifCh } -//TODO: +//Defer Channel includes all messages when the channel has to be deferred func (ns *NotificationService) DeferChannel() { close(ns.notifCh) ns.notifCh = nil + fmt.Println("SSE: client connection is closed") } diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go index 0f3c0fe36..3c684b1ea 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go @@ -37,17 +37,14 @@ func (r *UserRepo) NewUser() (user.User, error) { if err != nil { return user.User{}, err } - fmt.Printf("New DefaultUser at %p\n", &r.user) return r.user, nil } // GetUser returns the user func (r *UserRepo) GetUser() (*user.User, error) { - fmt.Printf("user-repo address %p", r) if r.user.IsEmpty() { return nil, fmt.Errorf("user not found") } - fmt.Printf("Get User at %p", &r.user) return &r.user, nil } diff --git a/cmd/apps/skychat/skychat.go b/cmd/apps/skychat/skychat.go index fccc15a4a..ee104fbc8 100644 --- a/cmd/apps/skychat/skychat.go +++ b/cmd/apps/skychat/skychat.go @@ -36,7 +36,7 @@ func main() { // cd .. // mingw32-make build-windows // .\skywire-cli.exe config gen -i -r -o .\skywire-config.json -// .\skywire-visor.exe -c .\skywire-config.json +// .\skywire-visor.exe -c .\skywire-config.json --loglvl debug /* From ae4488fcedfd5ca566e237abd68994990620dffb Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Sun, 5 Feb 2023 21:39:15 +0100 Subject: [PATCH 24/72] commit --- .../app/chat/commands/add_local_room.go | 94 ------------ .../app/chat/commands/add_local_server.go | 14 +- .../app/chat/commands/delete_local_route.go | 66 +++++++++ .../commands/delete_local_server._by_route.go | 51 ------- .../commands/delete_remote_visor_by_pk.go | 93 ------------ .../app/chat/commands/leave_remote_route.go | 95 ++++++++---- .../chat/commands/send_add_room_message.go | 2 +- .../internal/app/chat/commands/todos.go | 51 +++++++ .../app/chat/queries/get_all_visors.go | 3 +- .../app/chat/queries/get_visor_by_pk.go | 2 +- .../skychat/internal/app/chat/services.go | 10 +- .../internal/app/messenger/messenger.go | 12 +- .../internal/app/notification/notification.go | 11 +- cmd/apps/skychat/internal/app/services.go | 2 +- .../internal/app/user/commands/set_info.go | 58 +++++++- .../skychat/internal/app/user/services.go | 5 +- cmd/apps/skychat/internal/domain/chat/room.go | 6 +- .../skychat/internal/domain/chat/server.go | 33 ++++- .../skychat/internal/domain/chat/visor.go | 49 +++++- .../skychat/internal/domain/client/client.go | 18 ++- cmd/apps/skychat/internal/domain/info/info.go | 5 +- .../internal/domain/message/message.go | 6 +- .../internal/inputports/http/chat/handler.go | 77 ++++------ .../internal/inputports/http/server.go | 11 +- .../inputports/http/static/index.html | 2 +- .../internal/inputports/http/static/index.js | 33 +++-- .../messenger/netcon/messenger_service.go | 61 +++++--- .../netcon/messenger_service_local_server.go | 140 +++++++++++++----- .../messenger/netcon/messenger_service_p2p.go | 16 +- .../netcon/messenger_service_remote_server.go | 42 +++--- .../notification/http/notification_service.go | 4 +- .../storage/memory/visor_repo.go | 6 - 32 files changed, 585 insertions(+), 493 deletions(-) delete mode 100644 cmd/apps/skychat/internal/app/chat/commands/add_local_room.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go delete mode 100644 cmd/apps/skychat/internal/app/chat/commands/delete_local_server._by_route.go delete mode 100644 cmd/apps/skychat/internal/app/chat/commands/delete_remote_visor_by_pk.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/todos.go diff --git a/cmd/apps/skychat/internal/app/chat/commands/add_local_room.go b/cmd/apps/skychat/internal/app/chat/commands/add_local_room.go deleted file mode 100644 index 3ab231c5b..000000000 --- a/cmd/apps/skychat/internal/app/chat/commands/add_local_room.go +++ /dev/null @@ -1,94 +0,0 @@ -// Package commands contains commands to add a local room -package commands - -import ( - "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" -) - -// AddLocalRoomRequest of AddLocalRoomRequestHandler -type AddLocalRoomRequest struct { - Route util.PKRoute - Info info.Info - Type int -} - -// AddLocalRoomRequestHandler struct that allows handling AddLocalRoomRequest -type AddLocalRoomRequestHandler interface { - Handle(command AddLocalRoomRequest) error -} - -type addLocalRoomRequestHandler struct { - visorRepo chat.Repository - userRepo user.Repository - ns notification.Service -} - -// NewAddLocalRoomRequestHandler Initializes an AddCommandHandler -func NewAddLocalRoomRequestHandler(visorRepo chat.Repository, userRepo user.Repository, ns notification.Service) AddLocalRoomRequestHandler { - return addLocalRoomRequestHandler{visorRepo: visorRepo, userRepo: userRepo, ns: ns} -} - -// Handle Handles the AddLocalRoomRequest -func (h addLocalRoomRequestHandler) Handle(command AddLocalRoomRequest) error { - //Get user - usr, err := h.userRepo.GetUser() - if err != nil { - return err - } - - // Check if visor exists - visor, err := h.visorRepo.GetByPK(command.Route.Visor) - if err != nil { - return err - } - // Check if server exists - server, err := visor.GetServerByPK(command.Route.Server) - if err != nil { - return err - } - - // make a new route - rr := util.NewLocalRoomRoute(command.Route.Visor, command.Route.Server, server.GetAllRoomsBoolMap()) - - // setup room for repository - r := chat.NewLocalRoom(rr, command.Info, command.Type) - - //setup user as peer for room membership - p := peer.NewPeer(*usr.GetInfo(), usr.GetInfo().Alias) - //Add user as member to room - err = r.AddMember(*p) - if err != nil { - return err - } - - //[]: if room is visible/public also add messengerService and send 'Room-Added' Message to Members of server - - // add room to server, update visor and then update repository - err = server.AddRoom(r) - if err != nil { - return err - } - err = visor.SetServer(*server) - if err != nil { - return err - } - - err = h.visorRepo.Set(*visor) - if err != nil { - return err - } - - //notify about sent chat request message - n := notification.NewAddRouteNotification(rr) - err = h.ns.Notify(n) - if err != nil { - return err - } - - return nil -} diff --git a/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go b/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go index 881c97ad6..458bf993d 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go +++ b/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go @@ -12,8 +12,7 @@ import ( // AddLocalServerRequest of AddLocalServerRequestHandler type AddLocalServerRequest struct { - Route util.PKRoute - Info info.Info + Info info.Info } // AddLocalServerRequestHandler struct that allows handling AddLocalServerRequest @@ -40,12 +39,11 @@ func (h addLocalServerRequestHandler) Handle(command AddLocalServerRequest) erro return err } - //TODO: Rewrite so the local visor pk must not be known from requester (-> use userRepo) // Check if local visor exists, if not add the default local visor visor := chat.Visor{} - pVisor, err := h.visorRepo.GetByPK(command.Route.Visor) + pVisor, err := h.visorRepo.GetByPK(usr.GetInfo().GetPK()) if err != nil { - visor = chat.NewUndefinedVisor(command.Route.Visor) + visor = chat.NewUndefinedVisor(usr.GetInfo().GetPK()) err = h.visorRepo.Add(visor) if err != nil { return err @@ -71,11 +69,15 @@ func (h addLocalServerRequestHandler) Handle(command AddLocalServerRequest) erro p := peer.NewPeer(*usr.GetInfo(), usr.GetInfo().Alias) //Add user as member from server - //TODO: maybe also add user as server admin as we are sending all commands to the local server instance like it is a message from remote to only handle message from one point? err = server.AddMember(*p) if err != nil { return err } + //Add user as admin, otherwise we can't send admin command messages to our own server + err = server.AddAdmin(p.GetPK()) + if err != nil { + return err + } //Add user as member from room err = r.AddMember(*p) if err != nil { diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go b/cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go new file mode 100644 index 000000000..89c6056cb --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go @@ -0,0 +1,66 @@ +package commands + +import ( + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// DeleteLocalRouteRequest of DeleteLocalRouteRequestHandler +type DeleteLocalRouteRequest struct { + Route util.PKRoute +} + +// DeleteLocalRouteRequestHandler struct that allows handling DeleteLocalRouteRequest +type DeleteLocalRouteRequestHandler interface { + Handle(command DeleteLocalRouteRequest) error +} + +type deleteLocalRouteRequestHandler struct { + messengerService messenger.Service + visorRepo chat.Repository +} + +// NewDeleteLocalRouteRequestHandler Initializes an AddCommandHandler +func NewDeleteLocalRouteRequestHandler(messengerService messenger.Service, visorRepo chat.Repository) DeleteLocalRouteRequestHandler { + return deleteLocalRouteRequestHandler{messengerService: messengerService, visorRepo: visorRepo} +} + +// Handle Handles the DeleteLocalRouteRequest +func (h deleteLocalRouteRequestHandler) Handle(command DeleteLocalRouteRequest) error { + // Check if visor exists + visor, err := h.visorRepo.GetByPK(command.Route.Visor) + if err != nil { + return err + } + // Check if server exists + server, err := visor.GetServerByPK(command.Route.Server) + if err != nil { + return err + } + + // if this, then we want to delete the whole server + if command.Route.Server == command.Route.Room { + //TODO: Send Room-Delete-Message to Room members in every room? + //TODO: Send Server-Delete-Message to Server members + err = visor.DeleteServer(command.Route.Server) + if err != nil { + return err + } + return h.visorRepo.Set(*visor) + } + + // Check if room exists + _, err = server.GetRoomByPK(command.Route.Room) + if err != nil { + return err + } + + //TODO: Send Room-Delete-Message to Room members (and to server members, if room is public) + err = server.DeleteRoom(command.Route.Room) + if err != nil { + return err + } + + return h.visorRepo.Set(*visor) +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_local_server._by_route.go b/cmd/apps/skychat/internal/app/chat/commands/delete_local_server._by_route.go deleted file mode 100644 index cbdbb08b6..000000000 --- a/cmd/apps/skychat/internal/app/chat/commands/delete_local_server._by_route.go +++ /dev/null @@ -1,51 +0,0 @@ -package commands - -import ( - "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" -) - -// DeleteLocalServerRequest of DeleteLocalServerRequestHandler -type DeleteLocalServerRequest struct { - Route util.PKRoute -} - -// DeleteLocalServerRequestHandler struct that allows handling DeleteLocalServerRequest -type DeleteLocalServerRequestHandler interface { - Handle(command DeleteLocalServerRequest) error -} - -type deleteLocalServerRequestHandler struct { - messengerService messenger.Service - visorRepo chat.Repository -} - -// NewDeleteLocalServerRequestHandler Initializes an AddCommandHandler -func NewDeleteLocalServerRequestHandler(messengerService messenger.Service, visorRepo chat.Repository) DeleteLocalServerRequestHandler { - return deleteLocalServerRequestHandler{messengerService: messengerService, visorRepo: visorRepo} -} - -// Handle Handles the DeleteLocalServerRequest -func (h deleteLocalServerRequestHandler) Handle(command DeleteLocalServerRequest) error { - // Check if visor exists - visor, err := h.visorRepo.GetByPK(command.Route.Visor) - if err != nil { - return err - } - // Check if server exists - _, err = visor.GetServerByPK(command.Route.Server) - if err != nil { - return err - } - - //[]: Send 'Server-Deleted-Message' to Server members - - // Delete server from visor and update repo - err = visor.DeleteServer(command.Route.Server) - if err != nil { - return err - } - - return h.visorRepo.Set(*visor) -} diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_remote_visor_by_pk.go b/cmd/apps/skychat/internal/app/chat/commands/delete_remote_visor_by_pk.go deleted file mode 100644 index d5421f401..000000000 --- a/cmd/apps/skychat/internal/app/chat/commands/delete_remote_visor_by_pk.go +++ /dev/null @@ -1,93 +0,0 @@ -// Package commands contains commands to delete a remote visor -package commands - -import ( - "fmt" - - "github.com/skycoin/skywire-utilities/pkg/cipher" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" -) - -// DeleteRemoteVisorRequest Command Model -type DeleteRemoteVisorRequest struct { - Pk cipher.PubKey -} - -// DeleteRemoteVisorRequestHandler Handler Struct with Dependencies -type DeleteRemoteVisorRequestHandler interface { - Handle(command DeleteRemoteVisorRequest) error -} - -type deleteRemoteVisorRequestHandler struct { - cliRepo client.Repository - messengerService messenger.Service - visorRepo chat.Repository -} - -// NewDeleteRemoteVisorRequestHandler Handler constructor -func NewDeleteRemoteVisorRequestHandler(cliRepo client.Repository, visorRepo chat.Repository, messengerService messenger.Service) DeleteRemoteVisorRequestHandler { - return deleteRemoteVisorRequestHandler{cliRepo: cliRepo, visorRepo: visorRepo, messengerService: messengerService} -} - -// Handle Handles the DeleteRemoteVisorRequest request -func (h deleteRemoteVisorRequestHandler) Handle(command DeleteRemoteVisorRequest) error { - // Check if visor exists - _, err := h.visorRepo.GetByPK(command.Pk) - if err != nil { - return err - } - - pCli, err := h.cliRepo.GetClient() - if err != nil { - fmt.Printf("Error Getting client") - return err - } - - // Send 'Leave-Visor-Message' to remote visor so it can be notified about the deletion - root := util.NewP2PRoute(pCli.GetAppClient().Config().VisorPK) - dest := util.NewP2PRoute(command.Pk) - err = h.messengerService.SendChatLeaveMessage(dest, root, dest) - if err != nil { - return err - } - - //get connection - conn, err := pCli.GetConnByPK(command.Pk) - if err != nil { - fmt.Printf("Error getting connection") - return err - } - - //close connection - err = conn.Close() - if err != nil { - fmt.Printf("Error closing connection") - return err - } - - //delete connection from client - err = pCli.DeleteConn(command.Pk) - if err != nil { - fmt.Printf("Error deleting connection") - return err - } - - //update client in repository - err = h.cliRepo.SetClient(*pCli) - if err != nil { - fmt.Printf("Error updating client") - return err - } - - //delete visor from visor repository - h.visorRepo.Delete(command.Pk) - if err != nil { - fmt.Printf("Error deleting visor") - return err - } - - return nil -} diff --git a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go index 048d53520..0ba54c83b 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go +++ b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go @@ -2,8 +2,11 @@ package commands import ( + "fmt" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) @@ -18,66 +21,94 @@ type LeaveRemoteRouteRequestHandler interface { } type leaveRemoteRouteRequestHandler struct { - messengerService messenger.Service - visorRepo chat.Repository + ms messenger.Service + visorRepo chat.Repository + usrRepo user.Repository } // NewLeaveRemoteRouteRequestHandler Handler constructor -func NewLeaveRemoteRouteRequestHandler(messengerService messenger.Service, visorRepo chat.Repository) LeaveRemoteRouteRequestHandler { - return leaveRemoteRouteRequestHandler{messengerService: messengerService, visorRepo: visorRepo} +func NewLeaveRemoteRouteRequestHandler(ms messenger.Service, visorRepo chat.Repository, usrRepo user.Repository) LeaveRemoteRouteRequestHandler { + return leaveRemoteRouteRequestHandler{ms: ms, visorRepo: visorRepo, usrRepo: usrRepo} } // Handle Handles the LeaveRemoteRouteRequest request func (h leaveRemoteRouteRequestHandler) Handle(command LeaveRemoteRouteRequest) error { - // Check if visor exists - visor, err := h.visorRepo.GetByPK(command.Route.Visor) + usr, err := h.usrRepo.GetUser() if err != nil { + fmt.Printf("Error getting user from repository: %s", err) return err } - // Check if server exists - server, err := visor.GetServerByPK(command.Route.Server) + + // Make sure that we don't leave a room of our own server + if command.Route.Visor == usr.GetInfo().GetPK() { + return fmt.Errorf("cannot leave route of own server") + } + + // Check if visor exists + visor, err := h.visorRepo.GetByPK(command.Route.Visor) if err != nil { return err } - //leave room if the request server and room are the same + // Check if handling p2p room if command.Route.Server == command.Route.Room { - // Check if room exists - _, err = server.GetRoomByPK(command.Route.Room) - if err != nil { - return err + if !visor.P2PIsEmpty() { + err = h.ms.SendLeaveChatMessage(command.Route) + if err != nil { + return err + } + err = visor.DeleteP2P() + if err != nil { + return err + } } - //TODO: Send Leave-Room-Message - - // Delete room from server - err = server.DeleteRoom(command.Route.Room) - if err != nil { - return err + // Check if visor has servers, if not delete visor + if len(visor.GetAllServer()) == 0 { + return h.visorRepo.Delete(command.Route.Visor) } - // Update visor with changed server - err = visor.SetServer(*server) - if err != nil { - return err - } + return h.visorRepo.Set(*visor) + } - //TODO:check if this was the last room of the server, if so maybe also leave server + // Check if server exists + server, err := visor.GetServerByPK(command.Route.Server) + if err != nil { + return err + } - // Update repository with changed visor - return h.visorRepo.Set(*visor) - } else { + // Check if room exists + _, err = server.GetRoomByPK(command.Route.Room) + if err != nil { + return err + } - //TODO: Send Leave-Server-Message + // Send LeaveChatMessage to remote server + err = h.ms.SendLeaveChatMessage(command.Route) + if err != nil { + return err + } + + // Delete room from server + err = server.DeleteRoom(command.Route.Room) + if err != nil { + return err + } - // Delete server from visor + //check if this was the last room of the server + if len(server.GetAllRooms()) == 0 { + //TODO: Send Leave-Server-Message err = visor.DeleteServer(command.Route.Server) if err != nil { return err } + } - // Update repository with changed visor - return h.visorRepo.Set(*visor) + // Check if visor has any other servers or p2p, if not delete visor + if len(visor.GetAllServer()) == 0 && visor.P2PIsEmpty() { + return h.visorRepo.Delete(command.Route.Visor) } + // Update repository with changed visor + return h.visorRepo.Set(*visor) } diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_add_room_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_add_room_message.go index bedd7866d..2a326623b 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/send_add_room_message.go +++ b/cmd/apps/skychat/internal/app/chat/commands/send_add_room_message.go @@ -28,7 +28,7 @@ func NewSendAddRoomMessageRequestHandler(messengerService messenger.Service) Sen return sendAddRoomMessageRequestHandler{messengerService: messengerService} } -// Handle Handles the AddCragRequest +// Handle handles the SendAddRoomMessageRequest func (h sendAddRoomMessageRequestHandler) Handle(command SendAddRoomMessageRequest) error { err := h.messengerService.SendAddRoomMessage(command.Route, command.Info) if err != nil { diff --git a/cmd/apps/skychat/internal/app/chat/commands/todos.go b/cmd/apps/skychat/internal/app/chat/commands/todos.go new file mode 100644 index 000000000..a00a0fccd --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/todos.go @@ -0,0 +1,51 @@ +package commands + +//-to-dos and brain-storming about the future of skychat + +//general +//TODO: database for user and visor repository +//TODO: flags to setup if database or in-memory is used for repositories (data is lost when stoping app) +//--> maybe even a way on setting this up for each chat, so simultaneously persistent chats and "deleteable" chats are possible +//--> how about "self-deleting-messages"? deletes itself after (1hour, 24hour, etc...) +//TODO: cli-interface +//with cli-interface a connection with the systray app would be possible -> notifications about new messages, incoming calls etc. +//TODO: encrypted messages (encrypted sending and encrypted saving on local storage) --> Password for app required + +//general-future +//TODO: voip-channels +//TODO: video-streams +//TODO: sending-fiber via chat, with notification about received payments -> also sending-fiber-requests + +//UI +//TODO:Make UI more beautiful +//TODO:Implement to look into peer-book and set custom aliases +//TODO:Implement to look into server-info, and see all lists (admins, members, etc) + +//? How about a way on customizing the appearance of a group chat and saving the css-data inside the server and sending it to the peers + +//usecases-------------------------------------------- + +//p2p----------------------- + +//server & rooms------------ +//TODO:send_hire_admin_message.go //maybe only allow this action from server-host +//TODO:send_fire_admin_message.go //maybe only allow this action from server-host +//TODO:send_hire_moderator_message.go +//TODO:send_fire_moderator_message.go +//TODO:send_mute_peer_message.go +//TODO:send_unmute_peer_message.go + +//TODO:send_add_room_message.go +//TODO:send_delete_room_message.go +//TODO:send_hide_room_message.go +//TODO:send_unhide_room_message.go +//TODO:send_set_route_info_message.go + +//send_hide_message.go //first a way to edit messages must be implemented +//send_unhide_message.go //first a way to edit messages must be implemented +//send_edit_message.go //first a way to edit messages must be implemented +//send_delete_message.go //first a way to edit messages must be implemented + +//send_invite_message.go //an option to send an invite message to a group which then can be accepted or rejected by the peer + +//transfer_local_server.go //a way to transfer ownership to another visor diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_all_visors.go b/cmd/apps/skychat/internal/app/chat/queries/get_all_visors.go index a4104a5da..2062a2f26 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_all_visors.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_all_visors.go @@ -36,11 +36,12 @@ func (h getAllVisorsRequestHandler) Handle() ([]GetAllVisorsResult, error) { } var result []GetAllVisorsResult for _, visor := range res { + p2p, err := visor.GetP2P() if err != nil { return nil, err } - result = append(result, GetAllVisorsResult{Pk: visor.GetPK(), P2P: p2p, Server: visor.GetAllServer()}) + result = append(result, GetAllVisorsResult{Pk: visor.GetPK(), P2P: *p2p, Server: visor.GetAllServer()}) } return result, nil } diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_visor_by_pk.go b/cmd/apps/skychat/internal/app/chat/queries/get_visor_by_pk.go index 40f8717d4..db912bfa4 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_visor_by_pk.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_visor_by_pk.go @@ -47,7 +47,7 @@ func (h getVisorByPKRequestHandler) Handle(query GetVisorByPKRequest) (GetVisorB return GetVisorByPKResult{}, err } - result = GetVisorByPKResult{Pk: visor.GetPK(), P2P: p2p, Server: visor.GetAllServer()} + result = GetVisorByPKResult{Pk: visor.GetPK(), P2P: *p2p, Server: visor.GetAllServer()} return result, nil } diff --git a/cmd/apps/skychat/internal/app/chat/services.go b/cmd/apps/skychat/internal/app/chat/services.go index 741a49241..610c26857 100644 --- a/cmd/apps/skychat/internal/app/chat/services.go +++ b/cmd/apps/skychat/internal/app/chat/services.go @@ -22,12 +22,10 @@ type Queries struct { // Commands Contains all available command handlers of this app type Commands struct { - AddLocalRoomHandler commands.AddLocalRoomRequestHandler AddLocalServerHandler commands.AddLocalServerRequestHandler JoinRemoteRouteHandler commands.JoinRemoteRouteRequestHandler - DeleteLocalServerHandler commands.DeleteLocalServerRequestHandler + DeleteLocalRouteHandler commands.DeleteLocalRouteRequestHandler LeaveRemoteRouteHandler commands.LeaveRemoteRouteRequestHandler - DeleteRemoteVisorHandler commands.DeleteRemoteVisorRequestHandler SendAddRoomMessageHandler commands.SendAddRoomMessageRequestHandler SendDeleteRoomMessageHandler commands.SendDeleteRoomMessageRequestHandler SendTextMessageHandler commands.SendTextMessageRequestHandler @@ -50,12 +48,10 @@ func NewServices(cliRepo client.Repository, visorRepo chat.Repository, userRepo GetAllMessagesFromRoomHandler: queries.NewGetAllMessagesFromRoomRequestHandler(visorRepo), }, Commands: Commands{ - AddLocalRoomHandler: commands.NewAddLocalRoomRequestHandler(visorRepo, userRepo, ns), AddLocalServerHandler: commands.NewAddLocalServerRequestHandler(visorRepo, userRepo, ns), JoinRemoteRouteHandler: commands.NewJoinRemoteRouteRequestHandler(visorRepo, ms), - DeleteLocalServerHandler: commands.NewDeleteLocalServerRequestHandler(ms, visorRepo), - LeaveRemoteRouteHandler: commands.NewLeaveRemoteRouteRequestHandler(ms, visorRepo), - DeleteRemoteVisorHandler: commands.NewDeleteRemoteVisorRequestHandler(cliRepo, visorRepo, ms), + DeleteLocalRouteHandler: commands.NewDeleteLocalRouteRequestHandler(ms, visorRepo), + LeaveRemoteRouteHandler: commands.NewLeaveRemoteRouteRequestHandler(ms, visorRepo, userRepo), SendAddRoomMessageHandler: commands.NewSendAddRoomMessageRequestHandler(ms), SendDeleteRoomMessageHandler: commands.NewSendDeleteRoomMessageRequestHandler(ms), SendTextMessageHandler: commands.NewSendTextMessageRequestHandler(ms), diff --git a/cmd/apps/skychat/internal/app/messenger/messenger.go b/cmd/apps/skychat/internal/app/messenger/messenger.go index f414d3e75..22ce9b8e5 100644 --- a/cmd/apps/skychat/internal/app/messenger/messenger.go +++ b/cmd/apps/skychat/internal/app/messenger/messenger.go @@ -11,10 +11,14 @@ import ( type Service interface { Handle(pk cipher.PubKey) Listen() - SendTextMessage(route util.PKRoute, msg []byte) error + + //only used as client/p2p SendRouteRequestMessage(route util.PKRoute) error - SendInfoMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute, info info.Info) error - SendChatLeaveMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute) error - SendAddRoomMessage(route util.PKRoute, info info.Info) error + SendLeaveChatMessage(pkroute util.PKRoute) error + + //used as client/p2p and server + SendTextMessage(route util.PKRoute, msg []byte) error SendDeleteRoomMessage(route util.PKRoute) error + SendAddRoomMessage(route util.PKRoute, info info.Info) error + SendInfoMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute, info info.Info) error } diff --git a/cmd/apps/skychat/internal/app/notification/notification.go b/cmd/apps/skychat/internal/app/notification/notification.go index f293947c7..763791f56 100644 --- a/cmd/apps/skychat/internal/app/notification/notification.go +++ b/cmd/apps/skychat/internal/app/notification/notification.go @@ -20,8 +20,8 @@ const ( //NewMsgNotifyType notifies about new message NewMsgNotifyType //DeleteChatNotifyType notifies about a deleted chat - //DeleteChatNotifyType - //TODO: add SentMsgNotifyType + DeleteChatNotifyType + //? add SentMsgNotifyType ) // Notification provides a struct to send messages via the Service @@ -32,13 +32,6 @@ type Notification struct { // NewMsgNotification notifies the user of a new message func NewMsgNotification(route util.PKRoute, msg message.Message) Notification { - /*Msg, err := json.Marshal(message.NewJSONMessage(msg)) - if err != nil { - fmt.Printf("Failed to marshal json: %v", err) - } - - clientMsg, err := json.Marshal(map[string]string{"visorpk": route.Visor.Hex(), "serverpk": route.Server.Hex(), "roompk": route.Room.Hex(), "message": string(Msg)}) - */ clientMsg, err := json.Marshal(map[string]string{"visorpk": route.Visor.Hex(), "serverpk": route.Server.Hex(), "roompk": route.Room.Hex()}) if err != nil { diff --git a/cmd/apps/skychat/internal/app/services.go b/cmd/apps/skychat/internal/app/services.go index 080055286..739801690 100644 --- a/cmd/apps/skychat/internal/app/services.go +++ b/cmd/apps/skychat/internal/app/services.go @@ -23,5 +23,5 @@ func NewServices(cliRepo client.Repository, usrRepo user.Repository, visorRepo c return Services{ NotificationService: notifyService, ChatServices: chatservices.NewServices(cliRepo, visorRepo, usrRepo, ms, notifyService), - UserServices: userservices.NewServices(usrRepo, ms)} + UserServices: userservices.NewServices(usrRepo, ms, visorRepo)} } diff --git a/cmd/apps/skychat/internal/app/user/commands/set_info.go b/cmd/apps/skychat/internal/app/user/commands/set_info.go index 85a0054f7..6fa5210c3 100644 --- a/cmd/apps/skychat/internal/app/user/commands/set_info.go +++ b/cmd/apps/skychat/internal/app/user/commands/set_info.go @@ -5,8 +5,10 @@ import ( "errors" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) // SetInfoRequest of SetInfoRequestHandler @@ -22,13 +24,14 @@ type SetInfoRequestHandler interface { } type setInfoRequestHandler struct { - messengerService messenger.Service - usrRepo user.Repository + ms messenger.Service + usrRepo user.Repository + visorRepo chat.Repository } // NewSetInfoRequestHandler Initializes an SetInfoHandler -func NewSetInfoRequestHandler(messengerService messenger.Service, usrRepo user.Repository) SetInfoRequestHandler { - return setInfoRequestHandler{messengerService: messengerService, usrRepo: usrRepo} +func NewSetInfoRequestHandler(ms messenger.Service, usrRepo user.Repository, visorRepo chat.Repository) SetInfoRequestHandler { + return setInfoRequestHandler{ms: ms, usrRepo: usrRepo, visorRepo: visorRepo} } // Handle Handles the SetInfoRequest @@ -43,10 +46,51 @@ func (h setInfoRequestHandler) Handle(req SetInfoRequest) error { pUsr.SetInfo(i) - //TODO:Send info to peers and servers that the info was updated //get all visors - //for each visor get all servers and p2p - //send info to them + visors, err := h.visorRepo.GetAll() + if err != nil { + return err + } + + //TODO: send info only to visors and visor then handles the info message to update all of its servers etc. where originator is member of (much less messages to send) + //send info message to each pkroute we know + for _, visor := range visors { + + //send the users info to p2p if it is not empty + if !visor.P2PIsEmpty() { + root := util.NewP2PRoute(pUsr.GetInfo().Pk) + + p2p, err := visor.GetP2P() + if err != nil { + return err + } + + dest := p2p.GetPKRoute() + + err = h.ms.SendInfoMessage(dest, root, dest, *pUsr.GetInfo()) + if err != nil { + return err + } + } + servers := visor.GetAllServer() + + for _, server := range servers { + + rooms := server.GetAllRooms() + + for _, room := range rooms { + //send the users info to the remote or local route + root := util.NewP2PRoute(pUsr.GetInfo().Pk) + dest := room.PKRoute + + err = h.ms.SendInfoMessage(room.PKRoute, root, dest, *pUsr.GetInfo()) + if err != nil { + return err + } + } + + } + } return h.usrRepo.SetUser(pUsr) } diff --git a/cmd/apps/skychat/internal/app/user/services.go b/cmd/apps/skychat/internal/app/user/services.go index d2de74824..76a1f03fe 100644 --- a/cmd/apps/skychat/internal/app/user/services.go +++ b/cmd/apps/skychat/internal/app/user/services.go @@ -5,6 +5,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/user/commands" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/user/queries" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) @@ -31,7 +32,7 @@ type UserServices struct { } // NewServices Bootstraps Application Layer dependencies -func NewServices(usrRepo user.Repository, ms messenger.Service) UserServices { +func NewServices(usrRepo user.Repository, ms messenger.Service, visorRepo chat.Repository) UserServices { return UserServices{ Queries: Queries{ GetUserPeerBookHandler: queries.NewGetUserPeerbookRequestHandler(usrRepo), @@ -42,7 +43,7 @@ func NewServices(usrRepo user.Repository, ms messenger.Service) UserServices { AddPeerHandler: commands.NewAddPeerRequestHandler(usrRepo), DeletePeerHandler: commands.NewDeletePeerRequestHandler(usrRepo), SetPeerHandler: commands.NewSetPeerRequestHandler(usrRepo), - SetInfoHandler: commands.NewSetInfoRequestHandler(ms, usrRepo), + SetInfoHandler: commands.NewSetInfoRequestHandler(ms, usrRepo, visorRepo), SetSettingsHandler: commands.NewSetSettingsRequestHandler(usrRepo), }, } diff --git a/cmd/apps/skychat/internal/domain/chat/room.go b/cmd/apps/skychat/internal/domain/chat/room.go index 65596bdee..619cdd338 100644 --- a/cmd/apps/skychat/internal/domain/chat/room.go +++ b/cmd/apps/skychat/internal/domain/chat/room.go @@ -18,11 +18,12 @@ const ( // ChatRoomType is used to define as chat room ChatRoomType // BoardRoomType is used to define as board - BoardRoomType + //BoardRoomType // VoiceRoomType is used to define as voice chat // VoiceRoom ) +// DefaultRoomType defines the default room type const DefaultRoomType = ChatRoomType // Room defines a room that can be of different types @@ -30,6 +31,7 @@ const DefaultRoomType = ChatRoomType // A Server is always a part of a visor // So you can think of this hierarchial structure: // (Visor (PublicKey1)) +// -> P2P-Room // -> Server1 (PublicKey1.1) // -> Room1 (PublicKey1.1.1) // -> Room2 (PublicKey1.1.2) @@ -194,7 +196,7 @@ func (r *Room) DeleteMuted(pk cipher.PubKey) error { } // GetAllMuted returns all muted members/peers -func (r *Room) GetAllMuted(pk cipher.PubKey) map[cipher.PubKey]bool { +func (r *Room) GetAllMuted() map[cipher.PubKey]bool { return r.Muted } diff --git a/cmd/apps/skychat/internal/domain/chat/server.go b/cmd/apps/skychat/internal/domain/chat/server.go index 6441d6d04..0884fd0de 100644 --- a/cmd/apps/skychat/internal/domain/chat/server.go +++ b/cmd/apps/skychat/internal/domain/chat/server.go @@ -37,6 +37,26 @@ func (s *Server) AddMessage(pkroute util.PKRoute, m message.Message) { s.Rooms[pkroute.Room] = r } +// SetRouteInfo sets the info of the given room inside the server +func (s *Server) SetRouteInfo(pkroute util.PKRoute, info info.Info) error { + if pkroute.Server == pkroute.Room { + s.SetInfo(info) + } + + room, err := s.GetRoomByPK(pkroute.Room) + if err != nil { + return err + } + room.SetInfo(info) + + err = s.SetRoom(*room) + if err != nil { + return err + } + + return nil +} + // GetPKRoute returns the PKRoute func (s *Server) GetPKRoute() util.PKRoute { return s.PKRoute @@ -126,6 +146,7 @@ func (s *Server) DeleteMember(pk cipher.PubKey) error { delete(s.Members, pk) return nil } + //TODO: also try to delete member from all rooms as he leaves the server delete(s.Members, pk) return nil } @@ -177,7 +198,10 @@ func (s *Server) SetMemberInfo(i info.Info) error { if err != nil { return err } - s.SetRoom(room) + err = s.SetRoom(room) + if err != nil { + return err + } } return nil @@ -229,7 +253,7 @@ func (s *Server) DeleteMuted(pk cipher.PubKey) error { } // GetAllMuted returns all muted members/peers -func (s *Server) GetAllMuted(pk cipher.PubKey) map[cipher.PubKey]bool { +func (s *Server) GetAllMuted() map[cipher.PubKey]bool { return s.Muted } @@ -362,7 +386,10 @@ func NewDefaultServer(route util.PKRoute) Server { s.Rooms = make(map[cipher.PubKey]Room) s.Conns = make(map[cipher.PubKey]net.Conn) - s.AddRoom(NewDefaultRemoteRoom(route)) + err := s.AddRoom(NewDefaultRemoteRoom(route)) + if err != nil { + fmt.Printf("Error in adding room: %s", err) + } return s } diff --git a/cmd/apps/skychat/internal/domain/chat/visor.go b/cmd/apps/skychat/internal/domain/chat/visor.go index 0886e1648..bcbd5d327 100644 --- a/cmd/apps/skychat/internal/domain/chat/visor.go +++ b/cmd/apps/skychat/internal/domain/chat/visor.go @@ -2,8 +2,10 @@ package chat import ( "fmt" + "reflect" "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) @@ -25,9 +27,14 @@ func (v *Visor) GetPK() cipher.PubKey { } // GetP2P returns peer to peer Room -func (v *Visor) GetP2P() (Room, error) { - //TODO: check if p2p is empty - return v.P2P, nil +// if the p2p is empty it returns an empty pointer +func (v *Visor) GetP2P() (*Room, error) { + return &v.P2P, nil +} + +// P2PIsEmpty returns a bool depending on if the visor has got a p2p +func (v *Visor) P2PIsEmpty() bool { + return reflect.DeepEqual(v.P2P, Room{}) } // AddServer adds the given server to the visor @@ -129,6 +136,37 @@ func (v *Visor) AddMessage(pkroute util.PKRoute, m message.Message) { v.Server[pkroute.Server] = s } +// SetRouteInfo sets the info of the given route inside the visor +func (v *Visor) SetRouteInfo(pkroute util.PKRoute, info info.Info) error { + if pkroute.Server == pkroute.Visor { + p2p, err := v.GetP2P() + if err != nil { + return err + } + p2p.SetInfo(info) + err = v.SetP2P(*p2p) + if err != nil { + return err + } + return nil + } + server, err := v.GetServerByPK(pkroute.Server) + if err != nil { + return err + } + err = server.SetRouteInfo(pkroute, info) + if err != nil { + return err + } + + err = v.SetServer(*server) + if err != nil { + return err + } + + return nil +} + // Constructors // NewUndefinedVisor creates undefined empty visor to a public key @@ -165,7 +203,10 @@ func NewDefaultVisor(route util.PKRoute) Visor { v.PK = route.Visor v.Server = make(map[cipher.PubKey]Server) - v.AddServer(NewDefaultServer(route)) + err := v.AddServer(NewDefaultServer(route)) + if err != nil { + fmt.Printf("Error in adding server: %s", err) + } return v } diff --git a/cmd/apps/skychat/internal/domain/client/client.go b/cmd/apps/skychat/internal/domain/client/client.go index 2f0cf798d..6d57b1002 100644 --- a/cmd/apps/skychat/internal/domain/client/client.go +++ b/cmd/apps/skychat/internal/domain/client/client.go @@ -18,7 +18,7 @@ import ( "github.com/skycoin/skywire/pkg/app/appnet" "github.com/skycoin/skywire/pkg/app/appserver" "github.com/skycoin/skywire/pkg/routing" - "github.com/skycoin/skywire/pkg/skyenv" + "github.com/skycoin/skywire/pkg/visor/visorconfig" ) // Client defines a chat client @@ -117,7 +117,7 @@ func NewClient() *Client { if runtime.GOOS == "windows" { var err error - c.ipcCl, err = ipc.StartClient(skyenv.SkychatName, nil) + c.ipcCl, err = ipc.StartClient(visorconfig.SkychatName, nil) if err != nil { fmt.Printf("Error creating ipc server for skychat client: %v\n", err) c.SetAppError(err) @@ -161,14 +161,22 @@ func (c *Client) SetAppError(appErr error) { } } +// SetAppPort sets the appPort +func (c *Client) SetAppPort(appCl *app.Client, port routing.Port) { + if err := appCl.SetAppPort(port); err != nil { + print(fmt.Sprintf("Failed to set port %v: %v\n", port, err)) + } +} + +// handleIPCSignal handles the ipc signal func handleIPCSignal(client *ipc.Client) { for { m, err := client.Read() if err != nil { - fmt.Printf("%s IPC received error: %v", skyenv.SkychatName, err) + fmt.Printf("%s IPC received error: %v", visorconfig.SkychatName, err) } - if m.MsgType == skyenv.IPCShutdownMessageType { - fmt.Println("Stopping " + skyenv.SkychatName + " via IPC") + if m.MsgType == visorconfig.IPCShutdownMessageType { + fmt.Println("Stopping " + visorconfig.SkychatName + " via IPC") break } } diff --git a/cmd/apps/skychat/internal/domain/info/info.go b/cmd/apps/skychat/internal/domain/info/info.go index 887816348..e1a209884 100644 --- a/cmd/apps/skychat/internal/domain/info/info.go +++ b/cmd/apps/skychat/internal/domain/info/info.go @@ -76,9 +76,12 @@ func NewDefaultInfo() Info { return info } -//const DefaultImage = "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAIAAAAHjs1qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5OTMyNUUzOTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjY5OTMyNUU0OTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6Njk5MzI1RTE5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Njk5MzI1RTI5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7FIRCzAAAPn0lEQVR42uyd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" +// DefaultImage is the default image of all infos const DefaultImage = "0" +// DefaultImage is the default image of all infos --> This doesn't work atm as the packet size is to small to send this in one packet +//const DefaultImage = "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAIAAAAHjs1qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5OTMyNUUzOTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjY5OTMyNUU0OTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6Njk5MzI1RTE5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Njk5MzI1RTI5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7FIRCzAAAPn0lEQVR42uyd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" + // IsEmpty checks if info is empty func (i *Info) IsEmpty() bool { return *i == Info{} diff --git a/cmd/apps/skychat/internal/domain/message/message.go b/cmd/apps/skychat/internal/domain/message/message.go index 85a867668..8765584a5 100644 --- a/cmd/apps/skychat/internal/domain/message/message.go +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -36,14 +36,16 @@ const ( ConnMsgTypeReject // ConnMsgTypeLeave is used to handle connection message of type Leave ConnMsgTypeLeave + // ConnMsgTypeDelete is used to handle connection message of type Delete + ConnMsgTypeDelete ) // subtypes of InfoMsgType const ( //ErrInfoMsgType is used to handle info error messages ErrInfoMsgType = iota - //InfoMsgTypeUser is used to handle the info of a single user or server - InfoMsgTypeUser + //InfoMsgTypeSingle is used to handle the info of a single user or server or room + InfoMsgTypeSingle //InfoMsgTypeServerMembers is used to update the list of members of a server InfoMsgTypeServerMembers //InfoMsgTypeRoomMembers is used to update the list of members of a room diff --git a/cmd/apps/skychat/internal/inputports/http/chat/handler.go b/cmd/apps/skychat/internal/inputports/http/chat/handler.go index 9846da29e..d0fd16506 100644 --- a/cmd/apps/skychat/internal/inputports/http/chat/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/chat/handler.go @@ -33,8 +33,6 @@ const AddLocalServerURLParam = "addLocalServer" // AddLocalServerRequestModel represents the request model expected for Add request type AddLocalServerRequestModel struct { - //PKRoute - VisorPk string `json:"visorpk"` //Info Alias string `json:"alias"` Desc string `json:"desc"` @@ -51,25 +49,13 @@ func (c Handler) AddLocalServer(w http.ResponseWriter, r *http.Request) { return } - route := util.PKRoute{} - - visorpk := cipher.PubKey{} - err := visorpk.Set(requestModel.VisorPk) - if err != nil { - w.WriteHeader(http.StatusInternalServerError) - fmt.Fprint(w, err.Error()) - return - } - route.Visor = visorpk - info := info.Info{} info.SetAlias(requestModel.Alias) info.SetDescription(requestModel.Desc) info.SetImg(requestModel.Img) - err = c.chatServices.Commands.AddLocalServerHandler.Handle(commands.AddLocalServerRequest{ - Route: route, - Info: info, + err := c.chatServices.Commands.AddLocalServerHandler.Handle(commands.AddLocalServerRequest{ + Info: info, }) if err != nil { w.WriteHeader(http.StatusInternalServerError) @@ -289,18 +275,19 @@ func (c Handler) SendAddRoomMessage(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -// DeleteLocalServerByRouteURLParam contains the parameter identifier to be parsed by the handler -const DeleteLocalServerByRouteURLParam = "deleteLocalServer" +// DeleteLocalRouteURLParam contains the parameter identifier to be parsed by the handler +const DeleteLocalRouteURLParam = "DeleteLocalRoute" -// DeleteLocalServerByRouteRequestModel represents the request model expected for Delete request -type DeleteLocalServerByRouteRequestModel struct { +// DeleteLocalRouteRequestModel represents the request model expected for Delete request +type DeleteLocalRouteRequestModel struct { VisorPk string `json:"visorpk"` ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` } -// DeleteLocalServerByRoute adds a room to the local visor/server -func (c Handler) DeleteLocalServerByRoute(w http.ResponseWriter, r *http.Request) { - var requestModel DeleteLocalServerByRouteRequestModel +// DeleteLocalRoute adds a room to the local visor/server +func (c Handler) DeleteLocalRoute(w http.ResponseWriter, r *http.Request) { + var requestModel DeleteLocalRouteRequestModel decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) if decodeErr != nil { w.WriteHeader(http.StatusBadRequest) @@ -327,9 +314,20 @@ func (c Handler) DeleteLocalServerByRoute(w http.ResponseWriter, r *http.Request return } route.Server = serverpk + + if requestModel.RoomPk != "" { + roompk := cipher.PubKey{} + err = roompk.Set(requestModel.RoomPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Room = roompk + } } - err = c.chatServices.Commands.DeleteLocalServerHandler.Handle(commands.DeleteLocalServerRequest{ + err = c.chatServices.Commands.DeleteLocalRouteHandler.Handle(commands.DeleteLocalRouteRequest{ Route: route, }) if err != nil { @@ -340,32 +338,10 @@ func (c Handler) DeleteLocalServerByRoute(w http.ResponseWriter, r *http.Request w.WriteHeader(http.StatusOK) } -// DeleteVisorByPKURLParam contains the parameter identifier to be parsed by the handler -const DeleteVisorByPKURLParam = "deleteVisor" - -// DeleteVisorByPK Deletes the remote visor with the provided pk -func (c Handler) DeleteVisorByPK(w http.ResponseWriter, r *http.Request) { - fmt.Println(formatRequest(r)) - vars := mux.Vars(r) - fmt.Println(vars) - fmt.Println(vars[DeleteVisorByPKURLParam]) - chatPK := cipher.PubKey{} - err := chatPK.Set(vars[DeleteVisorByPKURLParam]) - if err != nil { - fmt.Println("could not convert pubkey") - } - fmt.Println(chatPK.Hex()) - err = c.chatServices.Commands.DeleteRemoteVisorHandler.Handle(commands.DeleteRemoteVisorRequest{Pk: chatPK}) - if err != nil { - w.WriteHeader(http.StatusBadRequest) - fmt.Fprint(w, err.Error()) - } -} - // LeaveRemoteRouteURLParam contains the parameter identifier to be parsed by the handler const LeaveRemoteRouteURLParam = "leaveRemoteRoute" -// LeaveRemoteRouteRequestModel represents the request model expected for Leave request +// LeaveRemoteRouteRequestModel represents the request model expected for Delete request type LeaveRemoteRouteRequestModel struct { VisorPk string `json:"visorpk"` ServerPk string `json:"serverpk"` @@ -401,6 +377,7 @@ func (c Handler) LeaveRemoteRoute(w http.ResponseWriter, r *http.Request) { return } route.Server = serverpk + if requestModel.RoomPk != "" { roompk := cipher.PubKey{} err = roompk.Set(requestModel.RoomPk) @@ -424,10 +401,8 @@ func (c Handler) LeaveRemoteRoute(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -//[]:rename to SendTextMessageURLParam - -// SendTextMessagePKURLParam contains the parameter identifier to be parsed by the handler -const SendTextMessagePKURLParam = "sendTxtMsg" +// SendTextMessageURLParam contains the parameter identifier to be parsed by the handler +const SendTextMessageURLParam = "sendTxtMsg" // SendTextMessageRequestModel represents the request model expected for Add request type SendTextMessageRequestModel struct { diff --git a/cmd/apps/skychat/internal/inputports/http/server.go b/cmd/apps/skychat/internal/inputports/http/server.go index 679561460..93d9f83e9 100644 --- a/cmd/apps/skychat/internal/inputports/http/server.go +++ b/cmd/apps/skychat/internal/inputports/http/server.go @@ -56,13 +56,18 @@ func (httpServer *Server) AddChatHTTPRoutes() { httpServer.router.HandleFunc(chatsHTTPRoutePath+"/{"+chat.GetVisorByPKURLParam+"}", chat.NewHandler(httpServer.appServices.ChatServices).GetVisorByPK).Methods("GET") //Commands - httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.AddLocalServerURLParam, chat.NewHandler(httpServer.appServices.ChatServices).AddLocalServer).Methods("POST") + //Remote httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.JoinRemoteRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).JoinRemoteRoute).Methods("POST") - httpServer.router.HandleFunc(chatsHTTPRoutePath+"/{"+chat.DeleteVisorByPKURLParam+"}", chat.NewHandler(httpServer.appServices.ChatServices).DeleteVisorByPK).Methods("DELETE") httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.LeaveRemoteRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).LeaveRemoteRoute).Methods("POST") + + //Local + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.AddLocalServerURLParam, chat.NewHandler(httpServer.appServices.ChatServices).AddLocalServer).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.DeleteLocalRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).DeleteLocalRoute).Methods("POST") + + //Both httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendAddRoomMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendAddRoomMessage).Methods("POST") httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendDeleteRoomMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendDeleteRoomMessage).Methods("POST") - httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendTextMessagePKURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendTextMessage).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendTextMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendTextMessage).Methods("POST") } diff --git a/cmd/apps/skychat/internal/inputports/http/static/index.html b/cmd/apps/skychat/internal/inputports/http/static/index.html index 38222a640..4150c85ef 100644 --- a/cmd/apps/skychat/internal/inputports/http/static/index.html +++ b/cmd/apps/skychat/internal/inputports/http/static/index.html @@ -30,7 +30,7 @@
              diff --git a/cmd/apps/skychat/internal/inputports/http/static/index.js b/cmd/apps/skychat/internal/inputports/http/static/index.js index a0ea5afc9..d4b7f8a03 100644 --- a/cmd/apps/skychat/internal/inputports/http/static/index.js +++ b/cmd/apps/skychat/internal/inputports/http/static/index.js @@ -1035,7 +1035,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa } }).catch(e => alert(e.message)); }else{ - fetch('chats/' + "addLocalServer", { method: 'POST', body: JSON.stringify({ visorpk: visorpk, alias: alias, desc: description, img: ""}) }) + fetch('chats/' + "addLocalServer", { method: 'POST', body: JSON.stringify({alias: alias, desc: description, img: ""}) }) .then(res => { if (res.ok) { res.text() @@ -1143,21 +1143,35 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa } //// DELETE - //tries to delete the current selected [Chat] - deleteChat() { + //tries to delete the given route + leaveRemoteRoute() { if (!this.chat) { return; } - + + let route = null + Object.keys(this.chats).forEach(c => { + if (this.chats[c].pk == this.chat){ + route = this.chats[c].route; + } + }) + + if (route == null){ + return; + } + const response = window.confirm("Are you sure you want to delete the chat?"); + const visorpk = route.visor + const serverpk = route.server + const roompk = route.room + if (response) { - - fetch('chats' + '/' + this.chat.toString() , { method: 'DELETE' }) + fetch('chats' + '/leaveRemoteRoute', { method: 'POST', body: JSON.stringify({ visorpk: visorpk, serverpk: serverpk, roompk: roompk}) }) .then(res => { if (res.ok) { res.text().then(); - this.chats = this.chats.filter(v => v.pk != this.chat); + this.chats = this.chats.filter(v => v.pk != roompk); document.getElementById('messages').innerHTML = ''; document.getElementById('chatButtonsContainer').classList.add('hidden'); @@ -1166,13 +1180,12 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa const pkArea = item.getElementsByClassName('pk')[0]; - if (pkArea.innerText === this.chat) { + if (pkArea.innerText === roompk) { item.parentNode.removeChild(item); }}); this.chat = null; } else { - //TODO: add visor-server-room pks to alert text - res.text().then(text => alert(`Failed to delete chat ${this.chat}: ${text}`)); + res.text().then(text => alert(`Failed to leave chat:\n visor:\n${visorpk}\nserver:\n${serverpk}\nroom:\n${roompk}\nreason:\n${text}`)); } }) diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index 1e55a42da..38fd79902 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -7,6 +7,7 @@ import ( "fmt" "net" "time" + "unsafe" "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/netutil" @@ -65,12 +66,13 @@ func (ms MessengerService) Handle(pk cipher.PubKey) { for { //read packets - buf := make([]byte, 32*1024) + buf := make([]byte, 32*1024*4) n, err := conn.Read(buf) + fmt.Printf("Received %d bytes \n", n) if err != nil { fmt.Println("Failed to read packet:", err) //close and delete connection - //TODO: close connection + //? close connection ? err2 := pCli.DeleteConn(conn.RemoteAddr().(appnet.Addr).PubKey) if err2 != nil { errs <- err2 @@ -165,7 +167,8 @@ func (ms MessengerService) Dial(pk cipher.PubKey) (net.Conn, error) { ms.ctx = ctx err = r.Do(ms.ctx, func() error { - //TODO: notify that dialing is happening? + //? notify that dialing is happening? + //? How about not deleting the visor, but saving the failed dials as a message so the user can see that something is happening. conn, err = pCli.GetAppClient().Dial(addr) //could not find a valid connection to a chat, so delete it. err2 := ms.visorRepo.Delete(pk) @@ -213,11 +216,10 @@ func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, fmt.Printf("New skychat added: %s\n", pkroute.String()) } - // if the message is a p2p message we have to check if the p2p room exists in the sever + // if the message is a p2p message we have to check if the p2p room exists in the server if pkroute.Visor == pkroute.Server { //maybe we already have a visor, but not yet a p2p-room so check if we have that. - _, err = v.GetP2P() - if err != nil { + if v.P2PIsEmpty() { p2p := chat.NewDefaultP2PRoom(pkroute.Visor) err = v.AddP2P(p2p) if err != nil { @@ -276,6 +278,8 @@ func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, fmt.Printf("Status: %d \n", m.Status) fmt.Printf("Seen: %t \n", m.Seen) fmt.Println("---------------------------------------------------------------------------------------------------") + fmt.Printf("Message Size: %T, %d\n", m, unsafe.Sizeof(m)) + fmt.Println("---------------------------------------------------------------------------------------------------") rm := message.NewRAWMessage(m) @@ -488,27 +492,34 @@ func (ms MessengerService) sendMessageToLocalRoute(msg message.Message) error { // SendInfoMessage sends an info message to the given chat and notifies about sent message func (ms MessengerService) SendInfoMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute, info info.Info) error { - bytes, err := json.Marshal(info) + usr, err := ms.usrRepo.GetUser() if err != nil { - fmt.Printf("Failed to marshal json: %v", err) + fmt.Printf("Error getting user from repository: %s", err) return err } - m := message.NewChatInfoMessage(root, dest, bytes) - - err = ms.sendMessage(pkroute, m, true) + bytes, err := json.Marshal(info) if err != nil { + fmt.Printf("Failed to marshal json: %v", err) return err } - //notify about sent info message - n := notification.NewMsgNotification(dest, m) - err = ms.ns.Notify(n) - if err != nil { - return err + m := message.NewChatInfoMessage(root, dest, bytes) + + if m.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(m) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(m) + if err != nil { + return err + } } return nil + } // SendChatAcceptMessage sends an accept-message from the root to the destination @@ -531,10 +542,18 @@ func (ms MessengerService) SendChatRejectMessage(root util.PKRoute, dest util.PK return nil } -// SendChatLeaveMessage sends a leave-message from the root to the destination -func (ms MessengerService) SendChatLeaveMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute) error { - m := message.NewChatLeaveMessage(root, dest) - err := ms.sendMessage(pkroute, m, true) +// SendLeaveChatMessage sends a leave-message from the root to the destination +func (ms MessengerService) SendLeaveChatMessage(pkroute util.PKRoute) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) + + m := message.NewChatLeaveMessage(root, pkroute) + err = ms.sendMessage(pkroute, m, true) if err != nil { return err } @@ -554,6 +573,8 @@ func (ms MessengerService) Listen() { return } + pCli.SetAppPort(pCli.GetAppClient(), pCli.GetPort()) + go func() { if err := <-ms.errs; err != nil { fmt.Printf("Error in go handle function: %s ", err) diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go index da9b95ffb..07b232416 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go @@ -3,7 +3,7 @@ package netcon import ( "encoding/json" "fmt" - "time" + "strconv" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" @@ -47,15 +47,15 @@ func (ms MessengerService) handleLocalServerMessage(m message.Message) error { //the destination route of a message to send back to the root dest := m.Root - //check if origin of message is a member or in blacklist of server //TODO: or not a member !! add always local as member - if _, ok := server.GetBlacklist()[m.Root.Visor]; ok { + //check if origin of message is in blacklist or not member of sever + _, isServerMember := server.GetAllMembers()[m.Root.Visor] + _, isInServerBlacklist := server.GetBlacklist()[m.Root.Visor] + if !isServerMember || isInServerBlacklist { err = ms.SendChatRejectMessage(root, dest) if err != nil { - //?:Maybe better continue than throwing an error as we don't care if the sending didnt work? - return err + return fmt.Errorf("error sending reject message: %s", err) } - //? Maybe better continue and log the event? - return fmt.Errorf("Message rejected from " + m.Root.Visor.String()) + return fmt.Errorf("message rejected from " + m.Root.Visor.String() + "isServerMember: " + strconv.FormatBool(isServerMember) + "isInServerBlacklist: " + strconv.FormatBool(isInServerBlacklist)) } //handle Command Messages @@ -68,18 +68,21 @@ func (ms MessengerService) handleLocalServerMessage(m message.Message) error { } //Check if room exists - r, err := server.GetRoomByPK(pkroute.Room) + room, err := server.GetRoomByPK(pkroute.Room) if err != nil { return err } - //check if origin of message is member or in blacklist of room //TODO: or not a member - if _, ok := r.GetBlacklist()[m.Root.Visor]; ok { + //check if origin of message is in blacklist or not member of room + _, isRoomMember := room.GetAllMembers()[m.Root.Visor] + _, isInRoomBlacklist := room.GetBlacklist()[m.Root.Visor] + if !isRoomMember || isInRoomBlacklist { err = ms.SendChatRejectMessage(root, dest) if err != nil { - return err + return fmt.Errorf("error sending reject message: %s", err) } - return fmt.Errorf("Message rejected from " + m.Root.Visor.String()) + return fmt.Errorf("message rejected from " + m.Root.Visor.String() + "isRoomMember: " + strconv.FormatBool(isRoomMember) + "isInRoomBlacklist: " + strconv.FormatBool(isInRoomBlacklist)) + } //now we can handle all other message-types @@ -126,7 +129,7 @@ func (ms MessengerService) handleLocalServerConnMsgType(visor *chat.Visor, m mes if err != nil { return err } - r, err := server.GetRoomByPK(m.Dest.Room) + room, err := server.GetRoomByPK(m.Dest.Room) if err != nil { return err } @@ -140,13 +143,16 @@ func (ms MessengerService) handleLocalServerConnMsgType(visor *chat.Visor, m mes case message.ConnMsgTypeRequest: //check if sender is in blacklist, if not send accept and info messages back, else send reject message if _, ok := server.GetBlacklist()[m.Root.Visor]; !ok { - if _, ok2 := r.GetBlacklist()[m.Root.Visor]; !ok2 { + if _, ok2 := room.GetBlacklist()[m.Root.Visor]; !ok2 { //add request message to room - r.AddMessage(m) + room.AddMessage(m) //send request message to peers - ms.sendMessageToPeers(visor, m) + err = ms.sendMessageToPeers(visor, m) + if err != nil { + return err + } //add remote peer to members so he is able to send other messages than connMsgType info := info.NewDefaultInfo() @@ -159,12 +165,12 @@ func (ms MessengerService) handleLocalServerConnMsgType(visor *chat.Visor, m mes return err } //add remote peer to room - err = r.AddMember(*dummyPeer) + err = room.AddMember(*dummyPeer) if err != nil { return err } //update room inside server - err = server.SetRoom(*r) + err = server.SetRoom(*room) if err != nil { return err } @@ -192,12 +198,8 @@ func (ms MessengerService) handleLocalServerConnMsgType(visor *chat.Visor, m mes return err } - //!! FIXME - //This sleep is necessary, as it looks like the transport hangs up when sending two messages in a short time frame - time.Sleep(1 * time.Second) - //send the rooms info to the remote peer - err = ms.SendInfoMessage(pkroute, root, dest, r.GetInfo()) + err = ms.SendInfoMessage(pkroute, root, dest, room.GetInfo()) if err != nil { return err } @@ -220,6 +222,39 @@ func (ms MessengerService) handleLocalServerConnMsgType(visor *chat.Visor, m mes } return fmt.Errorf("pk in server-blacklist rejected") } + case message.ConnMsgTypeLeave: + // if pkroute defines room, remove from room membership + if pkroute.Server != pkroute.Room { + err = room.DeleteMember(m.Origin) + if err != nil { + return err + } + //update server with updated room + err = server.SetRoom(*room) + if err != nil { + return err + } + + //TODO: send new member-list to members + + } else { + // if pk route defines server, remove from server memberhsip (and all rooms membership in method included) + err = server.DeleteMember(m.Origin) + if err != nil { + return err + } + + //TODO: for each room and the server: send new member-list to members + } + //update visor and respository + err = visor.SetServer(*server) + if err != nil { + return err + } + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } default: return fmt.Errorf("incorrect data received") @@ -256,25 +291,28 @@ func (ms MessengerService) handleLocalServerCmdMsgType(visor *chat.Visor, m mess switch m.MsgSubtype { case message.CmdMsgTypeAddRoom: - //TODO: First check if origin of msg is admin + //First check if origin of msg is admin + if _, isAdmin := server.GetAllAdmin()[m.Root.Visor]; !isAdmin { + return fmt.Errorf("command not accepted, no admin") + } // make a new route rr := util.NewLocalRoomRoute(m.Dest.Visor, m.Dest.Server, server.GetAllRoomsBoolMap()) // setup room for repository - r := chat.NewLocalRoom(rr, i, chat.DefaultRoomType) + room := chat.NewLocalRoom(rr, i, chat.DefaultRoomType) //setup user as peer for room membership p := peer.NewPeer(*usr.GetInfo(), usr.GetInfo().Alias) //Add user as member - err = r.AddMember(*p) + err = room.AddMember(*p) if err != nil { return err } - //TODO:: if room is visible/public also add messengerService and send 'Room-Added' Message to Members of server + //TODO: if room is visible/public also add messengerService and send 'Room-Added' Message to Members of server // add room to server, update visor and then update repository - err = server.AddRoom(r) + err = server.AddRoom(room) if err != nil { return err } @@ -296,10 +334,15 @@ func (ms MessengerService) handleLocalServerCmdMsgType(visor *chat.Visor, m mess } return nil case message.CmdMsgTypeDeleteRoom: - //TODO: First check if origin of msg is admin + //First check if origin of msg is admin + if _, isAdmin := server.GetAllAdmin()[m.Root.Visor]; !isAdmin { + return fmt.Errorf("command not accepted, no admin") + } //TODO: handle message + //send DeleteChatMessage to all members + //? do we have to differ between deleting the chat and stopping the service of forwarding and accepting any message? return nil - //TODO: add other cmd messages + //[] add other cmd messages default: return fmt.Errorf("incorrect data received") } @@ -352,30 +395,46 @@ func (ms MessengerService) handleLocalServerInfoMsgType(v *chat.Visor, m message return err } - //TODO: send updated info of members to all members + //TODO: send updated info of member to all members return nil } // handleLocalRoomTextMstType handles messages of type text of the p2p chat -func (ms MessengerService) handleLocalRoomTextMsgType(v *chat.Visor, m message.Message) error { +func (ms MessengerService) handleLocalRoomTextMsgType(visor *chat.Visor, m message.Message) error { fmt.Println("handleLocalRoomTextMsgType") pkroute := util.NewRoomRoute(m.GetDestinationVisor(), m.GetDestinationServer(), m.GetDestinationRoom()) - //check if in muted of server - //TODO: - //check if in muted of room - //TODO: + server, err := visor.GetServerByPK(m.Dest.Server) + if err != nil { + return err + } + + room, err := server.GetRoomByPK(m.Dest.Room) + if err != nil { + return err + } //notify about a new TextMessage n := notification.NewMsgNotification(pkroute, m) - err := ms.ns.Notify(n) + err = ms.ns.Notify(n) if err != nil { return err } - err = ms.sendMessageToPeers(v, m) + //check if in muted in server + if _, ok := server.GetAllMuted()[m.Origin]; ok { + return nil + } + + //check if in muted in room + if _, ok := room.GetAllMuted()[m.Origin]; ok { + return nil + } + + //as the originator is not muted we send the message to the peers + err = ms.sendMessageToPeers(visor, m) if err != nil { return err } @@ -394,12 +453,12 @@ func (ms MessengerService) sendMessageToPeers(v *chat.Visor, m message.Message) return err } - r, err := server.GetRoomByPK(m.Dest.Room) + room, err := server.GetRoomByPK(m.Dest.Room) if err != nil { return err } - members := r.GetAllMembers() + members := room.GetAllMembers() for _, peer := range members { @@ -409,6 +468,7 @@ func (ms MessengerService) sendMessageToPeers(v *chat.Visor, m message.Message) m.Root = pkroute m.Dest = util.NewP2PRoute(peer.GetPK()) + //send message to the peer, but don't save it again in database err := ms.sendMessage(pkroute, m, false) if err != nil { fmt.Printf("error sending group message to peer: %v", err) diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go index 3bfb3ff5c..732d6def7 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go @@ -3,7 +3,6 @@ package netcon import ( "encoding/json" "fmt" - "time" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" @@ -75,7 +74,7 @@ func (ms MessengerService) handleP2PMessage(m message.Message) error { return err } //handle the message - err := ms.handleP2PTextMsgType(visor, m) + err := ms.handleP2PTextMsgType(m) if err != nil { return err } @@ -155,10 +154,6 @@ func (ms MessengerService) handleP2PConnMsgType(m message.Message) error { return err } - //!! FIXME - //This sleep is necessary, as it looks like the transport hangs up when sending two messages in a short time frame - time.Sleep(1 * time.Second) - //send the users info to the remote peer err = ms.SendInfoMessage(pkroute, root, dest, *usr.GetInfo()) if err != nil { @@ -171,7 +166,7 @@ func (ms MessengerService) handleP2PConnMsgType(m message.Message) error { if err != nil { return err } - //TODO: !! we first have to check whether we don't have got servers of this visor saved + //TODO: !! we first have to check whether we don't have got any other servers of this visor saved //deletes the visor from the repository err = ms.visorRepo.Delete(pkroute.Visor) if err != nil { @@ -241,7 +236,10 @@ func (ms MessengerService) handleP2PInfoMsgType(v *chat.Visor, m message.Message fmt.Println("---------------------------------------------------------------------------------------------------") //update the info of the p2p - v.P2P.Info = i + err = v.SetRouteInfo(pkroute, i) + if err != nil { + return err + } err = ms.visorRepo.Set(*v) if err != nil { return err @@ -258,7 +256,7 @@ func (ms MessengerService) handleP2PInfoMsgType(v *chat.Visor, m message.Message } // handleP2PTextMstType handles messages of type text of the p2p chat -func (ms MessengerService) handleP2PTextMsgType(c *chat.Visor, m message.Message) error { +func (ms MessengerService) handleP2PTextMsgType(m message.Message) error { fmt.Println("handleP2PTextMsgType") pkroute := util.NewP2PRoute(m.Root.Visor) diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go index 4efc6f42a..2f73115c4 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go @@ -17,11 +17,14 @@ func (ms MessengerService) handleRemoteServerMessage(m message.Message) error { pkroute := util.NewRoomRoute(m.GetRootVisor(), m.GetRootServer(), m.GetRootRoom()) - //TODO: check if we are member -> if not ignore message - - visor, err := ms.visorRepo.GetByPK(m.Root.Visor) + //check if we are member of remote server -> if not ignore message + visor, err := ms.visorRepo.GetByPK(pkroute.Visor) if err != nil { - return err + return fmt.Errorf("message dumped: no member of remote, visor not even known") + } + _, err = visor.GetServerByPK(pkroute.Server) + if err != nil { + return fmt.Errorf("message dumped: no member of remote server") } switch m.GetMessageType() { @@ -95,6 +98,7 @@ func (ms MessengerService) handleRemoteRoomConnMsgType(m message.Message) error if err != nil { return err } + //as the remote route has accepted the chat request we now can send our info err = ms.SendInfoMessage(pkroute, root, dest, *user.GetInfo()) if err != nil { @@ -102,14 +106,18 @@ func (ms MessengerService) handleRemoteRoomConnMsgType(m message.Message) error } case message.ConnMsgTypeReject: + //notify that we send a reject message n := notification.NewMsgNotification(m.Root, m) err := ms.ns.Notify(n) if err != nil { return err } //? do we have to delete something here? + //? maybe we don't even have to notify the user, that a rejection happened? return nil - + case message.ConnMsgTypeDelete: + //? do we have to delete something here? --> maybe the peer wants to save the chat history and not delete it, therefore we would have to add some kind of flag or so, that + //? stops the user from sending any messages to the deleted chat/server default: return fmt.Errorf("incorrect data received") } @@ -120,6 +128,9 @@ func (ms MessengerService) handleRemoteRoomConnMsgType(m message.Message) error // handleRemoteRoomInfoMsgType handles messages of type info of peers func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message.Message) error { fmt.Println("handleRemoteRoomInfoMsgType") + + pkroute := util.NewRoomRoute(m.GetRootVisor(), m.GetRootServer(), m.GetRootRoom()) + //unmarshal the received message bytes to info.Info i := info.Info{} err := json.Unmarshal(m.Message, &i) @@ -134,26 +145,7 @@ func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message. fmt.Printf("Img: %s \n", i.Img) fmt.Println("---------------------------------------------------------------------------------------------------") - //TODO: ?? Put something like SetRoomInfo into visor as method so only a call of visor.SetRoomInfo etc. is needed everywhere and not getting server and then getting room?? - //get server from visor - s, err := v.GetServerByPK(m.GetRootServer()) - if err != nil { - return err - } - - //get room from server - r, err := s.GetRoomByPK(m.GetRootRoom()) - if err != nil { - return err - } - - //update the info of the remote server - r.SetInfo(i) //TODO: return error? - err = s.SetRoom(*r) - if err != nil { - return err - } - err = v.SetServer(*s) + err = v.SetRouteInfo(pkroute, i) if err != nil { return err } diff --git a/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go b/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go index ebe27ce58..fac283e30 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go @@ -32,7 +32,7 @@ func (ns *NotificationService) Notify(notification notification.Notification) er return nil } -//InitChannel inits the channel with make +// InitChannel inits the channel with make func (ns *NotificationService) InitChannel() { ns.notifCh = make(chan string) } @@ -42,7 +42,7 @@ func (ns *NotificationService) GetChannel() chan string { return ns.notifCh } -//Defer Channel includes all messages when the channel has to be deferred +// DeferChannel includes all messages when the channel has to be deferred func (ns *NotificationService) DeferChannel() { close(ns.notifCh) ns.notifCh = nil diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go index 567801f5a..021ede842 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go @@ -38,12 +38,6 @@ func (r *VisorRepo) GetByPK(pk cipher.PubKey) (*chat.Visor, error) { func (r *VisorRepo) GetAll() ([]chat.Visor, error) { r.visorsMu.Lock() defer r.visorsMu.Unlock() - // TODO(ersonp): code is unused; check for usage - // keys := make([]cipher.PubKey, 0) - - // for key := range r.chats { - // keys = append(keys, key) - // } var values []chat.Visor for _, value := range r.visors { From d4abfa4fdbeb31152659c73132fea39b04e1b324 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Mon, 13 Feb 2023 17:38:57 +0100 Subject: [PATCH 25/72] small changes --- .../app/chat/commands/leave_remote_route.go | 4 +- .../internal/app/chat/commands/todos.go | 1 + .../internal/app/messenger/messenger.go | 2 +- .../internal/domain/message/message.go | 15 +++ .../messenger/netcon/messenger_service.go | 12 +- .../netcon/messenger_service_local_server.go | 106 ++++++++++++++++-- .../messenger/netcon/messenger_service_p2p.go | 22 +++- .../netcon/messenger_service_remote_server.go | 100 ++++++++++++----- 8 files changed, 213 insertions(+), 49 deletions(-) diff --git a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go index 0ba54c83b..b2e2b7e33 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go +++ b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go @@ -53,7 +53,7 @@ func (h leaveRemoteRouteRequestHandler) Handle(command LeaveRemoteRouteRequest) // Check if handling p2p room if command.Route.Server == command.Route.Room { if !visor.P2PIsEmpty() { - err = h.ms.SendLeaveChatMessage(command.Route) + err = h.ms.SendLeaveRouteMessage(command.Route) if err != nil { return err } @@ -84,7 +84,7 @@ func (h leaveRemoteRouteRequestHandler) Handle(command LeaveRemoteRouteRequest) } // Send LeaveChatMessage to remote server - err = h.ms.SendLeaveChatMessage(command.Route) + err = h.ms.SendLeaveRouteMessage(command.Route) if err != nil { return err } diff --git a/cmd/apps/skychat/internal/app/chat/commands/todos.go b/cmd/apps/skychat/internal/app/chat/commands/todos.go index a00a0fccd..3508ccf70 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/todos.go +++ b/cmd/apps/skychat/internal/app/chat/commands/todos.go @@ -26,6 +26,7 @@ package commands //usecases-------------------------------------------- //p2p----------------------- +//make p2p room within own visor -> for informations from other apps or so? //server & rooms------------ //TODO:send_hire_admin_message.go //maybe only allow this action from server-host diff --git a/cmd/apps/skychat/internal/app/messenger/messenger.go b/cmd/apps/skychat/internal/app/messenger/messenger.go index 22ce9b8e5..c3ac81b93 100644 --- a/cmd/apps/skychat/internal/app/messenger/messenger.go +++ b/cmd/apps/skychat/internal/app/messenger/messenger.go @@ -14,7 +14,7 @@ type Service interface { //only used as client/p2p SendRouteRequestMessage(route util.PKRoute) error - SendLeaveChatMessage(pkroute util.PKRoute) error + SendLeaveRouteMessage(pkroute util.PKRoute) error //used as client/p2p and server SendTextMessage(route util.PKRoute, msg []byte) error diff --git a/cmd/apps/skychat/internal/domain/message/message.go b/cmd/apps/skychat/internal/domain/message/message.go index 8765584a5..1b092f283 100644 --- a/cmd/apps/skychat/internal/domain/message/message.go +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -269,6 +269,7 @@ func NewChatInfoMessage(root util.PKRoute, dest util.PKRoute, info []byte) Messa m.Root = root m.Dest = dest m.MsgType = InfoMsgType + m.MsgSubtype = InfoMsgTypeSingle m.Message = info m.Status = MsgStatusInitial m.Time = time.Now() @@ -303,6 +304,20 @@ func NewDeleteRoomMessage(root util.PKRoute, dest util.PKRoute) Message { return m } +// NewRoomMembersMessage returns a Message of roomMembers +func NewRoomMembersMessage(root util.PKRoute, dest util.PKRoute, members []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = InfoMsgType + m.MsgSubtype = InfoMsgTypeRoomMembers + m.Message = members + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + // GetID returns message ID func (m *Message) GetID() int { return m.ID diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index 38fd79902..037bd9a4b 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -459,7 +459,7 @@ func (ms MessengerService) SendDeleteRoomMessage(route util.PKRoute) error { return nil } -// sendMessageToRemoteRoute sends the given message to a remote route +// sendMessageToRemoteRoute sends the given message to a remote route (as p2p and client) func (ms MessengerService) sendMessageToRemoteRoute(msg message.Message) error { //if the message goes to p2p we save it in database, if not we wait for the remote server to send us our message //this way we can see that the message was received by the remote server @@ -479,7 +479,7 @@ func (ms MessengerService) sendMessageToRemoteRoute(msg message.Message) error { return nil } -// sendMessageToLocalRoute handles the message as a message received from a server +// sendMessageToLocalRoute "sends" the message to local server, so local server handles it, as it was sent from a remote route (used for messages send from server host, but as client) func (ms MessengerService) sendMessageToLocalRoute(msg message.Message) error { err := ms.handleLocalServerMessage(msg) if err != nil { @@ -506,12 +506,14 @@ func (ms MessengerService) SendInfoMessage(pkroute util.PKRoute, root util.PKRou m := message.NewChatInfoMessage(root, dest, bytes) + //send info to local route (we as host are a member also and have to update our info inside the server) if m.Dest.Visor == usr.GetInfo().GetPK() { err = ms.sendMessageToLocalRoute(m) if err != nil { return err } - } else { + } else if pkroute.Visor != usr.GetInfo().GetPK() { + //Send info to a remote route (as peer and as client) err = ms.sendMessageToRemoteRoute(m) if err != nil { return err @@ -542,8 +544,8 @@ func (ms MessengerService) SendChatRejectMessage(root util.PKRoute, dest util.PK return nil } -// SendLeaveChatMessage sends a leave-message from the root to the destination -func (ms MessengerService) SendLeaveChatMessage(pkroute util.PKRoute) error { +// SendLeaveRouteMessage sends a leave-message from the root to the destination +func (ms MessengerService) SendLeaveRouteMessage(pkroute util.PKRoute) error { usr, err := ms.usrRepo.GetUser() if err != nil { fmt.Printf("Error getting user from repository: %s", err) diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go index 07b232416..9335c1f5f 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go @@ -149,7 +149,7 @@ func (ms MessengerService) handleLocalServerConnMsgType(visor *chat.Visor, m mes room.AddMessage(m) //send request message to peers - err = ms.sendMessageToPeers(visor, m) + err = ms.sendMessageToPeers(visor, pkroute, m) if err != nil { return err } @@ -199,12 +199,26 @@ func (ms MessengerService) handleLocalServerConnMsgType(visor *chat.Visor, m mes } //send the rooms info to the remote peer - err = ms.SendInfoMessage(pkroute, root, dest, room.GetInfo()) + err = ms.sendLocalRouteInfoToPeer(pkroute, dest, room.GetInfo()) if err != nil { return err } - //TODO: send new member-list to members + // send new member-list to members + members := room.GetAllMembers() + + bytes, err := json.Marshal(members) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + msg := message.NewRoomMembersMessage(root, dest, bytes) + + err = ms.sendMessageToPeers(visor, pkroute, msg) + if err != nil { + return err + } } else { //sends a chat-reject-message to the remote peer @@ -222,7 +236,7 @@ func (ms MessengerService) handleLocalServerConnMsgType(visor *chat.Visor, m mes } return fmt.Errorf("pk in server-blacklist rejected") } - case message.ConnMsgTypeLeave: + case message.ConnMsgTypeLeave, message.ConnMsgTypeDelete: // if pkroute defines room, remove from room membership if pkroute.Server != pkroute.Room { err = room.DeleteMember(m.Origin) @@ -235,7 +249,21 @@ func (ms MessengerService) handleLocalServerConnMsgType(visor *chat.Visor, m mes return err } - //TODO: send new member-list to members + // send new member-list to members + members := room.GetAllMembers() + + bytes, err := json.Marshal(members) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + msg := message.NewRoomMembersMessage(root, dest, bytes) + + err = ms.sendMessageToPeers(visor, pkroute, msg) + if err != nil { + return err + } } else { // if pk route defines server, remove from server memberhsip (and all rooms membership in method included) @@ -282,7 +310,7 @@ func (ms MessengerService) handleLocalServerCmdMsgType(visor *chat.Visor, m mess return err } - //unmarshal the received message bytes to info.Info + //unmarshal the received message bytes to info.Info //FIXME: unmarshal to other thing than info i := info.Info{} err = json.Unmarshal(m.Message, &i) if err != nil { @@ -396,8 +424,39 @@ func (ms MessengerService) handleLocalServerInfoMsgType(v *chat.Visor, m message } //TODO: send updated info of member to all members + //FIXME: START: for the moment lets just update the whole list + server, err := v.GetServerByPK(m.Dest.Server) + if err != nil { + return err + } + room, err := server.GetRoomByPK(m.Dest.Room) + if err != nil { + return err + } + + //the root route of this server (== the Destination of the message) + root := pkroute + //the destination route of a message to send back to the root + dest := m.Root + // send new member-list to members + members := room.GetAllMembers() + bytes, err := json.Marshal(members) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + msg := message.NewRoomMembersMessage(root, dest, bytes) + + err = ms.sendMessageToPeers(v, pkroute, msg) + if err != nil { + return err + + } + //FIXME: END return nil + } // handleLocalRoomTextMstType handles messages of type text of the p2p chat @@ -434,7 +493,7 @@ func (ms MessengerService) handleLocalRoomTextMsgType(visor *chat.Visor, m messa } //as the originator is not muted we send the message to the peers - err = ms.sendMessageToPeers(visor, m) + err = ms.sendMessageToPeers(visor, pkroute, m) if err != nil { return err } @@ -443,17 +502,17 @@ func (ms MessengerService) handleLocalRoomTextMsgType(visor *chat.Visor, m messa } // -func (ms MessengerService) sendMessageToPeers(v *chat.Visor, m message.Message) error { +func (ms MessengerService) sendMessageToPeers(v *chat.Visor, pkroute util.PKRoute, m message.Message) error { fmt.Println("sendMessageToPeers") - pkroute := util.NewRoomRoute(m.GetDestinationVisor(), m.GetDestinationServer(), m.GetDestinationRoom()) + //pkroute := util.NewRoomRoute(m.GetDestinationVisor(), m.GetDestinationServer(), m.GetDestinationRoom()) - server, err := v.GetServerByPK(m.Dest.Server) + server, err := v.GetServerByPK(pkroute.Server) if err != nil { return err } - room, err := server.GetRoomByPK(m.Dest.Room) + room, err := server.GetRoomByPK(pkroute.Room) if err != nil { return err } @@ -478,3 +537,28 @@ func (ms MessengerService) sendMessageToPeers(v *chat.Visor, m message.Message) } return nil } + +// sendLocalRouteInfoToPeer sends the given message to a remote route as server +func (ms MessengerService) sendLocalRouteInfoToPeer(pkroute util.PKRoute, dest util.PKRoute, info info.Info) error { + bytes, err := json.Marshal(info) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + m := message.NewChatInfoMessage(pkroute, dest, bytes) + + err = ms.sendMessage(pkroute, m, true) + if err != nil { + return err + } + + //notify about sent text message + n := notification.NewMsgNotification(pkroute, m) + err = ms.ns.Notify(n) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go index 732d6def7..1a2e891fa 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go @@ -206,8 +206,26 @@ func (ms MessengerService) handleP2PConnMsgType(m message.Message) error { if err != nil { return err } - case message.ConnMsgTypeLeave: - return fmt.Errorf("commands are not allowed on p2p chats") + case message.ConnMsgTypeDelete, message.ConnMsgTypeLeave: + //get the visor + v, err := ms.visorRepo.GetByPK(pkroute.Visor) + if err != nil { + return err + } + + //add request message to visor route + v.AddMessage(pkroute, m) + err = ms.visorRepo.Set(*v) + if err != nil { + return err + } + + //notify that we received an accept message + n := notification.NewMsgNotification(pkroute, m) + err = ms.ns.Notify(n) + if err != nil { + return err + } default: return fmt.Errorf("incorrect data received") } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go index 2f73115c4..3c4ceb2c4 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go @@ -4,10 +4,12 @@ import ( "encoding/json" "fmt" + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) @@ -117,7 +119,7 @@ func (ms MessengerService) handleRemoteRoomConnMsgType(m message.Message) error return nil case message.ConnMsgTypeDelete: //? do we have to delete something here? --> maybe the peer wants to save the chat history and not delete it, therefore we would have to add some kind of flag or so, that - //? stops the user from sending any messages to the deleted chat/server + //? stops the peers from sending any messages to the deleted chat/server default: return fmt.Errorf("incorrect data received") } @@ -131,37 +133,79 @@ func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message. pkroute := util.NewRoomRoute(m.GetRootVisor(), m.GetRootServer(), m.GetRootRoom()) - //unmarshal the received message bytes to info.Info - i := info.Info{} - err := json.Unmarshal(m.Message, &i) - if err != nil { - return fmt.Errorf("failed to unmarshal json message: %v", err) - } - fmt.Println("---------------------------------------------------------------------------------------------------") - fmt.Printf("InfoMessage: \n") - fmt.Printf("Pk: %s \n", i.Pk.Hex()) - fmt.Printf("Alias: %s \n", i.Alias) - fmt.Printf("Desc: %s \n", i.Desc) - fmt.Printf("Img: %s \n", i.Img) - fmt.Println("---------------------------------------------------------------------------------------------------") + switch m.MsgSubtype { + case message.InfoMsgTypeSingle: - err = v.SetRouteInfo(pkroute, i) - if err != nil { - return err - } + //unmarshal the received message bytes to info.Info + i := info.Info{} + err := json.Unmarshal(m.Message, &i) + if err != nil { + return fmt.Errorf("failed to unmarshal json message: %v", err) + } + fmt.Println("---------------------------------------------------------------------------------------------------") + fmt.Printf("InfoMessage: \n") + fmt.Printf("Pk: %s \n", i.Pk.Hex()) + fmt.Printf("Alias: %s \n", i.Alias) + fmt.Printf("Desc: %s \n", i.Desc) + fmt.Printf("Img: %s \n", i.Img) + fmt.Println("---------------------------------------------------------------------------------------------------") + + err = v.SetRouteInfo(pkroute, i) + if err != nil { + return err + } - err = ms.visorRepo.Set(*v) - if err != nil { - return err - } + err = ms.visorRepo.Set(*v) + if err != nil { + return err + } - //notify about new info message - n := notification.NewMsgNotification(m.Root, m) - err = ms.ns.Notify(n) - if err != nil { - return err - } + //notify about new info message + n := notification.NewMsgNotification(pkroute, m) + err = ms.ns.Notify(n) + if err != nil { + return err + } + case message.InfoMsgTypeRoomMembers: + //unmarshal the received message bytes to map[cipher.Pubkey]peer.Peer + members := map[cipher.PubKey]peer.Peer{} + err := json.Unmarshal(m.Message, &members) + if err != nil { + return fmt.Errorf("failed to unmarshal json message: %v", err) + } + server, err := v.GetServerByPK(pkroute.Server) + if err != nil { + return err + } + room, err := server.GetRoomByPK(pkroute.Room) + if err != nil { + return err + } + room.Members = members + + err = server.SetRoom(*room) + if err != nil { + return err + } + err = v.SetServer(*server) + if err != nil { + return err + } + + err = ms.visorRepo.Set(*v) + if err != nil { + return err + } + + //notify about new info message + n := notification.NewMsgNotification(pkroute, m) + err = ms.ns.Notify(n) + if err != nil { + return err + } + + } return nil } From 474ae3513b52cbfc867188a3174eb1f67553efbc Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Sat, 18 Feb 2023 22:42:15 +0100 Subject: [PATCH 26/72] next commit --- .../app/chat/commands/delete_local_route.go | 38 ++++++- .../app/chat/commands/leave_remote_route.go | 8 +- .../internal/app/chat/commands/todos.go | 3 + .../internal/app/messenger/messenger.go | 3 + .../internal/app/notification/notification.go | 2 +- .../skychat/internal/domain/chat/server.go | 1 - .../skychat/internal/domain/chat/visor.go | 10 +- .../internal/domain/message/message.go | 16 ++- .../skychat/internal/domain/util/pkroute.go | 2 + .../internal/inputports/http/static/index.js | 11 +- .../messenger/netcon/messenger_service.go | 3 +- .../netcon/messenger_service_local_server.go | 100 ++++++++++++++---- .../messenger/netcon/messenger_service_p2p.go | 16 ++- 13 files changed, 162 insertions(+), 51 deletions(-) diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go b/cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go index 89c6056cb..ca73292c4 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go +++ b/cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go @@ -41,26 +41,56 @@ func (h deleteLocalRouteRequestHandler) Handle(command DeleteLocalRouteRequest) // if this, then we want to delete the whole server if command.Route.Server == command.Route.Room { - //TODO: Send Room-Delete-Message to Room members in every room? - //TODO: Send Server-Delete-Message to Server members + //Send Server-Delete-Message to Server members -> they then have to delete or disable the function to send new messages to the server + serverroute := util.NewServerRoute(command.Route.Visor, command.Route.Server) + err = h.messengerService.SendRouteDeletedMessage(serverroute) + if err != nil { + return err + } + + //Delete server from visor err = visor.DeleteServer(command.Route.Server) if err != nil { return err } + + //update visorrepository return h.visorRepo.Set(*visor) } // Check if room exists - _, err = server.GetRoomByPK(command.Route.Room) + room, err := server.GetRoomByPK(command.Route.Room) + if err != nil { + return err + } + + //Send Room-Deleted-Message to room members + err = h.messengerService.SendRouteDeletedMessage(command.Route) if err != nil { return err } - //TODO: Send Room-Delete-Message to Room members (and to server members, if room is public) + //if room is public/visibile also send message to server members + if room.GetIsVisible() { + serverroute := util.NewServerRoute(command.Route.Visor, command.Route.Server) + err = h.messengerService.SendRouteDeletedMessage(serverroute) + if err != nil { + return err + } + } + + //delete room from server err = server.DeleteRoom(command.Route.Room) if err != nil { return err } + //update visor + err = visor.SetServer(*server) + if err != nil { + return err + } + + //update visorrepository return h.visorRepo.Set(*visor) } diff --git a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go index b2e2b7e33..ab857429d 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go +++ b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go @@ -97,7 +97,13 @@ func (h leaveRemoteRouteRequestHandler) Handle(command LeaveRemoteRouteRequest) //check if this was the last room of the server if len(server.GetAllRooms()) == 0 { - //TODO: Send Leave-Server-Message + //Prepare ServerRoute + serverroute := util.NewServerRoute(command.Route.Server, command.Route.Server) + // Send LeaveChatMessage to remote server + err = h.ms.SendLeaveRouteMessage(serverroute) + if err != nil { + return err + } err = visor.DeleteServer(command.Route.Server) if err != nil { return err diff --git a/cmd/apps/skychat/internal/app/chat/commands/todos.go b/cmd/apps/skychat/internal/app/chat/commands/todos.go index 3508ccf70..e6dea59e4 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/todos.go +++ b/cmd/apps/skychat/internal/app/chat/commands/todos.go @@ -3,6 +3,8 @@ package commands //-to-dos and brain-storming about the future of skychat //general +//TODO: Sending json that are bigger than one packet -> otherwise big lists and sending the image info won't work. +//TODO: message statuses: sent, received(achieved by implementing the peer to send a 'received-message' back) to check whether the message really was received by the peer //TODO: database for user and visor repository //TODO: flags to setup if database or in-memory is used for repositories (data is lost when stoping app) //--> maybe even a way on setting this up for each chat, so simultaneously persistent chats and "deleteable" chats are possible @@ -29,6 +31,7 @@ package commands //make p2p room within own visor -> for informations from other apps or so? //server & rooms------------ +//TODO:send_set_route_info_message.go //TODO:send_hire_admin_message.go //maybe only allow this action from server-host //TODO:send_fire_admin_message.go //maybe only allow this action from server-host //TODO:send_hire_moderator_message.go diff --git a/cmd/apps/skychat/internal/app/messenger/messenger.go b/cmd/apps/skychat/internal/app/messenger/messenger.go index c3ac81b93..e4ece5e7b 100644 --- a/cmd/apps/skychat/internal/app/messenger/messenger.go +++ b/cmd/apps/skychat/internal/app/messenger/messenger.go @@ -21,4 +21,7 @@ type Service interface { SendDeleteRoomMessage(route util.PKRoute) error SendAddRoomMessage(route util.PKRoute, info info.Info) error SendInfoMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute, info info.Info) error + + //used as server + SendRouteDeletedMessage(pkroute util.PKRoute) error } diff --git a/cmd/apps/skychat/internal/app/notification/notification.go b/cmd/apps/skychat/internal/app/notification/notification.go index 763791f56..43b3e6a3d 100644 --- a/cmd/apps/skychat/internal/app/notification/notification.go +++ b/cmd/apps/skychat/internal/app/notification/notification.go @@ -21,7 +21,7 @@ const ( NewMsgNotifyType //DeleteChatNotifyType notifies about a deleted chat DeleteChatNotifyType - //? add SentMsgNotifyType + //FUTUREFEATURE: add SentMsgNotifyType ) // Notification provides a struct to send messages via the Service diff --git a/cmd/apps/skychat/internal/domain/chat/server.go b/cmd/apps/skychat/internal/domain/chat/server.go index 0884fd0de..3493f4ad8 100644 --- a/cmd/apps/skychat/internal/domain/chat/server.go +++ b/cmd/apps/skychat/internal/domain/chat/server.go @@ -146,7 +146,6 @@ func (s *Server) DeleteMember(pk cipher.PubKey) error { delete(s.Members, pk) return nil } - //TODO: also try to delete member from all rooms as he leaves the server delete(s.Members, pk) return nil } diff --git a/cmd/apps/skychat/internal/domain/chat/visor.go b/cmd/apps/skychat/internal/domain/chat/visor.go index bcbd5d327..969775c0d 100644 --- a/cmd/apps/skychat/internal/domain/chat/visor.go +++ b/cmd/apps/skychat/internal/domain/chat/visor.go @@ -85,10 +85,10 @@ func (v *Visor) AddP2P(p2p Room) error { // SetP2P updates the p2p-chat of the visor func (v *Visor) SetP2P(p2p Room) error { - //check if room exists - _, err := v.GetP2P() - if err != nil { + //check if p2p exists + if !v.P2PIsEmpty() { v.P2P = p2p + return nil } return fmt.Errorf("setp2p: p2p does not exist in visor") //? should this be treaded as an error like now? -> or maybe even call AddP2P when p2p does not exist? } @@ -96,9 +96,9 @@ func (v *Visor) SetP2P(p2p Room) error { // DeleteP2P removes the p2p-chat-room from the visor func (v *Visor) DeleteP2P() error { //check if p2p exists - _, err := v.GetP2P() - if err != nil { + if !v.P2PIsEmpty() { v.P2P = Room{} + return nil } return fmt.Errorf("deletep2p: p2p does not exist in visor") //? should this be treaded as an error like now? } diff --git a/cmd/apps/skychat/internal/domain/message/message.go b/cmd/apps/skychat/internal/domain/message/message.go index 1b092f283..df10c43ce 100644 --- a/cmd/apps/skychat/internal/domain/message/message.go +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -50,7 +50,7 @@ const ( InfoMsgTypeServerMembers //InfoMsgTypeRoomMembers is used to update the list of members of a room InfoMsgTypeRoomMembers - //TODO: Admins, Moderators, Muted, Blacklist, Whitelist, Rooms from Server that are visible + //FUTUREFEATURES: Admins, Moderators, Muted, Blacklist, Whitelist, Rooms from Server that are visible ) // types of messageStatus @@ -262,6 +262,20 @@ func NewChatLeaveMessage(root util.PKRoute, dest util.PKRoute) Message { return m } +// NewRouteDeletedMessage returns new message to info about deleted route +func NewRouteDeletedMessage(route util.PKRoute, dest util.PKRoute) Message { + m := Message{} + m.Origin = route.Visor + m.Root = route + m.Dest = dest + m.MsgType = ConnMsgType + m.MsgSubtype = ConnMsgTypeDelete + m.Message = []byte("Chat Deleted") + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + // NewChatInfoMessage returns new chat info func NewChatInfoMessage(root util.PKRoute, dest util.PKRoute, info []byte) Message { m := Message{} diff --git a/cmd/apps/skychat/internal/domain/util/pkroute.go b/cmd/apps/skychat/internal/domain/util/pkroute.go index 421c2d9d7..5fb40cae3 100644 --- a/cmd/apps/skychat/internal/domain/util/pkroute.go +++ b/cmd/apps/skychat/internal/domain/util/pkroute.go @@ -29,10 +29,12 @@ func NewP2PRoute(visorpk cipher.PubKey) PKRoute { } // NewServerRoute returns a new route of a server +// This is achieved by setting Room == Server func NewServerRoute(visorpk cipher.PubKey, serverpk cipher.PubKey) PKRoute { pkr := PKRoute{} pkr.Visor = visorpk pkr.Server = serverpk + pkr.Room = serverpk return pkr } diff --git a/cmd/apps/skychat/internal/inputports/http/static/index.js b/cmd/apps/skychat/internal/inputports/http/static/index.js index d4b7f8a03..c83dc7a21 100644 --- a/cmd/apps/skychat/internal/inputports/http/static/index.js +++ b/cmd/apps/skychat/internal/inputports/http/static/index.js @@ -1236,16 +1236,8 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa break; //NewMsgNotifType case 3: - //Fetch data of chat with new message from HTTP - console.log("new message notification") - //const message = JSON.parse(notifMessage.message) - //visorpk = message.Root.Visor - //serverpk = message.Root.Server - //roompk = message.Root.Room - //route = new Route(visorpk,serverpk,roompk) - //console.log(message) - + //Fetch data of chat with new message from HTTP await this.getRoomByRoute(route).then(c => { if (this.chats == null){ this.chats = [] @@ -1293,6 +1285,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa return this.chats[this.getChatIndexFromRoute(route)].messages; } + //TODO: return fixed strings depending on type of last message (e.g. InfoType or so) //returns the last [Message] of the given pk/chat getLastMessageFromRoute(route){ let arr = this.chats; diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index 037bd9a4b..61880034c 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -7,7 +7,6 @@ import ( "fmt" "net" "time" - "unsafe" "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/netutil" @@ -278,7 +277,7 @@ func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, fmt.Printf("Status: %d \n", m.Status) fmt.Printf("Seen: %t \n", m.Seen) fmt.Println("---------------------------------------------------------------------------------------------------") - fmt.Printf("Message Size: %T, %d\n", m, unsafe.Sizeof(m)) + //fmt.Printf("Message Size: %T, %d\n", m, unsafe.Sizeof(m)) fmt.Println("---------------------------------------------------------------------------------------------------") rm := message.NewRAWMessage(m) diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go index 9335c1f5f..0525e3455 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go @@ -5,6 +5,7 @@ import ( "fmt" "strconv" + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" @@ -239,6 +240,16 @@ func (ms MessengerService) handleLocalServerConnMsgType(visor *chat.Visor, m mes case message.ConnMsgTypeLeave, message.ConnMsgTypeDelete: // if pkroute defines room, remove from room membership if pkroute.Server != pkroute.Room { + //add request message to room + room.AddMessage(m) + + //send message to peers + err = ms.sendMessageToPeers(visor, pkroute, m) + if err != nil { + return err + } + + //delete member from room err = room.DeleteMember(m.Origin) if err != nil { return err @@ -272,9 +283,9 @@ func (ms MessengerService) handleLocalServerConnMsgType(visor *chat.Visor, m mes return err } - //TODO: for each room and the server: send new member-list to members + //TODO: for each room and the server: send new member-list to members (where the peer was a member) } - //update visor and respository + //update visor and repository err = visor.SetServer(*server) if err != nil { return err @@ -310,19 +321,20 @@ func (ms MessengerService) handleLocalServerCmdMsgType(visor *chat.Visor, m mess return err } - //unmarshal the received message bytes to info.Info //FIXME: unmarshal to other thing than info - i := info.Info{} - err = json.Unmarshal(m.Message, &i) - if err != nil { - return fmt.Errorf("failed to unmarshal json message: %v", err) - } - switch m.MsgSubtype { case message.CmdMsgTypeAddRoom: //First check if origin of msg is admin if _, isAdmin := server.GetAllAdmin()[m.Root.Visor]; !isAdmin { return fmt.Errorf("command not accepted, no admin") } + + //unmarshal the received message bytes to info.Info + i := info.Info{} + err = json.Unmarshal(m.Message, &i) + if err != nil { + return fmt.Errorf("failed to unmarshal json message: %v", err) + } + // make a new route rr := util.NewLocalRoomRoute(m.Dest.Visor, m.Dest.Server, server.GetAllRoomsBoolMap()) @@ -337,7 +349,7 @@ func (ms MessengerService) handleLocalServerCmdMsgType(visor *chat.Visor, m mess return err } - //TODO: if room is visible/public also add messengerService and send 'Room-Added' Message to Members of server + //FUTUREFEATURE: if room is visible/public also add messengerService and send 'Room-Added' Message to Members of server // add room to server, update visor and then update repository err = server.AddRoom(room) @@ -366,9 +378,15 @@ func (ms MessengerService) handleLocalServerCmdMsgType(visor *chat.Visor, m mess if _, isAdmin := server.GetAllAdmin()[m.Root.Visor]; !isAdmin { return fmt.Errorf("command not accepted, no admin") } - //TODO: handle message - //send DeleteChatMessage to all members - //? do we have to differ between deleting the chat and stopping the service of forwarding and accepting any message? + + //prepare NewRooomDeletedMessage and send it to all members + msg := message.NewRouteDeletedMessage(pkroute, pkroute) + + err = ms.sendMessageToPeers(visor, pkroute, msg) + if err != nil { + return err + } + return nil //[] add other cmd messages default: @@ -423,8 +441,7 @@ func (ms MessengerService) handleLocalServerInfoMsgType(v *chat.Visor, m message return err } - //TODO: send updated info of member to all members - //FIXME: START: for the moment lets just update the whole list + //FIXME: START: for the moment lets just update the whole list, but in the future only send the updated peer info to reduce sent data server, err := v.GetServerByPK(m.Dest.Server) if err != nil { return err @@ -452,7 +469,6 @@ func (ms MessengerService) handleLocalServerInfoMsgType(v *chat.Visor, m message err = ms.sendMessageToPeers(v, pkroute, msg) if err != nil { return err - } //FIXME: END return nil @@ -501,23 +517,30 @@ func (ms MessengerService) handleLocalRoomTextMsgType(visor *chat.Visor, m messa return nil } -// +//sendMessageToPeers sends the given message to all peers of the given route func (ms MessengerService) sendMessageToPeers(v *chat.Visor, pkroute util.PKRoute, m message.Message) error { fmt.Println("sendMessageToPeers") - //pkroute := util.NewRoomRoute(m.GetDestinationVisor(), m.GetDestinationServer(), m.GetDestinationRoom()) - server, err := v.GetServerByPK(pkroute.Server) if err != nil { return err } - room, err := server.GetRoomByPK(pkroute.Room) - if err != nil { - return err + var members map[cipher.PubKey]peer.Peer + + if pkroute.Room != pkroute.Server { + room, err := server.GetRoomByPK(pkroute.Room) + if err != nil { + return err + } + members = room.GetAllMembers() + } else { + members = server.GetAllMembers() } - members := room.GetAllMembers() + if len(members) == 0 { + fmt.Printf("No members to send message to") + } for _, peer := range members { @@ -562,3 +585,34 @@ func (ms MessengerService) sendLocalRouteInfoToPeer(pkroute util.PKRoute, dest u return nil } + +// SendRouteDeletedMessage sends a ConnMsgType to all members of route to inform them that the route got deleted by the server +func (ms MessengerService) SendRouteDeletedMessage(pkroute util.PKRoute) error { + //Check if visor exists + visor, err := ms.visorRepo.GetByPK(pkroute.Visor) + if err != nil { + return err + } + + //Check if server exists + server, err := visor.GetServerByPK(pkroute.Server) + if err != nil { + return err + } + + if pkroute.Server != pkroute.Room { + //Check if room exists + _, err := server.GetRoomByPK(pkroute.Room) + if err != nil { + return err + } + } + //prepare NewRooomDeletedMessage and send it to all members + msg := message.NewRouteDeletedMessage(pkroute, pkroute) + + err = ms.sendMessageToPeers(visor, pkroute, msg) + if err != nil { + return err + } + return nil +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go index 1a2e891fa..8f65c53e9 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go @@ -122,8 +122,7 @@ func (ms MessengerService) handleP2PConnMsgType(m message.Message) error { } //check if p2p already exists in repository - _, err = v.GetP2P() - if err != nil { + if v.P2PIsEmpty() { //make new default p2p room and add it to the visor fmt.Println("Make new P2P room") p2p := chat.NewDefaultP2PRoom(pkroute.Visor) @@ -166,8 +165,17 @@ func (ms MessengerService) handleP2PConnMsgType(m message.Message) error { if err != nil { return err } - //TODO: !! we first have to check whether we don't have got any other servers of this visor saved - //deletes the visor from the repository + + // we first have to check whether we don't have got any other servers of this visor saved + v, err := ms.visorRepo.GetByPK(pkroute.Visor) + if err != nil { + return err + } + if len(v.GetAllServer()) != 0 { + return nil + } + + //deletes the visor from the repository if no other servers of the visor are saved err = ms.visorRepo.Delete(pkroute.Visor) if err != nil { return err From ffc2be5bb0886f44f48909b36d00eeff8aae0638 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Sun, 19 Feb 2023 00:40:28 +0100 Subject: [PATCH 27/72] [backend] add un/mute peer functionality --- .../chat/commands/send_mute_peer_message.go | 38 +++++ .../chat/commands/send_unmute_peer_message.go | 38 +++++ .../internal/app/chat/commands/todos.go | 14 +- .../skychat/internal/app/chat/services.go | 4 + .../internal/app/messenger/messenger.go | 4 + .../internal/domain/message/message.go | 54 ++++++- .../internal/inputports/http/chat/handler.go | 146 ++++++++++++++++++ .../internal/inputports/http/server.go | 2 + .../messenger/netcon/messenger_service.go | 64 ++++++++ .../netcon/messenger_service_local_server.go | 82 +++++++++- .../netcon/messenger_service_remote_server.go | 41 +++++ 11 files changed, 473 insertions(+), 14 deletions(-) create mode 100644 cmd/apps/skychat/internal/app/chat/commands/send_mute_peer_message.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/send_unmute_peer_message.go diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_mute_peer_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_mute_peer_message.go new file mode 100644 index 000000000..9a7b0c631 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/send_mute_peer_message.go @@ -0,0 +1,38 @@ +// Package commands contains commands to send text message +package commands + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// SendMutePeerMessageRequest of SendMutePeerMessageRequestHandler +type SendMutePeerMessageRequest struct { + Route util.PKRoute + Pk cipher.PubKey +} + +// SendMutePeerMessageRequestHandler struct that allows handling SendMutePeerMessageRequest +type SendMutePeerMessageRequestHandler interface { + Handle(command SendMutePeerMessageRequest) error +} + +type sendMutePeerMessageRequestHandler struct { + messengerService messenger.Service +} + +// NewSendMutePeerMessageRequestHandler Initializes an AddCommandHandler +func NewSendMutePeerMessageRequestHandler(messengerService messenger.Service) SendMutePeerMessageRequestHandler { + return sendMutePeerMessageRequestHandler{messengerService: messengerService} +} + +// Handle handles the SendMutePeerMessageRequest +func (h sendMutePeerMessageRequestHandler) Handle(command SendMutePeerMessageRequest) error { + err := h.messengerService.SendMutePeerMessage(command.Route, command.Pk) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_unmute_peer_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_unmute_peer_message.go new file mode 100644 index 000000000..92403e471 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/send_unmute_peer_message.go @@ -0,0 +1,38 @@ +// Package commands contains commands to send text message +package commands + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// SendUnmutePeerMessageRequest of SendUnmutePeerMessageRequestHandler +type SendUnmutePeerMessageRequest struct { + Route util.PKRoute + Pk cipher.PubKey +} + +// SendUnmutePeerMessageRequestHandler struct that allows handling SendUnmutePeerMessageRequest +type SendUnmutePeerMessageRequestHandler interface { + Handle(command SendUnmutePeerMessageRequest) error +} + +type sendUnmutePeerMessageRequestHandler struct { + messengerService messenger.Service +} + +// NewSendUnmutePeerMessageRequestHandler Initializes an AddCommandHandler +func NewSendUnmutePeerMessageRequestHandler(messengerService messenger.Service) SendUnmutePeerMessageRequestHandler { + return sendUnmutePeerMessageRequestHandler{messengerService: messengerService} +} + +// Handle handles the SendUnmutePeerMessageRequest +func (h sendUnmutePeerMessageRequestHandler) Handle(command SendUnmutePeerMessageRequest) error { + err := h.messengerService.SendUnmutePeerMessage(command.Route, command.Pk) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/todos.go b/cmd/apps/skychat/internal/app/chat/commands/todos.go index e6dea59e4..60893a811 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/todos.go +++ b/cmd/apps/skychat/internal/app/chat/commands/todos.go @@ -6,17 +6,17 @@ package commands //TODO: Sending json that are bigger than one packet -> otherwise big lists and sending the image info won't work. //TODO: message statuses: sent, received(achieved by implementing the peer to send a 'received-message' back) to check whether the message really was received by the peer //TODO: database for user and visor repository -//TODO: flags to setup if database or in-memory is used for repositories (data is lost when stoping app) +//FUTUREFEATUE: flags to setup if database or in-memory is used for repositories (data is lost when stoping app) //--> maybe even a way on setting this up for each chat, so simultaneously persistent chats and "deleteable" chats are possible //--> how about "self-deleting-messages"? deletes itself after (1hour, 24hour, etc...) //TODO: cli-interface //with cli-interface a connection with the systray app would be possible -> notifications about new messages, incoming calls etc. -//TODO: encrypted messages (encrypted sending and encrypted saving on local storage) --> Password for app required +//FUTUREFEATUE: encrypted messages (encrypted sending and encrypted saving on local storage) --> Password for app required //general-future -//TODO: voip-channels -//TODO: video-streams -//TODO: sending-fiber via chat, with notification about received payments -> also sending-fiber-requests +//FUTUREFEATUE: voip-channels +//FUTUREFEATUE: video-streams +//FUTUREFEATUE: sending-fiber via chat, with notification about received payments -> also sending-fiber-requests //UI //TODO:Make UI more beautiful @@ -36,8 +36,8 @@ package commands //TODO:send_fire_admin_message.go //maybe only allow this action from server-host //TODO:send_hire_moderator_message.go //TODO:send_fire_moderator_message.go -//TODO:send_mute_peer_message.go -//TODO:send_unmute_peer_message.go +//[x]send_mute_peer_message.go --> backend implemented, frontend missing +//[x]:send_unmute_peer_message.go --> backend implemented, frontend missing //TODO:send_add_room_message.go //TODO:send_delete_room_message.go diff --git a/cmd/apps/skychat/internal/app/chat/services.go b/cmd/apps/skychat/internal/app/chat/services.go index 610c26857..262b284ec 100644 --- a/cmd/apps/skychat/internal/app/chat/services.go +++ b/cmd/apps/skychat/internal/app/chat/services.go @@ -29,6 +29,8 @@ type Commands struct { SendAddRoomMessageHandler commands.SendAddRoomMessageRequestHandler SendDeleteRoomMessageHandler commands.SendDeleteRoomMessageRequestHandler SendTextMessageHandler commands.SendTextMessageRequestHandler + SendMutePeerMessageHandler commands.SendMutePeerMessageRequestHandler + SendUnmutePeerMessageHandler commands.SendUnmutePeerMessageRequestHandler } // ChatServices Contains the grouped queries and commands of the app layer @@ -55,6 +57,8 @@ func NewServices(cliRepo client.Repository, visorRepo chat.Repository, userRepo SendAddRoomMessageHandler: commands.NewSendAddRoomMessageRequestHandler(ms), SendDeleteRoomMessageHandler: commands.NewSendDeleteRoomMessageRequestHandler(ms), SendTextMessageHandler: commands.NewSendTextMessageRequestHandler(ms), + SendMutePeerMessageHandler: commands.NewSendMutePeerMessageRequestHandler(ms), + SendUnmutePeerMessageHandler: commands.NewSendUnmutePeerMessageRequestHandler(ms), }, } } diff --git a/cmd/apps/skychat/internal/app/messenger/messenger.go b/cmd/apps/skychat/internal/app/messenger/messenger.go index e4ece5e7b..c8fed9d35 100644 --- a/cmd/apps/skychat/internal/app/messenger/messenger.go +++ b/cmd/apps/skychat/internal/app/messenger/messenger.go @@ -24,4 +24,8 @@ type Service interface { //used as server SendRouteDeletedMessage(pkroute util.PKRoute) error + + //used as client + SendMutePeerMessage(pkroute util.PKRoute, pk cipher.PubKey) error + SendUnmutePeerMessage(pkroute util.PKRoute, pk cipher.PubKey) error } diff --git a/cmd/apps/skychat/internal/domain/message/message.go b/cmd/apps/skychat/internal/domain/message/message.go index df10c43ce..21b7c940d 100644 --- a/cmd/apps/skychat/internal/domain/message/message.go +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -50,6 +50,8 @@ const ( InfoMsgTypeServerMembers //InfoMsgTypeRoomMembers is used to update the list of members of a room InfoMsgTypeRoomMembers + //InfoMsgTypeRoomMuted is used to update the list of muted of a room + InfoMsgTypeRoomMuted //FUTUREFEATURES: Admins, Moderators, Muted, Blacklist, Whitelist, Rooms from Server that are visible ) @@ -71,9 +73,11 @@ const ( CmdMsgTypeAddRoom // CmdMsgTypeDeleteRoom is used to delete a room CmdMsgTypeDeleteRoom - /*CmdMsgTypeMutePeer + // CmdMsgTypeMutePeer is used to mute a peer + CmdMsgTypeMutePeer + // CmdMsgTypeUnmutePeer is used tu unmute a peer CmdMsgTypeUnmutePeer - CmdMsgTypeBanPeer + /*CmdMsgTypeBanPeer CmdMsgTypeUnbanPeer CmdMsgTypeHireAdmin CmdMsgTypeFireAdmin @@ -218,7 +222,9 @@ func NewRouteRequestMessage(pkOrigin cipher.PubKey, routeDestination util.PKRout return m } -/* NewChatAcceptMessage returns a chat accepted message +/* + NewChatAcceptMessage returns a chat accepted message + pk is the users pk to set the messages root */ func NewChatAcceptMessage(root util.PKRoute, dest util.PKRoute) Message { @@ -332,6 +338,48 @@ func NewRoomMembersMessage(root util.PKRoute, dest util.PKRoute, members []byte) return m } +// NewRoomMutedMessage returns a Message of muted pks of room +func NewRoomMutedMessage(root util.PKRoute, dest util.PKRoute, muted []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = InfoMsgType + m.MsgSubtype = InfoMsgTypeRoomMuted + m.Message = muted + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + +// NewMutePeerMessage returns a Message to mute a peer +func NewMutePeerMessage(root util.PKRoute, dest util.PKRoute, pk []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = CmdMsgType + m.MsgSubtype = CmdMsgTypeMutePeer + m.Message = pk + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + +// NewUnmutePeerMessage returns a Message to mute a peer +func NewUnmutePeerMessage(root util.PKRoute, dest util.PKRoute, pk []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = CmdMsgType + m.MsgSubtype = CmdMsgTypeUnmutePeer + m.Message = pk + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + // GetID returns message ID func (m *Message) GetID() int { return m.ID diff --git a/cmd/apps/skychat/internal/inputports/http/chat/handler.go b/cmd/apps/skychat/internal/inputports/http/chat/handler.go index d0fd16506..cf5e5e237 100644 --- a/cmd/apps/skychat/internal/inputports/http/chat/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/chat/handler.go @@ -275,6 +275,152 @@ func (c Handler) SendAddRoomMessage(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } +// SendMutePeerMessageURLParam contains the parameter identifier to be parsed by the handler +const SendMutePeerMessageURLParam = "sendMutePeerMessage" + +// SendMutePeerMessageRequestModel represents the request model expected for Delete request +type SendMutePeerMessageRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` + + PeerPk string `json:"peerpk"` +} + +// SendMutePeerMessage sends a mute message to the given route +func (c Handler) SendMutePeerMessage(w http.ResponseWriter, r *http.Request) { + var requestModel SendMutePeerMessageRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr.Error()) + return + } + + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + err := visorpk.Set(requestModel.VisorPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Visor = visorpk + if requestModel.ServerPk != "" { + serverpk := cipher.PubKey{} + err = serverpk.Set(requestModel.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + if requestModel.RoomPk != "" { + roompk := cipher.PubKey{} + err = roompk.Set(requestModel.RoomPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Room = roompk + } + } + + peerpk := cipher.PubKey{} + err = peerpk.Set(requestModel.PeerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + + err = c.chatServices.Commands.SendMutePeerMessageHandler.Handle(commands.SendMutePeerMessageRequest{ + Route: route, + Pk: peerpk, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + w.WriteHeader(http.StatusOK) +} + +// SendMutePeerMessageURLParam contains the parameter identifier to be parsed by the handler +const SendUnmutePeerMessageURLParam = "sendUnmutePeerMessage" + +// SendUnmutePeerMessageRequestModel represents the request model expected for Delete request +type SendUnmutePeerMessageRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` + + PeerPk string `json:"peerpk"` +} + +// SendUnmutePeerMessage sends an unmute message to the given route +func (c Handler) SendUnmutePeerMessage(w http.ResponseWriter, r *http.Request) { + var requestModel SendUnmutePeerMessageRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr.Error()) + return + } + + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + err := visorpk.Set(requestModel.VisorPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Visor = visorpk + if requestModel.ServerPk != "" { + serverpk := cipher.PubKey{} + err = serverpk.Set(requestModel.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + if requestModel.RoomPk != "" { + roompk := cipher.PubKey{} + err = roompk.Set(requestModel.RoomPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Room = roompk + } + } + + peerpk := cipher.PubKey{} + err = peerpk.Set(requestModel.PeerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + + err = c.chatServices.Commands.SendUnmutePeerMessageHandler.Handle(commands.SendUnmutePeerMessageRequest{ + Route: route, + Pk: peerpk, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + w.WriteHeader(http.StatusOK) +} + // DeleteLocalRouteURLParam contains the parameter identifier to be parsed by the handler const DeleteLocalRouteURLParam = "DeleteLocalRoute" diff --git a/cmd/apps/skychat/internal/inputports/http/server.go b/cmd/apps/skychat/internal/inputports/http/server.go index 93d9f83e9..65999145b 100644 --- a/cmd/apps/skychat/internal/inputports/http/server.go +++ b/cmd/apps/skychat/internal/inputports/http/server.go @@ -68,6 +68,8 @@ func (httpServer *Server) AddChatHTTPRoutes() { httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendAddRoomMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendAddRoomMessage).Methods("POST") httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendDeleteRoomMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendDeleteRoomMessage).Methods("POST") httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendTextMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendTextMessage).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendMutePeerMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendMutePeerMessage).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendUnmutePeerMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendUnmutePeerMessage).Methods("POST") } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index 61880034c..4b1cc7311 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -458,6 +458,70 @@ func (ms MessengerService) SendDeleteRoomMessage(route util.PKRoute) error { return nil } +// SendMutePeerMessage sends a command message to mute a peer in the given route +func (ms MessengerService) SendMutePeerMessage(pkroute util.PKRoute, pk cipher.PubKey) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + bytes, err := json.Marshal(pk) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) + + msg := message.NewMutePeerMessage(root, pkroute, bytes) + + if msg.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(msg) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(msg) + if err != nil { + return err + } + } + return nil +} + +// SendUnmutePeerMessage sends a command message to unmute a peer in the given route +func (ms MessengerService) SendUnmutePeerMessage(pkroute util.PKRoute, pk cipher.PubKey) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + bytes, err := json.Marshal(pk) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) + + msg := message.NewUnmutePeerMessage(root, pkroute, bytes) + + if msg.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(msg) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(msg) + if err != nil { + return err + } + } + return nil +} + // sendMessageToRemoteRoute sends the given message to a remote route (as p2p and client) func (ms MessengerService) sendMessageToRemoteRoute(msg message.Message) error { //if the message goes to p2p we save it in database, if not we wait for the remote server to send us our message diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go index 0525e3455..a79ed984a 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go @@ -388,7 +388,81 @@ func (ms MessengerService) handleLocalServerCmdMsgType(visor *chat.Visor, m mess } return nil - //[] add other cmd messages + case message.CmdMsgTypeMutePeer: + //check if room exists + room, err := server.GetRoomByPK(pkroute.Room) + if err != nil { + return err + } + //First check if origin of msg is either admin or moderator of room + _, isAdmin := server.GetAllAdmin()[m.Root.Visor] + _, isMod := room.GetAllMods()[m.Root.Visor] + + if isAdmin || isMod { + //unmarshal the received message bytes to cipher.PubKey + pk := cipher.PubKey{} + err = json.Unmarshal(m.Message, &pk) + if err != nil { + return fmt.Errorf("failed to unmarshal json message: %v", err) + } + err = room.AddMuted(pk) + if err != nil { + return err + } + + //send updated list of Muted to peers + muted := room.GetAllMuted() + bytes, err := json.Marshal(muted) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + msg := message.NewRoomMutedMessage(pkroute, pkroute, bytes) + + err = ms.sendMessageToPeers(visor, pkroute, msg) + if err != nil { + return err + } + } + return nil + case message.CmdMsgTypeUnmutePeer: + //check if room exists + room, err := server.GetRoomByPK(pkroute.Room) + if err != nil { + return err + } + //First check if origin of msg is either admin or moderator of room + _, isAdmin := server.GetAllAdmin()[m.Root.Visor] + _, isMod := room.GetAllMods()[m.Root.Visor] + + if isAdmin || isMod { + //unmarshal the received message bytes to cipher.PubKey + pk := cipher.PubKey{} + err = json.Unmarshal(m.Message, &pk) + if err != nil { + return fmt.Errorf("failed to unmarshal json message: %v", err) + } + err = room.DeleteMuted(pk) + if err != nil { + return err + } + + //send updated list of Muted to peers + muted := room.GetAllMuted() + bytes, err := json.Marshal(muted) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + msg := message.NewRoomMutedMessage(pkroute, pkroute, bytes) + + err = ms.sendMessageToPeers(visor, pkroute, msg) + if err != nil { + return err + } + } + return nil + //FUTUREFEATURES: add other cmd messages default: return fmt.Errorf("incorrect data received") } @@ -498,12 +572,12 @@ func (ms MessengerService) handleLocalRoomTextMsgType(visor *chat.Visor, m messa return err } - //check if in muted in server + //check if muted in server if _, ok := server.GetAllMuted()[m.Origin]; ok { return nil } - //check if in muted in room + //check if muted in room if _, ok := room.GetAllMuted()[m.Origin]; ok { return nil } @@ -517,7 +591,7 @@ func (ms MessengerService) handleLocalRoomTextMsgType(visor *chat.Visor, m messa return nil } -//sendMessageToPeers sends the given message to all peers of the given route +// sendMessageToPeers sends the given message to all peers of the given route func (ms MessengerService) sendMessageToPeers(v *chat.Visor, pkroute util.PKRoute, m message.Message) error { fmt.Println("sendMessageToPeers") diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go index 3c4ceb2c4..f4f1946b7 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go @@ -181,6 +181,8 @@ func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message. if err != nil { return err } + + //TODO: make method instead of direct access of variable room.Members = members err = server.SetRoom(*room) @@ -204,7 +206,46 @@ func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message. if err != nil { return err } + case message.InfoMsgTypeRoomMuted: + //unmarshal the received message bytes to map[cipher.Pubkey]bool + muted := map[cipher.PubKey]bool{} + err := json.Unmarshal(m.Message, &muted) + if err != nil { + return fmt.Errorf("failed to unmarshal json message: %v", err) + } + server, err := v.GetServerByPK(pkroute.Server) + if err != nil { + return err + } + room, err := server.GetRoomByPK(pkroute.Room) + if err != nil { + return err + } + + //TODO: make method instead of direct access of variable + room.Muted = muted + + err = server.SetRoom(*room) + if err != nil { + return err + } + err = v.SetServer(*server) + if err != nil { + return err + } + + err = ms.visorRepo.Set(*v) + if err != nil { + return err + } + + //notify about new info message + n := notification.NewMsgNotification(pkroute, m) + err = ms.ns.Notify(n) + if err != nil { + return err + } } return nil } From 81a56dce4fa788f615bc60134817a8e0991b72ed Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Sun, 19 Feb 2023 13:46:04 +0100 Subject: [PATCH 28/72] fix check-windows output --- .../app/chat/commands/add_local_server.go | 2 +- cmd/apps/skychat/internal/domain/chat/room.go | 17 +++++++++-------- .../skychat/internal/domain/message/message.go | 7 ++----- .../internal/inputports/http/chat/handler.go | 2 +- .../messenger/netcon/messenger_service.go | 2 +- 5 files changed, 14 insertions(+), 16 deletions(-) diff --git a/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go b/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go index 458bf993d..8ca933a50 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go +++ b/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go @@ -40,7 +40,7 @@ func (h addLocalServerRequestHandler) Handle(command AddLocalServerRequest) erro } // Check if local visor exists, if not add the default local visor - visor := chat.Visor{} + var visor chat.Visor pVisor, err := h.visorRepo.GetByPK(usr.GetInfo().GetPK()) if err != nil { visor = chat.NewUndefinedVisor(usr.GetInfo().GetPK()) diff --git a/cmd/apps/skychat/internal/domain/chat/room.go b/cmd/apps/skychat/internal/domain/chat/room.go index 619cdd338..41f926891 100644 --- a/cmd/apps/skychat/internal/domain/chat/room.go +++ b/cmd/apps/skychat/internal/domain/chat/room.go @@ -30,14 +30,15 @@ const DefaultRoomType = ChatRoomType // A Room always is a part of a server // A Server is always a part of a visor // So you can think of this hierarchial structure: -// (Visor (PublicKey1)) -// -> P2P-Room -// -> Server1 (PublicKey1.1) -// -> Room1 (PublicKey1.1.1) -// -> Room2 (PublicKey1.1.2) -// -> Room3 (PublicKey1.1.2) -// -> Server2 (PublicKey1.2) -// -> Room1 (PublicKey1.2.1) +// +// (Visor (PublicKey1)) +// -> P2P-Room +// -> Server1 (PublicKey1.1) +// -> Room1 (PublicKey1.1.1) +// -> Room2 (PublicKey1.1.2) +// -> Room3 (PublicKey1.1.2) +// -> Server2 (PublicKey1.2) +// -> Room1 (PublicKey1.2.1) type Room struct { //P2P & Server PKRoute util.PKRoute // P2P: send // Server: only send when room isVisible diff --git a/cmd/apps/skychat/internal/domain/message/message.go b/cmd/apps/skychat/internal/domain/message/message.go index 21b7c940d..3f65ac28e 100644 --- a/cmd/apps/skychat/internal/domain/message/message.go +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -222,11 +222,8 @@ func NewRouteRequestMessage(pkOrigin cipher.PubKey, routeDestination util.PKRout return m } -/* - NewChatAcceptMessage returns a chat accepted message - -pk is the users pk to set the messages root -*/ +// NewChatAcceptMessage returns a chat accepted message +// pk is the users pk to set the messages root func NewChatAcceptMessage(root util.PKRoute, dest util.PKRoute) Message { m := Message{} m.Origin = root.Visor diff --git a/cmd/apps/skychat/internal/inputports/http/chat/handler.go b/cmd/apps/skychat/internal/inputports/http/chat/handler.go index cf5e5e237..6c617a0cd 100644 --- a/cmd/apps/skychat/internal/inputports/http/chat/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/chat/handler.go @@ -348,7 +348,7 @@ func (c Handler) SendMutePeerMessage(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -// SendMutePeerMessageURLParam contains the parameter identifier to be parsed by the handler +// SendUnmutePeerMessageURLParam contains the parameter identifier to be parsed by the handler const SendUnmutePeerMessageURLParam = "sendUnmutePeerMessage" // SendUnmutePeerMessageRequestModel represents the request model expected for Delete request diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index 4b1cc7311..e1037839f 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -200,7 +200,7 @@ func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, //check if visor exists v, err := ms.visorRepo.GetByPK(pkroute.Visor) if err != nil { - v2 := chat.Visor{} + var v2 chat.Visor //visor doesn't exist so we add a new remote route if pkroute.Visor == pkroute.Server { // --> P2P remote route v2 = chat.NewDefaultP2PVisor(pkroute.Visor) From 330eda760f31d4cc00fe3ca984aa0876be4af7f4 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Thu, 30 Mar 2023 17:48:06 +0200 Subject: [PATCH 29/72] fix build path in windows the build path of the apps was changed from ./apps to ./build/apps in linux, but not in windows. This change fixes the build path on windows --- Makefile | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index b24e6ff3a..faffaa554 100644 --- a/Makefile +++ b/Makefile @@ -214,12 +214,12 @@ example-apps: ## Build example apps ${OPTS} go build ${BUILD_OPTS} -o $(BUILD_PATH)apps/ ./example/example-server-app host-apps-windows: ## build apps on windows - powershell -Command new-item .\apps -itemtype directory -force - powershell 'Get-ChildItem .\cmd\apps | % { ${OPTS} go build ${BUILD_OPTS} -o ./apps $$_.FullName }' + powershell -Command new-item $(BUILD_PATH)apps/ -itemtype directory -force + powershell 'Get-ChildItem .\cmd\apps | % { ${OPTS} go build ${BUILD_OPTS} -o $(BUILD_PATH)apps/ $$_.FullName }' host-apps-windows-appveyor: ## build apps on windows. `go build` with ${OPTS} for AppVeyor image - powershell -Command new-item .\apps -itemtype directory -force - powershell 'Get-ChildItem .\cmd\apps | % { ${OPTS} go build -o ./apps $$_.FullName }' + powershell -Command new-item $(BUILD_PATH)apps/ -itemtype directory -force + powershell 'Get-ChildItem .\cmd\apps | % { ${OPTS} go build -o $(BUILD_PATH)apps/ $$_.FullName }' # Static Apps host-apps-static: ## Build app From 3a8edc8b34b18c63c7d64d1883a5b56ae4d3481c Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Thu, 30 Mar 2023 17:49:43 +0200 Subject: [PATCH 30/72] fix to stop hangups sometimes the processing of the sent messages seem to hangup, this fix looks like it helps to prevent those hangups --- .../interfaceadapters/messenger/netcon/messenger_service.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index e1037839f..ea3bcbec7 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -107,11 +107,11 @@ func (ms MessengerService) Handle(pk cipher.PubKey) { fmt.Println("---------------------------------------------------------------------------------------------------") if jm.GetDestinationVisor() == localPK && jm.GetDestinationServer() == localPK && jm.GetDestinationRoom() == localPK && jm.GetRootVisor() == jm.GetRootServer() && jm.GetRootServer() == jm.GetRootRoom() { - err = ms.handleP2PMessage(jm) + go ms.handleP2PMessage(jm) } else if jm.GetRootVisor() != jm.GetRootServer() && jm.GetRootServer() != jm.GetRootRoom() { - err = ms.handleRemoteServerMessage(jm) + go ms.handleRemoteServerMessage(jm) } else if jm.GetDestinationVisor() == localPK && jm.GetDestinationVisor() != jm.GetDestinationServer() && jm.GetDestinationServer() != jm.GetDestinationRoom() { - err = ms.handleLocalServerMessage(jm) + go ms.handleLocalServerMessage(jm) } else { fmt.Println("received message that can't be matched to remote or local server or p2p chat") } From fc02d3afb130e81f3a4ff062440754a05093956f Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Sat, 1 Apr 2023 23:39:31 +0200 Subject: [PATCH 31/72] export User attributes --- cmd/apps/skychat/internal/domain/user/user.go | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/cmd/apps/skychat/internal/domain/user/user.go b/cmd/apps/skychat/internal/domain/user/user.go index d0c2621a8..10742d9b8 100644 --- a/cmd/apps/skychat/internal/domain/user/user.go +++ b/cmd/apps/skychat/internal/domain/user/user.go @@ -11,39 +11,39 @@ import ( // User defines the user type User struct { - info info.Info // the info of the local user - settings settings.Settings // the settings of the local user - peerbook peer.Peerbook // the contactsbook of the local user + Info info.Info // the info of the local user + Settings settings.Settings // the settings of the local user + Peerbook peer.Peerbook // the contactsbook of the local user } // GetInfo gets the user info func (u *User) GetInfo() *info.Info { - return &u.info + return &u.Info } // GetSettings returns *settings.Settings func (u *User) GetSettings() *settings.Settings { - return &u.settings + return &u.Settings } // GetPeerbook returns the peerbook func (u *User) GetPeerbook() *peer.Peerbook { - return &u.peerbook + return &u.Peerbook } // SetInfo sets the user's info func (u *User) SetInfo(i info.Info) { - u.info = i + u.Info = i } // SetSettings applies settings func (u *User) SetSettings(s settings.Settings) { - u.settings = s + u.Settings = s } // SetPeerbook sets the peerbook func (u *User) SetPeerbook(p peer.Peerbook) { - u.peerbook = p + u.Peerbook = p } // NewDefaultUser returns *User @@ -51,15 +51,15 @@ func NewDefaultUser() *User { fmt.Println("user - NewDefaultUser") u := User{} - u.info = info.NewDefaultInfo() - u.settings = settings.NewDefaultSettings() + u.Info = info.NewDefaultInfo() + u.Settings = settings.NewDefaultSettings() return &u } // IsEmpty checks if the user is empty func (u *User) IsEmpty() bool { - if u.info.IsEmpty() && u.settings.IsEmpty() { + if u.Info.IsEmpty() && u.Settings.IsEmpty() { return true } return false From 86c8d371547aea8edc283d6e5d0679be269b3deb Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Sat, 1 Apr 2023 23:41:04 +0200 Subject: [PATCH 32/72] remove unused exported Interface function --- .../skychat/internal/domain/user/user_repository.go | 1 - .../interfaceadapters/storage/memory/user_repo.go | 10 +++++----- .../interfaceadapters/storage/memory/visor_repo.go | 6 +----- 3 files changed, 6 insertions(+), 11 deletions(-) diff --git a/cmd/apps/skychat/internal/domain/user/user_repository.go b/cmd/apps/skychat/internal/domain/user/user_repository.go index 861edbe42..d9447d0cc 100644 --- a/cmd/apps/skychat/internal/domain/user/user_repository.go +++ b/cmd/apps/skychat/internal/domain/user/user_repository.go @@ -3,7 +3,6 @@ package user // Repository is the interface to the user repository type Repository interface { - NewUser() (User, error) GetUser() (*User, error) SetUser(u *User) error } diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go index 3c684b1ea..c3b4c4015 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go @@ -18,7 +18,7 @@ func NewUserRepo(pk cipher.PubKey) *UserRepo { r := UserRepo{} var err error - r.user, err = r.NewUser() + err = r.NewUser() r.user.GetInfo().SetPK(pk) if err != nil { fmt.Println(err) @@ -29,15 +29,15 @@ func NewUserRepo(pk cipher.PubKey) *UserRepo { // NewUser fills repo with a new user, if none has been set // also returns a user when a user has been set already -func (r *UserRepo) NewUser() (user.User, error) { +func (r *UserRepo) NewUser() error { if !r.user.IsEmpty() { - return r.user, fmt.Errorf("user already defined") + return fmt.Errorf("user already defined") } err := r.SetUser(user.NewDefaultUser()) if err != nil { - return user.User{}, err + return err } - return r.user, nil + return nil } // GetUser returns the user diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go index 021ede842..608d2a72a 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go @@ -49,11 +49,7 @@ func (r *VisorRepo) GetAll() ([]chat.Visor, error) { // Add adds the provided visor to the repository func (r *VisorRepo) Add(visor chat.Visor) error { - r.visorsMu.Lock() - defer r.visorsMu.Unlock() - - r.visors[visor.GetPK()] = visor - return nil + return r.Set(visor) } // Set sets the provided visor From 846c075c0bb4b2057b873a97877e5420f75607ab Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Sun, 2 Apr 2023 14:22:57 +0200 Subject: [PATCH 33/72] add boltdb for user repository --- .../internal/domain/chat/visor_repository.go | 2 + .../domain/client/client_repository.go | 1 + .../internal/domain/user/user_repository.go | 2 + .../internal/interfaceadapters/services.go | 22 +++- .../storage/boltdb/user_repo.go | 103 ++++++++++++++++++ .../storage/memory/client_repo.go | 5 + .../storage/memory/user_repo.go | 5 + .../storage/memory/visor_repo.go | 5 + cmd/apps/skychat/skychat.go | 15 +-- 9 files changed, 145 insertions(+), 15 deletions(-) create mode 100644 cmd/apps/skychat/internal/interfaceadapters/storage/boltdb/user_repo.go diff --git a/cmd/apps/skychat/internal/domain/chat/visor_repository.go b/cmd/apps/skychat/internal/domain/chat/visor_repository.go index 421eda74f..a7953cc69 100644 --- a/cmd/apps/skychat/internal/domain/chat/visor_repository.go +++ b/cmd/apps/skychat/internal/domain/chat/visor_repository.go @@ -12,4 +12,6 @@ type Repository interface { Add(v Visor) error Set(v Visor) error Delete(pk cipher.PubKey) error + + Close() error } diff --git a/cmd/apps/skychat/internal/domain/client/client_repository.go b/cmd/apps/skychat/internal/domain/client/client_repository.go index bb22da306..bd005691d 100644 --- a/cmd/apps/skychat/internal/domain/client/client_repository.go +++ b/cmd/apps/skychat/internal/domain/client/client_repository.go @@ -6,4 +6,5 @@ type Repository interface { New() (Client, error) GetClient() (*Client, error) SetClient(c Client) error + Close() error } diff --git a/cmd/apps/skychat/internal/domain/user/user_repository.go b/cmd/apps/skychat/internal/domain/user/user_repository.go index d9447d0cc..ce151a85d 100644 --- a/cmd/apps/skychat/internal/domain/user/user_repository.go +++ b/cmd/apps/skychat/internal/domain/user/user_repository.go @@ -5,4 +5,6 @@ package user type Repository interface { GetUser() (*User, error) SetUser(u *User) error + + Close() error } diff --git a/cmd/apps/skychat/internal/interfaceadapters/services.go b/cmd/apps/skychat/internal/interfaceadapters/services.go index bc1bf744d..da7d1b883 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/services.go +++ b/cmd/apps/skychat/internal/interfaceadapters/services.go @@ -2,6 +2,8 @@ package interfaceadapters import ( + "fmt" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" @@ -9,6 +11,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon" channel "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/notification/http" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/storage/boltdb" "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/storage/memory" ) @@ -25,8 +28,8 @@ type Services struct { func NewServices() Services { cliRepo := memory.NewClientRepo() cli, _ := cliRepo.GetClient() //nolint - usrRepo := memory.NewUserRepo(cli.GetAppClient().Config().VisorPK) vsrRepo := memory.NewVisorRepo() + usrRepo := boltdb.NewUserRepo(cli.GetAppClient().Config().VisorPK) ns := channel.NewNotificationService() ms := netcon.NewMessengerService(ns, cliRepo, usrRepo, vsrRepo) @@ -38,3 +41,20 @@ func NewServices() Services { NotificationService: ns, } } + +// Close closes every open repository +func (s *Services) Close() error { + err := s.ClientRepository.Close() + if err != nil { + fmt.Println(err) + } + err = s.UserRepository.Close() + if err != nil { + fmt.Println(err) + } + err = s.VisorRepository.Close() + if err != nil { + fmt.Println(err) + } + return err +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/boltdb/user_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/boltdb/user_repo.go new file mode 100644 index 000000000..99b6f0a2c --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/boltdb/user_repo.go @@ -0,0 +1,103 @@ +// Package boltdb contains code of the user repo of interfaceadapters +package boltdb + +import ( + "encoding/json" + "fmt" + + "github.com/boltdb/bolt" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" +) + +const USERBUCKET = "users" + +// UserRepo Implements the Repository Interface to provide an in-memory storage provider +type UserRepo struct { + pk cipher.PubKey + db *bolt.DB +} + +// NewUserRepo Constructor +func NewUserRepo(pk cipher.PubKey) *UserRepo { + r := UserRepo{} + + db, err := bolt.Open("user.db", 0600, nil) + if err != nil { + fmt.Println(err.Error()) + } + r.db = db + //defer db.Close() + + r.pk = pk + + r.NewUser() + if err != nil { + fmt.Println(err) + } + + return &r +} + +// NewUser fills repo with a new user, if none has been set +func (r *UserRepo) NewUser() error { + // Store the user model in the user bucket using the pk as the key. + err := r.db.Update(func(tx *bolt.Tx) error { + b, err := tx.CreateBucketIfNotExists([]byte(USERBUCKET)) + if err != nil { + return err + } + + //check if the key is already available, then we don't have to make a new user + ok := b.Get([]byte(r.pk.Hex())) + if ok != nil { + return nil + } + + //make new default user and set pk + usr := user.NewDefaultUser() + usr.GetInfo().SetPK(r.pk) + + encoded, err := json.Marshal(usr) + if err != nil { + return err + } + return b.Put([]byte(r.pk.Hex()), encoded) + }) + return err +} + +// GetUser returns the user +func (r *UserRepo) GetUser() (*user.User, error) { + var usr user.User + err := r.db.View(func(tx *bolt.Tx) error { + b := tx.Bucket([]byte(USERBUCKET)) + v := b.Get([]byte(r.pk.Hex())) + return json.Unmarshal(v, &usr) + }) + return &usr, err +} + +// SetUser updates the provided user +func (r *UserRepo) SetUser(user *user.User) error { + // Store the user model in the user bucket using the username as the key. + err := r.db.Update(func(tx *bolt.Tx) error { + b, err := tx.CreateBucketIfNotExists([]byte(USERBUCKET)) + if err != nil { + return err + } + + encoded, err := json.Marshal(user) + if err != nil { + return err + } + return b.Put([]byte(user.GetInfo().GetPK().Hex()), encoded) + }) + return err +} + +// Close closes the db +func (r *UserRepo) Close() error { + return r.db.Close() +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go index 435721e03..48d99ca46 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go @@ -57,3 +57,8 @@ func (r *ClientRepo) SetClient(client client.Client) error { r.client = client return nil } + +// Close does nothing in memory package +func (r *ClientRepo) Close() error { + return nil +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go index c3b4c4015..3b6aaf0c7 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go @@ -53,3 +53,8 @@ func (r *UserRepo) SetUser(user *user.User) error { r.user = *user return nil } + +// Close does nothing in memory package +func (r *UserRepo) Close() error { + return nil +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go index 608d2a72a..47839d604 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go @@ -73,3 +73,8 @@ func (r *VisorRepo) Delete(pk cipher.PubKey) error { delete(r.visors, pk) return nil } + +// Close does nothing in memory package +func (r *VisorRepo) Close() error { + return nil +} diff --git a/cmd/apps/skychat/skychat.go b/cmd/apps/skychat/skychat.go index ee104fbc8..4c13f2aae 100644 --- a/cmd/apps/skychat/skychat.go +++ b/cmd/apps/skychat/skychat.go @@ -19,6 +19,7 @@ func main() { flag.Parse() interfaceAdapterServices := interfaceadapters.NewServices() + defer interfaceAdapterServices.Close() appServices := app.NewServices(interfaceAdapterServices.ClientRepository, interfaceAdapterServices.UserRepository, interfaceAdapterServices.VisorRepository, interfaceAdapterServices.NotificationService, interfaceAdapterServices.MessengerService) inputPortsServices := inputports.NewServices(appServices) @@ -37,17 +38,3 @@ func main() { // mingw32-make build-windows // .\skywire-cli.exe config gen -i -r -o .\skywire-config.json // .\skywire-visor.exe -c .\skywire-config.json --loglvl debug - -/* - -Text message -{"Id":0,"Origin":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Time":"2022-07-02T00:06:33.0067605+02:00","Sender":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Msgtype":2,"MsgSubtype":0,"Message":"Hey Friend","Status":1,"Seen":false} - -Accept message -{"Id":0,"Origin":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Time":"2022-07-02T00:06:33.0067605+02:00","Sender":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Msgtype":1,"MsgSubtype":2,"Message":"","Status":1,"Seen":false} - -Request message -{"Id":0,"Origin":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Time":"2022-07-02T00:06:33.0067605+02:00","Sender":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Msgtype":1,"MsgSubtype":1,"Message":"","Status":1,"Seen":false} - -{"Id":0,"Origin":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Time":"2022-07-02T14:01:02.3116213+02:00","Sender":"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22","Msgtype":3,"MsgSubtype":0,"Message":"{\"Pk\":\"03389acab4f1a39ebd6e5547acf733b99415f69983270de500715dfef56cddda22\",\"Alias\":\"Meister\",\"Desc\":\"Unknown\",\"Img\":\""}","Status":1,"Seen":false} -*/ From 40ed125120b0c297500203a0c1770e29df8d1f23 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Sun, 2 Apr 2023 14:55:37 +0200 Subject: [PATCH 34/72] add RejectMessage to P2P --- .../messenger/netcon/messenger_service_p2p.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go index 8f65c53e9..3c014b742 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go @@ -209,6 +209,19 @@ func (ms MessengerService) handleP2PConnMsgType(m message.Message) error { } case message.ConnMsgTypeReject: + //get the visor + v, err := ms.visorRepo.GetByPK(pkroute.Visor) + if err != nil { + return err + } + + //add request message to visor route + v.AddMessage(pkroute, m) + err = ms.visorRepo.Set(*v) + if err != nil { + return err + } + n := notification.NewMsgNotification(pkroute, m) err = ms.ns.Notify(n) if err != nil { From 9c9052d9fffee49806894f1744d6371d6862f3c5 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Thu, 6 Apr 2023 18:34:15 +0200 Subject: [PATCH 35/72] fix make-check errs --- .../app/chat/commands/delete_local_route.go | 1 + .../chat/commands/send_add_room_message.go | 2 +- .../chat/commands/send_delete_room_message.go | 2 +- .../chat/commands/send_mute_peer_message.go | 2 +- .../chat/commands/send_unmute_peer_message.go | 2 +- .../netcon/messenger_service_local_server.go | 48 ++++++++++++------- .../messenger/netcon/messenger_service_p2p.go | 35 +++++++++----- .../netcon/messenger_service_remote_server.go | 27 +++++++---- .../storage/boltdb/user_repo.go | 4 +- .../storage/memory/user_repo.go | 3 +- 10 files changed, 77 insertions(+), 49 deletions(-) diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go b/cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go index ca73292c4..7713f5675 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go +++ b/cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go @@ -1,3 +1,4 @@ +// Package commands contains commands to delete local route package commands import ( diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_add_room_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_add_room_message.go index 2a326623b..2722683cb 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/send_add_room_message.go +++ b/cmd/apps/skychat/internal/app/chat/commands/send_add_room_message.go @@ -1,4 +1,4 @@ -// Package commands contains commands to send text message +// Package commands contains commands to send add room message package commands import ( diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_delete_room_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_delete_room_message.go index f2e07355f..32c3cc171 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/send_delete_room_message.go +++ b/cmd/apps/skychat/internal/app/chat/commands/send_delete_room_message.go @@ -1,4 +1,4 @@ -// Package commands contains commands to send text message +// Package commands contains commands to send delete room message package commands import ( diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_mute_peer_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_mute_peer_message.go index 9a7b0c631..ac3c79a38 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/send_mute_peer_message.go +++ b/cmd/apps/skychat/internal/app/chat/commands/send_mute_peer_message.go @@ -1,4 +1,4 @@ -// Package commands contains commands to send text message +// Package commands contains commands to send mute peer message package commands import ( diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_unmute_peer_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_unmute_peer_message.go index 92403e471..110f990b6 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/send_unmute_peer_message.go +++ b/cmd/apps/skychat/internal/app/chat/commands/send_unmute_peer_message.go @@ -1,4 +1,4 @@ -// Package commands contains commands to send text message +// Package commands contains commands to send unmute peer message package commands import ( diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go index a79ed984a..7f50d9df9 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go @@ -16,7 +16,7 @@ import ( // handleLocalServerMessage handles messages received to a local route (server/room) // these can also be locally sent messages from the user to his own local route -func (ms MessengerService) handleLocalServerMessage(m message.Message) error { +func (ms MessengerService) handleLocalServerMessage(m message.Message) { fmt.Println("handleLocalServerMessage") pkroute := util.NewRoomRoute(m.GetDestinationVisor(), m.GetDestinationServer(), m.GetDestinationRoom()) @@ -24,13 +24,15 @@ func (ms MessengerService) handleLocalServerMessage(m message.Message) error { //Check if visor exists visor, err := ms.visorRepo.GetByPK(m.Dest.Visor) if err != nil { - return err + ms.errs <- err + return } //Check if server exists server, err := visor.GetServerByPK(m.Dest.Server) if err != nil { - return err + ms.errs <- err + return } //check if the message is of type ConnMsgType @@ -38,9 +40,10 @@ func (ms MessengerService) handleLocalServerMessage(m message.Message) error { if m.GetMessageType() == message.ConnMsgType { err := ms.handleLocalServerConnMsgType(visor, m) if err != nil { - return err + ms.errs <- err + return } - return nil + return } //the root route of this server @@ -54,24 +57,28 @@ func (ms MessengerService) handleLocalServerMessage(m message.Message) error { if !isServerMember || isInServerBlacklist { err = ms.SendChatRejectMessage(root, dest) if err != nil { - return fmt.Errorf("error sending reject message: %s", err) + ms.errs <- fmt.Errorf("error sending reject message: %s", err) + return } - return fmt.Errorf("message rejected from " + m.Root.Visor.String() + "isServerMember: " + strconv.FormatBool(isServerMember) + "isInServerBlacklist: " + strconv.FormatBool(isInServerBlacklist)) + ms.errs <- fmt.Errorf("message rejected from " + m.Root.Visor.String() + "isServerMember: " + strconv.FormatBool(isServerMember) + "isInServerBlacklist: " + strconv.FormatBool(isInServerBlacklist)) + return } //handle Command Messages if m.GetMessageType() == message.CmdMsgType { err := ms.handleLocalServerCmdMsgType(visor, m) if err != nil { - return err + ms.errs <- err + return } - return nil + return } //Check if room exists room, err := server.GetRoomByPK(pkroute.Room) if err != nil { - return err + ms.errs <- err + return } //check if origin of message is in blacklist or not member of room @@ -80,10 +87,11 @@ func (ms MessengerService) handleLocalServerMessage(m message.Message) error { if !isRoomMember || isInRoomBlacklist { err = ms.SendChatRejectMessage(root, dest) if err != nil { - return fmt.Errorf("error sending reject message: %s", err) + ms.errs <- fmt.Errorf("error sending reject message: %s", err) + return } - return fmt.Errorf("message rejected from " + m.Root.Visor.String() + "isRoomMember: " + strconv.FormatBool(isRoomMember) + "isInRoomBlacklist: " + strconv.FormatBool(isInRoomBlacklist)) - + ms.errs <- fmt.Errorf("message rejected from " + m.Root.Visor.String() + "isRoomMember: " + strconv.FormatBool(isRoomMember) + "isInRoomBlacklist: " + strconv.FormatBool(isInRoomBlacklist)) + return } //now we can handle all other message-types @@ -93,7 +101,8 @@ func (ms MessengerService) handleLocalServerMessage(m message.Message) error { visor.AddMessage(pkroute, m) err = ms.visorRepo.Set(*visor) if err != nil { - return err + ms.errs <- err + return } //handle the message err = ms.handleLocalServerInfoMsgType(visor, m) @@ -105,18 +114,20 @@ func (ms MessengerService) handleLocalServerMessage(m message.Message) error { visor.AddMessage(pkroute, m) err = ms.visorRepo.Set(*visor) if err != nil { - return err + ms.errs <- err + return } //handle the message err := ms.handleLocalRoomTextMsgType(visor, m) if err != nil { - return err + ms.errs <- err + return } default: - return fmt.Errorf("incorrect data received") + ms.errs <- fmt.Errorf("incorrect data received") + return } - return nil } // handleLocalServerConnMsgType handles an incoming connection message and either accepts it and sends back the own info as message @@ -379,6 +390,7 @@ func (ms MessengerService) handleLocalServerCmdMsgType(visor *chat.Visor, m mess return fmt.Errorf("command not accepted, no admin") } + //TODO: really delete room from server and update visor in reposiory //prepare NewRooomDeletedMessage and send it to all members msg := message.NewRouteDeletedMessage(pkroute, pkroute) diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go index 3c014b742..f3eed2ae8 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go @@ -12,7 +12,7 @@ import ( ) // handleP2PMessage handles messages received as direct message -func (ms MessengerService) handleP2PMessage(m message.Message) error { +func (ms MessengerService) handleP2PMessage(m message.Message) { fmt.Println("handleP2PMessage") pkroute := util.NewP2PRoute(m.Root.Visor) @@ -22,15 +22,17 @@ func (ms MessengerService) handleP2PMessage(m message.Message) error { if m.GetMessageType() == message.ConnMsgType { err := ms.handleP2PConnMsgType(m) if err != nil { - return err + ms.errs <- err + return } - return nil + return } //if the message is not of type ConnMsgType check if the remote pk is blacklisted // to prevent a peer from sending other messages before a connection-request message usr, err := ms.usrRepo.GetUser() if err != nil { - return err + ms.errs <- err + return } //the p2p route of the user @@ -41,15 +43,18 @@ func (ms MessengerService) handleP2PMessage(m message.Message) error { if usr.GetSettings().InBlacklist(pkroute.Visor) { err = ms.SendChatRejectMessage(root, dest) if err != nil { - return err + ms.errs <- err + return } - return fmt.Errorf("Message rejected from " + m.Root.Visor.String()) + ms.errs <- fmt.Errorf("Message rejected from " + m.Root.Visor.String()) + return } //get the current p2p-room so when updating nothing gets overwritten visor, err := ms.visorRepo.GetByPK(m.Root.Visor) if err != nil { - return err + ms.errs <- err + return } //now we can handle all other message-types @@ -59,7 +64,8 @@ func (ms MessengerService) handleP2PMessage(m message.Message) error { visor.AddMessage(pkroute, m) err = ms.visorRepo.Set(*visor) if err != nil { - return err + ms.errs <- err + return } //handle the message err = ms.handleP2PInfoMsgType(visor, m) @@ -71,19 +77,22 @@ func (ms MessengerService) handleP2PMessage(m message.Message) error { visor.AddMessage(pkroute, m) err = ms.visorRepo.Set(*visor) if err != nil { - return err + ms.errs <- err + return } //handle the message err := ms.handleP2PTextMsgType(m) if err != nil { - return err + ms.errs <- err + return } case message.CmdMsgType: - return fmt.Errorf("commands are not allowed on p2p chats") + ms.errs <- fmt.Errorf("commands are not allowed on p2p chats") + return default: - return fmt.Errorf("incorrect data received") + ms.errs <- fmt.Errorf("incorrect data received") + return } - return nil } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go index f4f1946b7..3320407dc 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go @@ -14,7 +14,7 @@ import ( ) // handleRemoteServerMessage handles all messages from a remote server/room -func (ms MessengerService) handleRemoteServerMessage(m message.Message) error { +func (ms MessengerService) handleRemoteServerMessage(m message.Message) { fmt.Println("handleRemoteServerMessage") pkroute := util.NewRoomRoute(m.GetRootVisor(), m.GetRootServer(), m.GetRootRoom()) @@ -22,11 +22,13 @@ func (ms MessengerService) handleRemoteServerMessage(m message.Message) error { //check if we are member of remote server -> if not ignore message visor, err := ms.visorRepo.GetByPK(pkroute.Visor) if err != nil { - return fmt.Errorf("message dumped: no member of remote, visor not even known") + ms.errs <- fmt.Errorf("message dumped: no member of remote, visor not even known") + return } _, err = visor.GetServerByPK(pkroute.Server) if err != nil { - return fmt.Errorf("message dumped: no member of remote server") + ms.errs <- fmt.Errorf("message dumped: no member of remote server") + return } switch m.GetMessageType() { @@ -35,7 +37,8 @@ func (ms MessengerService) handleRemoteServerMessage(m message.Message) error { visor.AddMessage(pkroute, m) err = ms.visorRepo.Set(*visor) if err != nil { - return err + ms.errs <- err + return } //handle the message err = ms.handleRemoteRoomConnMsgType(m) @@ -47,7 +50,8 @@ func (ms MessengerService) handleRemoteServerMessage(m message.Message) error { visor.AddMessage(pkroute, m) err = ms.visorRepo.Set(*visor) if err != nil { - return err + ms.errs <- err + return } //handle the message err = ms.handleRemoteRoomInfoMsgType(visor, m) @@ -59,20 +63,23 @@ func (ms MessengerService) handleRemoteServerMessage(m message.Message) error { visor.AddMessage(pkroute, m) err = ms.visorRepo.Set(*visor) if err != nil { - return err + ms.errs <- err + return } //handle the message err := ms.handleRemoteRoomTextMsgType(visor, m) if err != nil { - return err + ms.errs <- err + return } case message.CmdMsgType: - return fmt.Errorf("commands are not allowed on p2p chats") + ms.errs <- fmt.Errorf("commands are not allowed on p2p chats") + return default: - return fmt.Errorf("incorrect data received") + ms.errs <- fmt.Errorf("incorrect data received") + return } - return nil } // handleRemoteRoomConnMsgType handles all messages of type ConnMsgtype of remote servers diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/boltdb/user_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/boltdb/user_repo.go index 99b6f0a2c..2ef3182e1 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/boltdb/user_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/boltdb/user_repo.go @@ -11,6 +11,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) +// USERBUCKET defines the key for the users bucket const USERBUCKET = "users" // UserRepo Implements the Repository Interface to provide an in-memory storage provider @@ -28,11 +29,10 @@ func NewUserRepo(pk cipher.PubKey) *UserRepo { fmt.Println(err.Error()) } r.db = db - //defer db.Close() r.pk = pk - r.NewUser() + err = r.NewUser() if err != nil { fmt.Println(err) } diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go index 3b6aaf0c7..929733893 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go @@ -17,8 +17,7 @@ type UserRepo struct { func NewUserRepo(pk cipher.PubKey) *UserRepo { r := UserRepo{} - var err error - err = r.NewUser() + err := r.NewUser() r.user.GetInfo().SetPK(pk) if err != nil { fmt.Println(err) From 1128393b1f67c34b2c18f2fe29d56868058c90a6 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Mon, 17 Apr 2023 21:36:34 +0200 Subject: [PATCH 36/72] turn function call into go routine --- .../interfaceadapters/messenger/netcon/messenger_service.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index ea3bcbec7..bf8486dc6 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -544,10 +544,7 @@ func (ms MessengerService) sendMessageToRemoteRoute(msg message.Message) error { // sendMessageToLocalRoute "sends" the message to local server, so local server handles it, as it was sent from a remote route (used for messages send from server host, but as client) func (ms MessengerService) sendMessageToLocalRoute(msg message.Message) error { - err := ms.handleLocalServerMessage(msg) - if err != nil { - return err - } + go ms.handleLocalServerMessage(msg) //notification is handled inside handleServerMessage return nil From 373b37bcbc3b86475f1c7f1ab8e75f4f6ef94725 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <50741854+4rchim3d3s@users.noreply.github.com> Date: Thu, 20 Apr 2023 21:16:49 +0200 Subject: [PATCH 37/72] fix darwin make format errs --- cmd/apps/skychat/skychat.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/cmd/apps/skychat/skychat.go b/cmd/apps/skychat/skychat.go index 4c13f2aae..d523ce74e 100644 --- a/cmd/apps/skychat/skychat.go +++ b/cmd/apps/skychat/skychat.go @@ -5,6 +5,7 @@ skychat app for skywire visor package main import ( + "fmt" "flag" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app" @@ -19,7 +20,12 @@ func main() { flag.Parse() interfaceAdapterServices := interfaceadapters.NewServices() - defer interfaceAdapterServices.Close() + defer func() { + err := interfaceAdapterServices.Close() + if err != nil { + fmt.Println(err.Error()) + } + }() appServices := app.NewServices(interfaceAdapterServices.ClientRepository, interfaceAdapterServices.UserRepository, interfaceAdapterServices.VisorRepository, interfaceAdapterServices.NotificationService, interfaceAdapterServices.MessengerService) inputPortsServices := inputports.NewServices(appServices) From 53e00c82b663d9b6b74966a81143ef894f383b71 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Thu, 20 Apr 2023 21:48:38 +0200 Subject: [PATCH 38/72] add usecases to hire and fire moderator --- .../app/chat/commands/send_fire_moderator.go | 38 +++++ .../app/chat/commands/send_hire_moderator.go | 38 +++++ .../skychat/internal/app/chat/services.go | 40 ++--- .../internal/app/messenger/messenger.go | 3 + .../internal/domain/message/message.go | 51 +++++- .../internal/inputports/http/chat/handler.go | 146 ++++++++++++++++++ .../internal/inputports/http/server.go | 2 + .../messenger/netcon/messenger_service.go | 64 ++++++++ .../netcon/messenger_service_local_server.go | 133 ++++++++++++++++ 9 files changed, 494 insertions(+), 21 deletions(-) create mode 100644 cmd/apps/skychat/internal/app/chat/commands/send_fire_moderator.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/send_hire_moderator.go diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_fire_moderator.go b/cmd/apps/skychat/internal/app/chat/commands/send_fire_moderator.go new file mode 100644 index 000000000..a564a8194 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/send_fire_moderator.go @@ -0,0 +1,38 @@ +// Package commands contains commands to send fire moderator message +package commands + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// SendFireModeratorMessageRequest of SendFireModeratorMessageRequestHandler +type SendFireModeratorMessageRequest struct { + Route util.PKRoute + Pk cipher.PubKey +} + +// SendFireModeratorMessageRequestHandler struct that allows handling SendFireModeratorMessageRequest +type SendFireModeratorMessageRequestHandler interface { + Handle(command SendFireModeratorMessageRequest) error +} + +type sendFireModeratorMessageRequestHandler struct { + messengerService messenger.Service +} + +// NewSendFireModeratorMessageRequestHandler Initializes an AddCommandHandler +func NewSendFireModeratorMessageRequestHandler(messengerService messenger.Service) SendFireModeratorMessageRequestHandler { + return sendFireModeratorMessageRequestHandler{messengerService: messengerService} +} + +// Handle handles the SendFireModeratorMessageRequest +func (h sendFireModeratorMessageRequestHandler) Handle(command SendFireModeratorMessageRequest) error { + err := h.messengerService.SendFireModeratorMessage(command.Route, command.Pk) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_hire_moderator.go b/cmd/apps/skychat/internal/app/chat/commands/send_hire_moderator.go new file mode 100644 index 000000000..43f6bc329 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/send_hire_moderator.go @@ -0,0 +1,38 @@ +// Package commands contains commands to send hire moderator message +package commands + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// SendHireModeratorMessageRequest of SendHireModeratorMessageRequestHandler +type SendHireModeratorMessageRequest struct { + Route util.PKRoute + Pk cipher.PubKey +} + +// SendHireModeratorMessageRequestHandler struct that allows handling SendHireModeratorMessageRequest +type SendHireModeratorMessageRequestHandler interface { + Handle(command SendHireModeratorMessageRequest) error +} + +type sendHireModeratorMessageRequestHandler struct { + messengerService messenger.Service +} + +// NewSendHireModeratorMessageRequestHandler Initializes an AddCommandHandler +func NewSendHireModeratorMessageRequestHandler(messengerService messenger.Service) SendHireModeratorMessageRequestHandler { + return sendHireModeratorMessageRequestHandler{messengerService: messengerService} +} + +// Handle handles the SendHireModeratorMessageRequest +func (h sendHireModeratorMessageRequestHandler) Handle(command SendHireModeratorMessageRequest) error { + err := h.messengerService.SendHireModeratorMessage(command.Route, command.Pk) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/apps/skychat/internal/app/chat/services.go b/cmd/apps/skychat/internal/app/chat/services.go index 262b284ec..81b0e0919 100644 --- a/cmd/apps/skychat/internal/app/chat/services.go +++ b/cmd/apps/skychat/internal/app/chat/services.go @@ -22,15 +22,17 @@ type Queries struct { // Commands Contains all available command handlers of this app type Commands struct { - AddLocalServerHandler commands.AddLocalServerRequestHandler - JoinRemoteRouteHandler commands.JoinRemoteRouteRequestHandler - DeleteLocalRouteHandler commands.DeleteLocalRouteRequestHandler - LeaveRemoteRouteHandler commands.LeaveRemoteRouteRequestHandler - SendAddRoomMessageHandler commands.SendAddRoomMessageRequestHandler - SendDeleteRoomMessageHandler commands.SendDeleteRoomMessageRequestHandler - SendTextMessageHandler commands.SendTextMessageRequestHandler - SendMutePeerMessageHandler commands.SendMutePeerMessageRequestHandler - SendUnmutePeerMessageHandler commands.SendUnmutePeerMessageRequestHandler + AddLocalServerHandler commands.AddLocalServerRequestHandler + JoinRemoteRouteHandler commands.JoinRemoteRouteRequestHandler + DeleteLocalRouteHandler commands.DeleteLocalRouteRequestHandler + LeaveRemoteRouteHandler commands.LeaveRemoteRouteRequestHandler + SendAddRoomMessageHandler commands.SendAddRoomMessageRequestHandler + SendDeleteRoomMessageHandler commands.SendDeleteRoomMessageRequestHandler + SendTextMessageHandler commands.SendTextMessageRequestHandler + SendMutePeerMessageHandler commands.SendMutePeerMessageRequestHandler + SendUnmutePeerMessageHandler commands.SendUnmutePeerMessageRequestHandler + SendHireModeratorMessageHandler commands.SendHireModeratorMessageRequestHandler + SendFireModeratorMessageHandler commands.SendFireModeratorMessageRequestHandler } // ChatServices Contains the grouped queries and commands of the app layer @@ -50,15 +52,17 @@ func NewServices(cliRepo client.Repository, visorRepo chat.Repository, userRepo GetAllMessagesFromRoomHandler: queries.NewGetAllMessagesFromRoomRequestHandler(visorRepo), }, Commands: Commands{ - AddLocalServerHandler: commands.NewAddLocalServerRequestHandler(visorRepo, userRepo, ns), - JoinRemoteRouteHandler: commands.NewJoinRemoteRouteRequestHandler(visorRepo, ms), - DeleteLocalRouteHandler: commands.NewDeleteLocalRouteRequestHandler(ms, visorRepo), - LeaveRemoteRouteHandler: commands.NewLeaveRemoteRouteRequestHandler(ms, visorRepo, userRepo), - SendAddRoomMessageHandler: commands.NewSendAddRoomMessageRequestHandler(ms), - SendDeleteRoomMessageHandler: commands.NewSendDeleteRoomMessageRequestHandler(ms), - SendTextMessageHandler: commands.NewSendTextMessageRequestHandler(ms), - SendMutePeerMessageHandler: commands.NewSendMutePeerMessageRequestHandler(ms), - SendUnmutePeerMessageHandler: commands.NewSendUnmutePeerMessageRequestHandler(ms), + AddLocalServerHandler: commands.NewAddLocalServerRequestHandler(visorRepo, userRepo, ns), + JoinRemoteRouteHandler: commands.NewJoinRemoteRouteRequestHandler(visorRepo, ms), + DeleteLocalRouteHandler: commands.NewDeleteLocalRouteRequestHandler(ms, visorRepo), + LeaveRemoteRouteHandler: commands.NewLeaveRemoteRouteRequestHandler(ms, visorRepo, userRepo), + SendAddRoomMessageHandler: commands.NewSendAddRoomMessageRequestHandler(ms), + SendDeleteRoomMessageHandler: commands.NewSendDeleteRoomMessageRequestHandler(ms), + SendTextMessageHandler: commands.NewSendTextMessageRequestHandler(ms), + SendMutePeerMessageHandler: commands.NewSendMutePeerMessageRequestHandler(ms), + SendUnmutePeerMessageHandler: commands.NewSendUnmutePeerMessageRequestHandler(ms), + SendHireModeratorMessageHandler: commands.NewSendHireModeratorMessageRequestHandler(ms), + SendFireModeratorMessageHandler: commands.NewSendFireModeratorMessageRequestHandler(ms), }, } } diff --git a/cmd/apps/skychat/internal/app/messenger/messenger.go b/cmd/apps/skychat/internal/app/messenger/messenger.go index c8fed9d35..4e764e44f 100644 --- a/cmd/apps/skychat/internal/app/messenger/messenger.go +++ b/cmd/apps/skychat/internal/app/messenger/messenger.go @@ -28,4 +28,7 @@ type Service interface { //used as client SendMutePeerMessage(pkroute util.PKRoute, pk cipher.PubKey) error SendUnmutePeerMessage(pkroute util.PKRoute, pk cipher.PubKey) error + + SendHireModeratorMessage(pkroute util.PKRoute, pk cipher.PubKey) error + SendFireModeratorMessage(pkroute util.PKRoute, pk cipher.PubKey) error } diff --git a/cmd/apps/skychat/internal/domain/message/message.go b/cmd/apps/skychat/internal/domain/message/message.go index 3f65ac28e..427b74437 100644 --- a/cmd/apps/skychat/internal/domain/message/message.go +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -77,12 +77,15 @@ const ( CmdMsgTypeMutePeer // CmdMsgTypeUnmutePeer is used tu unmute a peer CmdMsgTypeUnmutePeer + // CmdMsgTypeHireModerator is used to hire a peer as moderator + CmdMsgTypeHireModerator + // CmdMsgTypeFireModerator is used to fire a moderator + CmdMsgTypeFireModerator /*CmdMsgTypeBanPeer CmdMsgTypeUnbanPeer CmdMsgTypeHireAdmin CmdMsgTypeFireAdmin - CmdMsgTypeHireModerator - CmdMsgTypeFireModerator*/ + */ ) // Message defines a message @@ -321,7 +324,7 @@ func NewDeleteRoomMessage(root util.PKRoute, dest util.PKRoute) Message { return m } -// NewRoomMembersMessage returns a Message of roomMembers +// NewRoomMembersMessage returns a Message of room members func NewRoomMembersMessage(root util.PKRoute, dest util.PKRoute, members []byte) Message { m := Message{} m.Origin = root.Visor @@ -335,6 +338,20 @@ func NewRoomMembersMessage(root util.PKRoute, dest util.PKRoute, members []byte) return m } +// NewRoomModsMessage returns a Message of room moderators +func NewRoomModsMessage(root util.PKRoute, dest util.PKRoute, moderators []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = InfoMsgType + m.MsgSubtype = InfoMsgTypeRoomMembers + m.Message = moderators + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + // NewRoomMutedMessage returns a Message of muted pks of room func NewRoomMutedMessage(root util.PKRoute, dest util.PKRoute, muted []byte) Message { m := Message{} @@ -377,6 +394,34 @@ func NewUnmutePeerMessage(root util.PKRoute, dest util.PKRoute, pk []byte) Messa return m } +// NewHireModeratorMessage returns a Message to hire a peer as moderator +func NewHireModeratorMessage(root util.PKRoute, dest util.PKRoute, pk []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = CmdMsgType + m.MsgSubtype = CmdMsgTypeHireModerator + m.Message = pk + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + +// NewFireModeratorMessage returns a Message to fire a moderator +func NewFireModeratorMessage(root util.PKRoute, dest util.PKRoute, pk []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = CmdMsgType + m.MsgSubtype = CmdMsgTypeFireModerator + m.Message = pk + m.Status = MsgStatusInitial + m.Time = time.Now() + return m +} + // GetID returns message ID func (m *Message) GetID() int { return m.ID diff --git a/cmd/apps/skychat/internal/inputports/http/chat/handler.go b/cmd/apps/skychat/internal/inputports/http/chat/handler.go index 6c617a0cd..8c340f3d2 100644 --- a/cmd/apps/skychat/internal/inputports/http/chat/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/chat/handler.go @@ -421,6 +421,152 @@ func (c Handler) SendUnmutePeerMessage(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } +// SendHireModMessageURLParam contains the parameter identifier to be parsed by the handler +const SendHireModMessageURLParam = "sendHireModMessage" + +// SendHireModMessageRequestModel represents the request model expected for hire moderator request +type SendHireModMessageRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` + + PeerPk string `json:"peerpk"` +} + +// SendHireModMessage sends a hire moderator message to the given route +func (c Handler) SendHireModMessage(w http.ResponseWriter, r *http.Request) { + var requestModel SendHireModMessageRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr.Error()) + return + } + + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + err := visorpk.Set(requestModel.VisorPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Visor = visorpk + if requestModel.ServerPk != "" { + serverpk := cipher.PubKey{} + err = serverpk.Set(requestModel.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + if requestModel.RoomPk != "" { + roompk := cipher.PubKey{} + err = roompk.Set(requestModel.RoomPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Room = roompk + } + } + + peerpk := cipher.PubKey{} + err = peerpk.Set(requestModel.PeerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + + err = c.chatServices.Commands.SendHireModeratorMessageHandler.Handle(commands.SendHireModeratorMessageRequest{ + Route: route, + Pk: peerpk, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + w.WriteHeader(http.StatusOK) +} + +// SendFireModMessageURLParam contains the parameter identifier to be parsed by the handler +const SendFireModMessageURLParam = "sendFireModMessage" + +// SendFireModMessageRequestModel represents the request model expected for fire moderator request +type SendFireModMessageRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` + + PeerPk string `json:"peerpk"` +} + +// SendFireModMessage sends a fire moderator message to the given route +func (c Handler) SendFireModMessage(w http.ResponseWriter, r *http.Request) { + var requestModel SendFireModMessageRequestModel + decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) + if decodeErr != nil { + w.WriteHeader(http.StatusBadRequest) + fmt.Fprint(w, decodeErr.Error()) + return + } + + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + err := visorpk.Set(requestModel.VisorPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Visor = visorpk + if requestModel.ServerPk != "" { + serverpk := cipher.PubKey{} + err = serverpk.Set(requestModel.ServerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Server = serverpk + if requestModel.RoomPk != "" { + roompk := cipher.PubKey{} + err = roompk.Set(requestModel.RoomPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + route.Room = roompk + } + } + + peerpk := cipher.PubKey{} + err = peerpk.Set(requestModel.PeerPk) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + + err = c.chatServices.Commands.SendFireModeratorMessageHandler.Handle(commands.SendFireModeratorMessageRequest{ + Route: route, + Pk: peerpk, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + w.WriteHeader(http.StatusOK) +} + // DeleteLocalRouteURLParam contains the parameter identifier to be parsed by the handler const DeleteLocalRouteURLParam = "DeleteLocalRoute" diff --git a/cmd/apps/skychat/internal/inputports/http/server.go b/cmd/apps/skychat/internal/inputports/http/server.go index 65999145b..c8fca9145 100644 --- a/cmd/apps/skychat/internal/inputports/http/server.go +++ b/cmd/apps/skychat/internal/inputports/http/server.go @@ -70,6 +70,8 @@ func (httpServer *Server) AddChatHTTPRoutes() { httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendTextMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendTextMessage).Methods("POST") httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendMutePeerMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendMutePeerMessage).Methods("POST") httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendUnmutePeerMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendUnmutePeerMessage).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendHireModMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendHireModMessage).Methods("POST") + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendFireModMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendFireModMessage).Methods("POST") } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index bf8486dc6..0b69e79e1 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -522,6 +522,70 @@ func (ms MessengerService) SendUnmutePeerMessage(pkroute util.PKRoute, pk cipher return nil } +// SendHireModeratorMessage sends a command message to hire a peer as moderator +func (ms MessengerService) SendHireModeratorMessage(pkroute util.PKRoute, pk cipher.PubKey) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + bytes, err := json.Marshal(pk) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) + + msg := message.NewHireModeratorMessage(root, pkroute, bytes) + + if msg.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(msg) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(msg) + if err != nil { + return err + } + } + return nil +} + +// SendFireModeratorMessage sends a command message to fire a moderator +func (ms MessengerService) SendFireModeratorMessage(pkroute util.PKRoute, pk cipher.PubKey) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + bytes, err := json.Marshal(pk) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) + + msg := message.NewFireModeratorMessage(root, pkroute, bytes) + + if msg.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(msg) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(msg) + if err != nil { + return err + } + } + return nil +} + // sendMessageToRemoteRoute sends the given message to a remote route (as p2p and client) func (ms MessengerService) sendMessageToRemoteRoute(msg message.Message) error { //if the message goes to p2p we save it in database, if not we wait for the remote server to send us our message diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go index 7f50d9df9..812cb9d00 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go @@ -422,6 +422,27 @@ func (ms MessengerService) handleLocalServerCmdMsgType(visor *chat.Visor, m mess return err } + // update server, update visor and then update repository + err = server.SetRoom(*room) + if err != nil { + return err + } + err = visor.SetServer(*server) + if err != nil { + return err + } + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + + //notify about the added route + n := notification.NewAddRouteNotification(pkroute) + err = ms.ns.Notify(n) + if err != nil { + return err + } + //send updated list of Muted to peers muted := room.GetAllMuted() bytes, err := json.Marshal(muted) @@ -459,6 +480,20 @@ func (ms MessengerService) handleLocalServerCmdMsgType(visor *chat.Visor, m mess return err } + // update server, update visor and then update repository + err = server.SetRoom(*room) + if err != nil { + return err + } + err = visor.SetServer(*server) + if err != nil { + return err + } + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + //send updated list of Muted to peers muted := room.GetAllMuted() bytes, err := json.Marshal(muted) @@ -474,6 +509,104 @@ func (ms MessengerService) handleLocalServerCmdMsgType(visor *chat.Visor, m mess } } return nil + case message.CmdMsgTypeHireModerator: + //check if room exists + room, err := server.GetRoomByPK(pkroute.Room) + if err != nil { + return err + } + //First check if origin of msg is admin + _, isAdmin := server.GetAllAdmin()[m.Root.Visor] + + if isAdmin { + //unmarshal the received message bytes to cipher.PubKey + pk := cipher.PubKey{} + err = json.Unmarshal(m.Message, &pk) + if err != nil { + return fmt.Errorf("failed to unmarshal json message: %v", err) + } + err = room.AddMod(pk) + if err != nil { + return err + } + // update server, update visor and then update repository + err = server.SetRoom(*room) + if err != nil { + return err + } + err = visor.SetServer(*server) + if err != nil { + return err + } + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + + //send updated list of Mods to peers + muted := room.GetAllMods() + bytes, err := json.Marshal(muted) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + msg := message.NewRoomModsMessage(pkroute, pkroute, bytes) + + err = ms.sendMessageToPeers(visor, pkroute, msg) + if err != nil { + return err + } + } + return nil + case message.CmdMsgTypeFireModerator: + //check if room exists + room, err := server.GetRoomByPK(pkroute.Room) + if err != nil { + return err + } + //First check if origin of msg is admin + _, isAdmin := server.GetAllAdmin()[m.Root.Visor] + + if isAdmin { + //unmarshal the received message bytes to cipher.PubKey + pk := cipher.PubKey{} + err = json.Unmarshal(m.Message, &pk) + if err != nil { + return fmt.Errorf("failed to unmarshal json message: %v", err) + } + err = room.DeleteMod(pk) + if err != nil { + return err + } + // update server, update visor and then update repository + err = server.SetRoom(*room) + if err != nil { + return err + } + err = visor.SetServer(*server) + if err != nil { + return err + } + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + + //send updated list of Mods to peers + muted := room.GetAllMods() + bytes, err := json.Marshal(muted) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + msg := message.NewRoomModsMessage(pkroute, pkroute, bytes) + + err = ms.sendMessageToPeers(visor, pkroute, msg) + if err != nil { + return err + } + } + return nil //FUTUREFEATURES: add other cmd messages default: return fmt.Errorf("incorrect data received") From 281535a91884572c441f452e5452f494a6a933f0 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Thu, 20 Apr 2023 23:01:40 +0200 Subject: [PATCH 39/72] add cli functionality With this commit cli functionality can be integrated into the app, but the config entries inside skywire-config.json have to be changed to be: { "name": "skychat", "binary": "skychat", "args": ["--addr=:8001"], "auto_start": true, "port": 1 }, This was changed in the default app config generation. --- .../internal/inputports/cli/chat/root.go | 18 ++++ .../inputports/cli/chat/send/handler.go | 46 +++++++++ .../internal/inputports/cli/chat/send/root.go | 13 +++ .../inputports/cli/chat/send/textmessage.go | 36 +++++++ .../skychat/internal/inputports/cli/root.go | 93 +++++++++++++++++++ cmd/apps/skychat/skychat.go | 31 +------ pkg/visor/visorconfig/config.go | 2 +- 7 files changed, 210 insertions(+), 29 deletions(-) create mode 100644 cmd/apps/skychat/internal/inputports/cli/chat/root.go create mode 100644 cmd/apps/skychat/internal/inputports/cli/chat/send/handler.go create mode 100644 cmd/apps/skychat/internal/inputports/cli/chat/send/root.go create mode 100644 cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go create mode 100644 cmd/apps/skychat/internal/inputports/cli/root.go diff --git a/cmd/apps/skychat/internal/inputports/cli/chat/root.go b/cmd/apps/skychat/internal/inputports/cli/chat/root.go new file mode 100644 index 000000000..4d752becd --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/cli/chat/root.go @@ -0,0 +1,18 @@ +// Package clichat contains code for chat command of cli inputports +package clichat + +import ( + "github.com/spf13/cobra" + + clichatsend "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/cli/chat/send" +) + +// RootCmd is the sub-command so interact with the chats +var RootCmd = &cobra.Command{ + Use: "chat", + Short: "Send messages or query a chat", +} + +func init() { + RootCmd.AddCommand(clichatsend.SendCmd) +} diff --git a/cmd/apps/skychat/internal/inputports/cli/chat/send/handler.go b/cmd/apps/skychat/internal/inputports/cli/chat/send/handler.go new file mode 100644 index 000000000..6a08fbbe4 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/cli/chat/send/handler.go @@ -0,0 +1,46 @@ +// Package clichatsend contains code of the cobra-cli handler for inputports +package clichatsend + +import ( + "encoding/json" + "fmt" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + chatservices "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/chat/commands" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// Handler clichat request handler +type Handler struct { + chatServices chatservices.ChatServices +} + +// NewHandler Constructor returns *Handler +func NewHandler(cs chatservices.ChatServices) *Handler { + return &Handler{chatServices: cs} +} + +// SendTextMessageRequestModel represents the request model expected for send text request +type SendTextMessageRequestModel struct { + VisorPk cipher.PubKey + ServerPk cipher.PubKey + RoomPk cipher.PubKey + Msg string +} + +// SendTextMessage sends a text message to the given route +func (c Handler) SendTextMessage(r SendTextMessageRequestModel) error { + + bytes, err := json.Marshal(r.Msg) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + err = c.chatServices.Commands.SendTextMessageHandler.Handle(commands.SendTextMessageRequest{ + Route: util.NewRoomRoute(r.VisorPk, r.ServerPk, r.RoomPk), + Msg: bytes, + }) + return err +} diff --git a/cmd/apps/skychat/internal/inputports/cli/chat/send/root.go b/cmd/apps/skychat/internal/inputports/cli/chat/send/root.go new file mode 100644 index 000000000..22a2a9ee7 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/cli/chat/send/root.go @@ -0,0 +1,13 @@ +package clichatsend + +import "github.com/spf13/cobra" + +// SendCmd is the sub-command to send messages +var SendCmd = &cobra.Command{ + Use: "send", + Short: "Send messages", +} + +func init() { + SendCmd.AddCommand(textMessageCmd) +} diff --git a/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go b/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go new file mode 100644 index 000000000..d5cc23648 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go @@ -0,0 +1,36 @@ +package clichatsend + +import ( + "fmt" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/skycoin/skywire-utilities/pkg/cipher" +) + +var textMessageCmd = &cobra.Command{ + Use: "text ", + Short: "Send text message", + Args: cobra.MinimumNArgs(4), + Run: func(cmd *cobra.Command, args []string) { + vpk := ParsePK(cmd.Flags(), "vpk", args[0]) + spk := ParsePK(cmd.Flags(), "spk", args[1]) + rpk := ParsePK(cmd.Flags(), "rpk", args[2]) + msg := args[3] + fmt.Println("SendTextMessage (cli)") + fmt.Println(msg) + fmt.Printf("to v: %s s: %s, r %s\n", vpk.Hex(), spk.Hex(), rpk.Hex()) + }, +} + +// ParsePK parses a public key +func ParsePK(cmdFlags *pflag.FlagSet, name, v string) cipher.PubKey { + var pk cipher.PubKey + err := pk.Set(v) + if err != nil { + //PrintFatalError(cmdFlags, fmt.Errorf("failed to parse <%s>: %v", name, err)) + fmt.Printf("Error") + } + return pk +} diff --git a/cmd/apps/skychat/internal/inputports/cli/root.go b/cmd/apps/skychat/internal/inputports/cli/root.go new file mode 100644 index 000000000..6d7a5d264 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/cli/root.go @@ -0,0 +1,93 @@ +// Package cli contains code for the cli service of inputports +package cli + +import ( + "fmt" + "log" + + cc "github.com/ivanpirog/coloredcobra" + "github.com/spf13/cobra" + + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports" + clichat "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/cli/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters" +) + +var port string + +var rootCmd = &cobra.Command{ + Use: "skychat.go", + Short: "Command Line Interface for skychat", + Long: ` + ┌─┐┬┌─┬ ┬ ┌─┐┬ ┬ + └─┐├┴┐└┬┘ CHAT ──│ │ │ + └─┘┴ ┴ ┴ └─┘┴─┘┴`, + SilenceErrors: true, + SilenceUsage: true, + DisableSuggestions: true, + Run: func(cmd *cobra.Command, args []string) { + + //TODO: Setup Databases depending on flags/attributes + + interfaceAdapterServices := interfaceadapters.NewServices() + defer func() { + err := interfaceAdapterServices.Close() + if err != nil { + fmt.Println(err.Error()) + } + }() + appServices := app.NewServices(interfaceAdapterServices.ClientRepository, interfaceAdapterServices.UserRepository, interfaceAdapterServices.VisorRepository, interfaceAdapterServices.NotificationService, interfaceAdapterServices.MessengerService) + inputportsServices := inputports.NewServices(appServices) + + //messengerService listen + go interfaceAdapterServices.MessengerService.Listen() + + //http-server + inputportsServices.Server.ListenAndServe(&port) + }, +} + +func init() { + rootCmd.AddCommand( + clichat.RootCmd, + ) + var helpflag bool + rootCmd.SetUsageTemplate(help) + rootCmd.PersistentFlags().BoolVarP(&helpflag, "help", "h", false, "help for "+rootCmd.Use) + rootCmd.SetHelpCommand(&cobra.Command{Hidden: true}) + rootCmd.PersistentFlags().MarkHidden("help") //nolint + + rootCmd.Flags().StringVar(&port, "httpport", ":8001", "port to bind") +} + +// Execute executes root CLI command. +func Execute() { + cc.Init(&cc.Config{ + RootCmd: rootCmd, + Headings: cc.HiBlue + cc.Bold, //+ cc.Underline, + Commands: cc.HiBlue + cc.Bold, + CmdShortDescr: cc.HiBlue, + Example: cc.HiBlue + cc.Italic, + ExecName: cc.HiBlue + cc.Bold, + Flags: cc.HiBlue + cc.Bold, + //FlagsDataType: cc.HiBlue, + FlagsDescr: cc.HiBlue, + NoExtraNewlines: true, + NoBottomNewline: true, + }) + + if err := rootCmd.Execute(); err != nil { + log.Fatal("Failed to execute command: ", err) + } +} + +const help = "Usage:\r\n" + + " {{.UseLine}}{{if .HasAvailableSubCommands}}{{end}} {{if gt (len .Aliases) 0}}\r\n\r\n" + + "{{.NameAndAliases}}{{end}}{{if .HasAvailableSubCommands}}\r\n\r\n" + + "Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand)}}\r\n " + + "{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}\r\n\r\n" + + "Flags:\r\n" + + "{{.LocalFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasAvailableInheritedFlags}}\r\n\r\n" + + "Global Flags:\r\n" + + "{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}\r\n\r\n" diff --git a/cmd/apps/skychat/skychat.go b/cmd/apps/skychat/skychat.go index d523ce74e..d2d2ffca6 100644 --- a/cmd/apps/skychat/skychat.go +++ b/cmd/apps/skychat/skychat.go @@ -4,36 +4,11 @@ skychat app for skywire visor */ package main -import ( - "fmt" - "flag" - - "github.com/skycoin/skywire/cmd/apps/skychat/internal/app" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters" -) - -var addr = flag.String("addr", ":8001", "address to bind") +import "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/cli" func main() { - - flag.Parse() - - interfaceAdapterServices := interfaceadapters.NewServices() - defer func() { - err := interfaceAdapterServices.Close() - if err != nil { - fmt.Println(err.Error()) - } - }() - appServices := app.NewServices(interfaceAdapterServices.ClientRepository, interfaceAdapterServices.UserRepository, interfaceAdapterServices.VisorRepository, interfaceAdapterServices.NotificationService, interfaceAdapterServices.MessengerService) - inputPortsServices := inputports.NewServices(appServices) - - //appclient listen - go interfaceAdapterServices.MessengerService.Listen() - - //http-server - inputPortsServices.Server.ListenAndServe(addr) + //cobra-cli + cli.Execute() } diff --git a/pkg/visor/visorconfig/config.go b/pkg/visor/visorconfig/config.go index ac34164f6..c6dd93105 100644 --- a/pkg/visor/visorconfig/config.go +++ b/pkg/visor/visorconfig/config.go @@ -242,7 +242,7 @@ func makeDefaultLauncherAppsConfig(dnsServer string) []appserver.AppConfig { Binary: SkychatName, AutoStart: true, Port: routing.Port(skyenv.SkychatPort), - Args: []string{"-addr", SkychatAddr}, + Args: []string{"--httpport=" + SkychatAddr}, }, { Name: SkysocksName, From 496b95844cf931fb9c2ad75b66094a457fa076b2 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Sun, 23 Apr 2023 00:04:11 +0200 Subject: [PATCH 40/72] improve cli functionality with rpc implement rpc server so appservices can be launched from the cli as rpc client. First implemented usecase is sending textmessages via cli. --- cmd/apps/skychat/internal/app/services.go | 2 + .../inputports/cli/chat/send/textmessage.go | 9 ++- .../skychat/internal/inputports/cli/root.go | 30 +++++++--- .../{cli/chat/send => rpc/chat}/handler.go | 16 ++++-- .../skychat/internal/inputports/rpc/client.go | 45 +++++++++++++++ .../skychat/internal/inputports/rpc/server.go | 56 +++++++++++++++++++ .../skychat/internal/inputports/services.go | 13 ++++- .../internal/interfaceadapters/services.go | 2 + 8 files changed, 157 insertions(+), 16 deletions(-) rename cmd/apps/skychat/internal/inputports/{cli/chat/send => rpc/chat}/handler.go (63%) create mode 100644 cmd/apps/skychat/internal/inputports/rpc/client.go create mode 100644 cmd/apps/skychat/internal/inputports/rpc/server.go diff --git a/cmd/apps/skychat/internal/app/services.go b/cmd/apps/skychat/internal/app/services.go index 739801690..2f53ce419 100644 --- a/cmd/apps/skychat/internal/app/services.go +++ b/cmd/apps/skychat/internal/app/services.go @@ -11,6 +11,8 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) +var AppServices Services + // Services contains all exposed services of the application layer type Services struct { NotificationService notification.Service diff --git a/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go b/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go index d5cc23648..ae2e563d6 100644 --- a/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go +++ b/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go @@ -7,6 +7,7 @@ import ( "github.com/spf13/pflag" "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports" ) var textMessageCmd = &cobra.Command{ @@ -18,9 +19,15 @@ var textMessageCmd = &cobra.Command{ spk := ParsePK(cmd.Flags(), "spk", args[1]) rpk := ParsePK(cmd.Flags(), "rpk", args[2]) msg := args[3] - fmt.Println("SendTextMessage (cli)") + + fmt.Println("SendTextMessage via cli (cli)") fmt.Println(msg) fmt.Printf("to v: %s s: %s, r %s\n", vpk.Hex(), spk.Hex(), rpk.Hex()) + + err := inputports.InputportsServices.RPCClient.SendTextMessage(vpk, spk, rpk, msg) + if err != nil { + fmt.Println(err) + } }, } diff --git a/cmd/apps/skychat/internal/inputports/cli/root.go b/cmd/apps/skychat/internal/inputports/cli/root.go index 6d7a5d264..50e1fbf0b 100644 --- a/cmd/apps/skychat/internal/inputports/cli/root.go +++ b/cmd/apps/skychat/internal/inputports/cli/root.go @@ -14,10 +14,11 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters" ) -var port string +var httpport string +var rpcport string var rootCmd = &cobra.Command{ - Use: "skychat.go", + Use: "skychat", Short: "Command Line Interface for skychat", Long: ` ┌─┐┬┌─┬ ┬ ┌─┐┬ ┬ @@ -30,21 +31,32 @@ var rootCmd = &cobra.Command{ //TODO: Setup Databases depending on flags/attributes - interfaceAdapterServices := interfaceadapters.NewServices() + interfaceadapters.InterfaceAdapterServices = interfaceadapters.NewServices() defer func() { - err := interfaceAdapterServices.Close() + err := interfaceadapters.InterfaceAdapterServices.Close() if err != nil { fmt.Println(err.Error()) } }() - appServices := app.NewServices(interfaceAdapterServices.ClientRepository, interfaceAdapterServices.UserRepository, interfaceAdapterServices.VisorRepository, interfaceAdapterServices.NotificationService, interfaceAdapterServices.MessengerService) - inputportsServices := inputports.NewServices(appServices) + + app.AppServices = app.NewServices( + interfaceadapters.InterfaceAdapterServices.ClientRepository, + interfaceadapters.InterfaceAdapterServices.UserRepository, + interfaceadapters.InterfaceAdapterServices.VisorRepository, + interfaceadapters.InterfaceAdapterServices.NotificationService, + interfaceadapters.InterfaceAdapterServices.MessengerService) + + inputports.InputportsServices = inputports.NewServices(app.AppServices) //messengerService listen - go interfaceAdapterServices.MessengerService.Listen() + go interfaceadapters.InterfaceAdapterServices.MessengerService.Listen() + + //rpc-server + rpcport = ":4040" + go inputports.InputportsServices.RPCServer.ListenAndServe(&rpcport) //http-server - inputportsServices.Server.ListenAndServe(&port) + inputports.InputportsServices.HTTPServer.ListenAndServe(&httpport) }, } @@ -58,7 +70,7 @@ func init() { rootCmd.SetHelpCommand(&cobra.Command{Hidden: true}) rootCmd.PersistentFlags().MarkHidden("help") //nolint - rootCmd.Flags().StringVar(&port, "httpport", ":8001", "port to bind") + rootCmd.Flags().StringVar(&httpport, "httpport", ":8001", "port to bind") } // Execute executes root CLI command. diff --git a/cmd/apps/skychat/internal/inputports/cli/chat/send/handler.go b/cmd/apps/skychat/internal/inputports/rpc/chat/handler.go similarity index 63% rename from cmd/apps/skychat/internal/inputports/cli/chat/send/handler.go rename to cmd/apps/skychat/internal/inputports/rpc/chat/handler.go index 6a08fbbe4..597bc7bc4 100644 --- a/cmd/apps/skychat/internal/inputports/cli/chat/send/handler.go +++ b/cmd/apps/skychat/internal/inputports/rpc/chat/handler.go @@ -1,5 +1,5 @@ -// Package clichatsend contains code of the cobra-cli handler for inputports -package clichatsend +// Package chat contains code of the rpc handler for inputports +package chat import ( "encoding/json" @@ -11,7 +11,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) -// Handler clichat request handler +// Handler chat request handler type Handler struct { chatServices chatservices.ChatServices } @@ -21,6 +21,9 @@ func NewHandler(cs chatservices.ChatServices) *Handler { return &Handler{chatServices: cs} } +// SendTextMessageRPCParam contains the parameter identifier to be parsed by the handler +const SendTextMessageRPCParam = "Handler" + "." + "SendTextMessage" + // SendTextMessageRequestModel represents the request model expected for send text request type SendTextMessageRequestModel struct { VisorPk cipher.PubKey @@ -30,7 +33,12 @@ type SendTextMessageRequestModel struct { } // SendTextMessage sends a text message to the given route -func (c Handler) SendTextMessage(r SendTextMessageRequestModel) error { +func (c Handler) SendTextMessage(r SendTextMessageRequestModel, reply *int) error { + + fmt.Println("RPC: SendTextMessage via cli (rpc)") + fmt.Printf("RPC: Message: %s\n v: %s\n s: %s\n r: %s\n", r.Msg, r.VisorPk.Hex(), r.ServerPk.Hex(), r.RoomPk.Hex()) + + //TODO: maybe check if route is available first and depending on result first send join remote route bytes, err := json.Marshal(r.Msg) if err != nil { diff --git a/cmd/apps/skychat/internal/inputports/rpc/client.go b/cmd/apps/skychat/internal/inputports/rpc/client.go new file mode 100644 index 000000000..212cc434b --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/rpc/client.go @@ -0,0 +1,45 @@ +// Package rpc contains code of the rpc handler for inputports +package rpc + +import ( + "log" + "net/rpc" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/rpc/chat" +) + +// Client represents the rpc client running for this service +type Client struct { + appServices app.Services +} + +// NewClient RPC Client constructor +func NewClient(appServices app.Services) *Client { + rc := &Client{appServices: appServices} + return rc +} + +func (c *Client) SendTextMessage(VisorPk cipher.PubKey, ServerPk cipher.PubKey, RoomPk cipher.PubKey, Message string) error { + + //TODO: fix so that rpc adress is dynamic from cobra args here. + rpcClient, err := rpc.DialHTTP("tcp", ":4040") + if err != nil { + log.Fatal("Connection error: ", err) + } + + stmrm := chat.SendTextMessageRequestModel{ + VisorPk: VisorPk, + ServerPk: ServerPk, + RoomPk: RoomPk, + Msg: Message, + } + + err = rpcClient.Call(chat.SendTextMessageRPCParam, stmrm, nil) + if err != nil { + log.Fatal("Client invocation error: ", err) + } + + return nil +} diff --git a/cmd/apps/skychat/internal/inputports/rpc/server.go b/cmd/apps/skychat/internal/inputports/rpc/server.go new file mode 100644 index 000000000..a83948a17 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/rpc/server.go @@ -0,0 +1,56 @@ +// Package rpc contains code of the rpc handler for inputports +package rpc + +import ( + "fmt" + "log" + "net" + "net/http" + "net/rpc" + + "github.com/gorilla/mux" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/rpc/chat" +) + +var RPCAdress string + +// Server represents the rpc server running for this service +type Server struct { + appServices app.Services + router *mux.Router +} + +// NewServer RPC Server constructor +func NewServer(appServices app.Services) *Server { + rpcServer := &Server{appServices: appServices} + rpcServer.router = mux.NewRouter() + + return rpcServer +} + +// ListenAndServe Starts listening for requests +func (rpcServer *Server) ListenAndServe(port *string) { + + api := chat.NewHandler(rpcServer.appServices.ChatServices) + err := rpc.Register(api) + if err != nil { + log.Fatal("error registering API", err) + } + + rpc.HandleHTTP() + + listener, err := net.Listen("tcp", *port) + if err != nil { + log.Fatal("Listener error", err) + } + + fmt.Println("Serving RPC on", *port) + + err = http.Serve(listener, nil) + if err != nil { + log.Fatal("error serving: ", err) + } + + RPCAdress = *port +} diff --git a/cmd/apps/skychat/internal/inputports/services.go b/cmd/apps/skychat/internal/inputports/services.go index 33b0be196..ca1e06264 100644 --- a/cmd/apps/skychat/internal/inputports/services.go +++ b/cmd/apps/skychat/internal/inputports/services.go @@ -4,14 +4,23 @@ package inputports import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/app" "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/http" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/rpc" ) +var InputportsServices Services + // Services contains the ports services type Services struct { - Server *http.Server + HTTPServer *http.Server + RPCServer *rpc.Server + RPCClient *rpc.Client } // NewServices instantiates the services of input ports func NewServices(appServices app.Services) Services { - return Services{Server: http.NewServer(appServices)} + return Services{ + HTTPServer: http.NewServer(appServices), + RPCServer: rpc.NewServer(appServices), + RPCClient: rpc.NewClient(appServices), + } } diff --git a/cmd/apps/skychat/internal/interfaceadapters/services.go b/cmd/apps/skychat/internal/interfaceadapters/services.go index da7d1b883..126e23e68 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/services.go +++ b/cmd/apps/skychat/internal/interfaceadapters/services.go @@ -15,6 +15,8 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/storage/memory" ) +var InterfaceAdapterServices Services + // Services contains the exposed services of interface adapters type Services struct { ClientRepository client.Repository From 9d265910a84db2cd5f541d24651efba51a825c60 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Sun, 23 Apr 2023 00:16:56 +0200 Subject: [PATCH 41/72] fix make-check errs --- cmd/apps/skychat/internal/app/services.go | 1 + .../internal/inputports/cli/chat/send/root.go | 1 + .../skychat/internal/inputports/rpc/client.go | 3 ++- .../skychat/internal/inputports/rpc/server.go | 27 +++++++++++-------- .../skychat/internal/inputports/services.go | 1 + .../internal/interfaceadapters/services.go | 1 + 6 files changed, 22 insertions(+), 12 deletions(-) diff --git a/cmd/apps/skychat/internal/app/services.go b/cmd/apps/skychat/internal/app/services.go index 2f53ce419..2f28dda3d 100644 --- a/cmd/apps/skychat/internal/app/services.go +++ b/cmd/apps/skychat/internal/app/services.go @@ -11,6 +11,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) +// AppServices holds the apps services as variable var AppServices Services // Services contains all exposed services of the application layer diff --git a/cmd/apps/skychat/internal/inputports/cli/chat/send/root.go b/cmd/apps/skychat/internal/inputports/cli/chat/send/root.go index 22a2a9ee7..2706683d7 100644 --- a/cmd/apps/skychat/internal/inputports/cli/chat/send/root.go +++ b/cmd/apps/skychat/internal/inputports/cli/chat/send/root.go @@ -1,3 +1,4 @@ +// Package clichatsend contains code of the cobra cli chat send commands package clichatsend import "github.com/spf13/cobra" diff --git a/cmd/apps/skychat/internal/inputports/rpc/client.go b/cmd/apps/skychat/internal/inputports/rpc/client.go index 212cc434b..ee40fa666 100644 --- a/cmd/apps/skychat/internal/inputports/rpc/client.go +++ b/cmd/apps/skychat/internal/inputports/rpc/client.go @@ -21,9 +21,10 @@ func NewClient(appServices app.Services) *Client { return rc } +// SendTextMessage sends the command to send a message via rpc func (c *Client) SendTextMessage(VisorPk cipher.PubKey, ServerPk cipher.PubKey, RoomPk cipher.PubKey, Message string) error { - //TODO: fix so that rpc adress is dynamic from cobra args here. + //TODO: fix so that rpc address is dynamic from cobra args here. rpcClient, err := rpc.DialHTTP("tcp", ":4040") if err != nil { log.Fatal("Connection error: ", err) diff --git a/cmd/apps/skychat/internal/inputports/rpc/server.go b/cmd/apps/skychat/internal/inputports/rpc/server.go index a83948a17..b49d8a80a 100644 --- a/cmd/apps/skychat/internal/inputports/rpc/server.go +++ b/cmd/apps/skychat/internal/inputports/rpc/server.go @@ -4,17 +4,16 @@ package rpc import ( "fmt" "log" - "net" "net/http" "net/rpc" + "time" "github.com/gorilla/mux" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app" "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/rpc/chat" ) -var RPCAdress string - // Server represents the rpc server running for this service type Server struct { appServices app.Services @@ -40,17 +39,23 @@ func (rpcServer *Server) ListenAndServe(port *string) { rpc.HandleHTTP() - listener, err := net.Listen("tcp", *port) - if err != nil { - log.Fatal("Listener error", err) - } + /* + listener, err := net.Listen("tcp", *port) + if err != nil { + log.Fatal("Listener error", err) + }*/ fmt.Println("Serving RPC on", *port) - err = http.Serve(listener, nil) - if err != nil { - log.Fatal("error serving: ", err) + //err = http.Serve(listener, nil) + srv := &http.Server{ + Addr: *port, + ReadTimeout: 5 * time.Second, + WriteTimeout: 10 * time.Second, } + /*if err != nil { + log.Fatal("error serving: ", err) + }*/ - RPCAdress = *port + log.Fatal(srv.ListenAndServe()) } diff --git a/cmd/apps/skychat/internal/inputports/services.go b/cmd/apps/skychat/internal/inputports/services.go index ca1e06264..76819a3aa 100644 --- a/cmd/apps/skychat/internal/inputports/services.go +++ b/cmd/apps/skychat/internal/inputports/services.go @@ -7,6 +7,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/rpc" ) +// InputportsServices holds the inputports services as variable var InputportsServices Services // Services contains the ports services diff --git a/cmd/apps/skychat/internal/interfaceadapters/services.go b/cmd/apps/skychat/internal/interfaceadapters/services.go index 126e23e68..9eaff434c 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/services.go +++ b/cmd/apps/skychat/internal/interfaceadapters/services.go @@ -15,6 +15,7 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/storage/memory" ) +// InterfaceAdapterServices holds the interface adapter services as variable var InterfaceAdapterServices Services // Services contains the exposed services of interface adapters From 96f7183663ccb17d212660131a747af3617e3c8b Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Sun, 30 Apr 2023 20:46:22 +0200 Subject: [PATCH 42/72] small rpc fix --- cmd/apps/skychat/internal/inputports/rpc/server.go | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/cmd/apps/skychat/internal/inputports/rpc/server.go b/cmd/apps/skychat/internal/inputports/rpc/server.go index b49d8a80a..357e3b659 100644 --- a/cmd/apps/skychat/internal/inputports/rpc/server.go +++ b/cmd/apps/skychat/internal/inputports/rpc/server.go @@ -39,23 +39,13 @@ func (rpcServer *Server) ListenAndServe(port *string) { rpc.HandleHTTP() - /* - listener, err := net.Listen("tcp", *port) - if err != nil { - log.Fatal("Listener error", err) - }*/ - fmt.Println("Serving RPC on", *port) - //err = http.Serve(listener, nil) srv := &http.Server{ Addr: *port, ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, } - /*if err != nil { - log.Fatal("error serving: ", err) - }*/ log.Fatal(srv.ListenAndServe()) } From 341b4a05c0d6bdffe69c8fc11a680c0323bde5b5 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Sun, 30 Apr 2023 20:48:06 +0200 Subject: [PATCH 43/72] fix sending large info When setting a large image in the info, the app crashed. The app also crashed while trying to log the big IMG entry inside info. --- cmd/apps/skychat/internal/domain/info/info.go | 5 +- .../messenger/netcon/messenger_service.go | 80 ++++++++++++++----- .../netcon/messenger_service_local_server.go | 2 +- .../messenger/netcon/messenger_service_p2p.go | 2 +- .../netcon/messenger_service_remote_server.go | 2 +- 5 files changed, 68 insertions(+), 23 deletions(-) diff --git a/cmd/apps/skychat/internal/domain/info/info.go b/cmd/apps/skychat/internal/domain/info/info.go index e1a209884..1cc41b0d9 100644 --- a/cmd/apps/skychat/internal/domain/info/info.go +++ b/cmd/apps/skychat/internal/domain/info/info.go @@ -77,11 +77,12 @@ func NewDefaultInfo() Info { } // DefaultImage is the default image of all infos -const DefaultImage = "0" +//const DefaultImage = "0" // DefaultImage is the default image of all infos --> This doesn't work atm as the packet size is to small to send this in one packet -//const DefaultImage = "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAIAAAAHjs1qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5OTMyNUUzOTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjY5OTMyNUU0OTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6Njk5MzI1RTE5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Njk5MzI1RTI5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7FIRCzAAAPn0lEQVR42uyd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" +const DefaultImage = "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAIAAAAHjs1qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5OTMyNUUzOTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjY5OTMyNUU0OTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6Njk5MzI1RTE5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Njk5MzI1RTI5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7FIRCzAAAPn0lEQVR42uyd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" +// const DefaultImage = // IsEmpty checks if info is empty func (i *Info) IsEmpty() bool { return *i == Info{} diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index 0b69e79e1..7835452c0 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -3,8 +3,10 @@ package netcon import ( "context" + "encoding/binary" "encoding/json" "fmt" + "io" "net" "time" @@ -62,24 +64,55 @@ func (ms MessengerService) Handle(pk cipher.PubKey) { localPK := pCli.GetAppClient().Config().VisorPK - for { + buf := make([]byte, 1024) - //read packets - buf := make([]byte, 32*1024*4) - n, err := conn.Read(buf) - fmt.Printf("Received %d bytes \n", n) + for { + // read the length prefix + prefix := make([]byte, 4) + _, err = io.ReadFull(conn, prefix) if err != nil { - fmt.Println("Failed to read packet:", err) - //close and delete connection - //? close connection ? - err2 := pCli.DeleteConn(conn.RemoteAddr().(appnet.Addr).PubKey) - if err2 != nil { - errs <- err2 - return - } + fmt.Printf("Error Prefix: %s", err) errs <- err return } + length_from_prefix := binary.BigEndian.Uint32(prefix) + fmt.Printf("Prefix length: %d \n", length_from_prefix) + + data := make([]byte, 0) + length := 0 + for length = 0; length < int(length_from_prefix); { + //read packets + n, err := conn.Read(buf) + if err != nil { + // log if not normal error + if err != io.EOF { + fmt.Printf("Read error - %s\n", err) + } + break + } + + // append read data to full data + data = append(data, buf[:n]...) + + // update total read var + length += n + fmt.Printf("Data: %d/%d (PacketSize: %d) \n", length, length_from_prefix, n) + } + + fmt.Printf("Received %d bytes \n", length) + /* + if err != nil { + fmt.Println("Failed to read packet:", err) + //close and delete connection + //? close connection ? + err2 := pCli.DeleteConn(conn.RemoteAddr().(appnet.Addr).PubKey) + if err2 != nil { + errs <- err2 + return + } + errs <- err + return + }*/ //unmarshal the received bytes to a message.Message m := message.RAWMessage{} @@ -87,7 +120,7 @@ func (ms MessengerService) Handle(pk cipher.PubKey) { fmt.Println("New Raw Message") fmt.Println("---------------------------------------------------------------------------------------------------") - err = json.Unmarshal(buf[:n], &m) + err = json.Unmarshal(data, &m) if err != nil { fmt.Printf("Failed to unmarshal json message: %v \n", err) } else { @@ -101,7 +134,7 @@ func (ms MessengerService) Handle(pk cipher.PubKey) { fmt.Printf("Dest: %s \n", jm.Dest.String()) fmt.Printf("MsgType: %d \n", jm.MsgType) fmt.Printf("MsgSubType: %d \n", jm.MsgSubtype) - fmt.Printf("Message: %s \n", string(jm.Message)) + //fmt.Printf("Message: %s \n", string(jm.Message)) fmt.Printf("Status: %d \n", jm.Status) fmt.Printf("Seen: %t \n", jm.Seen) fmt.Println("---------------------------------------------------------------------------------------------------") @@ -158,7 +191,7 @@ func (ms MessengerService) Dial(pk cipher.PubKey) (net.Conn, error) { Port: pCli.GetPort(), } - var r = netutil.NewRetrier(pCli.GetLog(), 50*time.Millisecond, netutil.DefaultMaxBackoff, 5, 2) + var r = netutil.NewRetrier(pCli.GetLog(), 50*time.Millisecond, netutil.DefaultMaxBackoff, 2, 2) ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -273,7 +306,7 @@ func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, fmt.Printf("Dest: %s \n", m.Dest.String()) fmt.Printf("MsgType: %d \n", m.MsgType) fmt.Printf("MsgSubType: %d \n", m.MsgSubtype) - fmt.Printf("Message: %s \n", string(m.Message)) + //fmt.Printf("Message: %s \n", string(m.Message)) fmt.Printf("Status: %d \n", m.Status) fmt.Printf("Seen: %t \n", m.Seen) fmt.Println("---------------------------------------------------------------------------------------------------") @@ -296,9 +329,20 @@ func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, } } - fmt.Printf("Write Bytes to Conn: %s \n", conn.LocalAddr()) + // create the length prefix + prefix := make([]byte, 4) + binary.BigEndian.PutUint32(prefix, uint32(len(bytes))) + fmt.Printf("Write prefix with %d Bytes to Conn: %s \n", len(prefix), conn.LocalAddr()) + _, err = conn.Write(prefix) + if err != nil { + fmt.Printf("Failed to write prefix: %v \n", err) + return err + } + + fmt.Printf("Write %d Bytes to Conn: %s \n", len(bytes), conn.LocalAddr()) _, err = conn.Write(bytes) if err != nil { + fmt.Printf("Failed to write bytes: %v \n", err) return err } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go index 812cb9d00..06120127b 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go @@ -630,7 +630,7 @@ func (ms MessengerService) handleLocalServerInfoMsgType(v *chat.Visor, m message fmt.Printf("Pk: %s \n", i.Pk.Hex()) fmt.Printf("Alias: %s \n", i.Alias) fmt.Printf("Desc: %s \n", i.Desc) - fmt.Printf("Img: %s \n", i.Img) + //fmt.Printf("Img: %s \n", i.Img) fmt.Println("---------------------------------------------------------------------------------------------------") //get server from visor diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go index f3eed2ae8..03c012810 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go @@ -280,7 +280,7 @@ func (ms MessengerService) handleP2PInfoMsgType(v *chat.Visor, m message.Message fmt.Printf("Pk: %s \n", i.Pk.Hex()) fmt.Printf("Alias: %s \n", i.Alias) fmt.Printf("Desc: %s \n", i.Desc) - fmt.Printf("Img: %s \n", i.Img) + //fmt.Printf("Img: %s \n", i.Img) fmt.Println("---------------------------------------------------------------------------------------------------") //update the info of the p2p diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go index 3320407dc..a36560b34 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go @@ -154,7 +154,7 @@ func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message. fmt.Printf("Pk: %s \n", i.Pk.Hex()) fmt.Printf("Alias: %s \n", i.Alias) fmt.Printf("Desc: %s \n", i.Desc) - fmt.Printf("Img: %s \n", i.Img) + //fmt.Printf("Img: %s \n", i.Img) fmt.Println("---------------------------------------------------------------------------------------------------") err = v.SetRouteInfo(pkroute, i) From 35e12c468f65d487477a6061afa0a6823de837d9 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Mon, 1 May 2023 15:17:34 +0200 Subject: [PATCH 44/72] fix make-check errs --- cmd/apps/skychat/internal/domain/info/info.go | 1 - .../messenger/netcon/messenger_service.go | 8 ++++---- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/cmd/apps/skychat/internal/domain/info/info.go b/cmd/apps/skychat/internal/domain/info/info.go index 1cc41b0d9..98557ce03 100644 --- a/cmd/apps/skychat/internal/domain/info/info.go +++ b/cmd/apps/skychat/internal/domain/info/info.go @@ -82,7 +82,6 @@ func NewDefaultInfo() Info { // DefaultImage is the default image of all infos --> This doesn't work atm as the packet size is to small to send this in one packet const DefaultImage = "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAIAAAAHjs1qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5OTMyNUUzOTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjY5OTMyNUU0OTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6Njk5MzI1RTE5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Njk5MzI1RTI5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7FIRCzAAAPn0lEQVR42uyd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" -// const DefaultImage = // IsEmpty checks if info is empty func (i *Info) IsEmpty() bool { return *i == Info{} diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index 7835452c0..8b855af9a 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -75,12 +75,12 @@ func (ms MessengerService) Handle(pk cipher.PubKey) { errs <- err return } - length_from_prefix := binary.BigEndian.Uint32(prefix) - fmt.Printf("Prefix length: %d \n", length_from_prefix) + lengthFromPrefix := binary.BigEndian.Uint32(prefix) + fmt.Printf("Prefix length: %d \n", lengthFromPrefix) data := make([]byte, 0) length := 0 - for length = 0; length < int(length_from_prefix); { + for length = 0; length < int(lengthFromPrefix); { //read packets n, err := conn.Read(buf) if err != nil { @@ -96,7 +96,7 @@ func (ms MessengerService) Handle(pk cipher.PubKey) { // update total read var length += n - fmt.Printf("Data: %d/%d (PacketSize: %d) \n", length, length_from_prefix, n) + fmt.Printf("Data: %d/%d (PacketSize: %d) \n", length, lengthFromPrefix, n) } fmt.Printf("Received %d bytes \n", length) From 97ddb718993ce768e98245755a43c4fc8bfc70f3 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Tue, 6 Jun 2023 20:07:51 +0200 Subject: [PATCH 45/72] visor repository with boltdb Got visor repository working with boltdb and changed service to use boltdb instead of memory. Memory repositories will stay to be able to use skychat with a flag on 'memory'/'privacy' mode. --- .../internal/interfaceadapters/services.go | 2 +- .../storage/boltdb/visor_repo.go | 147 ++++++++++++++++++ 2 files changed, 148 insertions(+), 1 deletion(-) create mode 100644 cmd/apps/skychat/internal/interfaceadapters/storage/boltdb/visor_repo.go diff --git a/cmd/apps/skychat/internal/interfaceadapters/services.go b/cmd/apps/skychat/internal/interfaceadapters/services.go index 9eaff434c..24979fde4 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/services.go +++ b/cmd/apps/skychat/internal/interfaceadapters/services.go @@ -31,8 +31,8 @@ type Services struct { func NewServices() Services { cliRepo := memory.NewClientRepo() cli, _ := cliRepo.GetClient() //nolint - vsrRepo := memory.NewVisorRepo() usrRepo := boltdb.NewUserRepo(cli.GetAppClient().Config().VisorPK) + vsrRepo := boltdb.NewVisorRepo() ns := channel.NewNotificationService() ms := netcon.NewMessengerService(ns, cliRepo, usrRepo, vsrRepo) diff --git a/cmd/apps/skychat/internal/interfaceadapters/storage/boltdb/visor_repo.go b/cmd/apps/skychat/internal/interfaceadapters/storage/boltdb/visor_repo.go new file mode 100644 index 000000000..85b010c68 --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/boltdb/visor_repo.go @@ -0,0 +1,147 @@ +// Package boltdb contains code of the chat repo of interfaceadapters +package boltdb + +import ( + "encoding/json" + "fmt" + "sync" + + "github.com/boltdb/bolt" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" +) + +// VISORBUCKET defines the key for the visor bucket +const VISORBUCKET = "visors" + +// VisorRepo Implements the Repository Interface to provide an in-memory storage provider +type VisorRepo struct { + db *bolt.DB + visorsMu sync.Mutex +} + +// NewVisorRepo Constructor +func NewVisorRepo() *VisorRepo { + r := VisorRepo{} + + db, err := bolt.Open("chats.db", 0600, nil) + if err != nil { + fmt.Println(err.Error()) + } + r.db = db + + return &r +} + +// GetByPK Returns the visor with the provided pk +func (r *VisorRepo) GetByPK(pk cipher.PubKey) (*chat.Visor, error) { + r.visorsMu.Lock() + defer r.visorsMu.Unlock() + + var vsr chat.Visor + err := r.db.View(func(tx *bolt.Tx) error { + b := tx.Bucket([]byte(VISORBUCKET)) + if b == nil { + // The bucket doesn't exist + return fmt.Errorf("no visors in repository") + } + v := b.Get([]byte(pk.Hex())) + + err := json.Unmarshal([]byte(v), &vsr) + if err != nil { + return fmt.Errorf("could not get visor by pk %v", err) + } + return nil + }) + return &vsr, err +} + +// GetAll Returns all stored visors +func (r *VisorRepo) GetAll() ([]chat.Visor, error) { + r.visorsMu.Lock() + defer r.visorsMu.Unlock() + + var vsrs []chat.Visor + + err := r.db.View(func(tx *bolt.Tx) error { + // Assume bucket exists and has keys + b := tx.Bucket([]byte(VISORBUCKET)) + if b == nil { + // The bucket doesn't exist + return fmt.Errorf("no visors in repository") + } + + // Create a cursor to iterate over the keys in the bucket + c := b.Cursor() + key, _ := c.First() + + // Check if the first key is nil + if key == nil { + return fmt.Errorf("no visors in repository") + } + err := b.ForEach(func(k, v []byte) error { + var vsr chat.Visor + err := json.Unmarshal([]byte(v), &vsr) + if err != nil { + return fmt.Errorf("could not get visor: %v", err) + } + vsrs = append(vsrs, vsr) + return nil + }) + return err + + }) + if err != nil { + fmt.Println(err.Error()) + } + return vsrs, nil + //TODO: return err and handle correctly in caller functions? -> BUT we don't want to have an error when getAll is called, only an empty slice +} + +// Add adds the provided visor to the repository +func (r *VisorRepo) Add(visor chat.Visor) error { + return r.Set(visor) +} + +// Set sets the provided visor +func (r *VisorRepo) Set(visor chat.Visor) error { + r.visorsMu.Lock() + defer r.visorsMu.Unlock() + + // Store the user model in the user bucket using the pk as the key. + err := r.db.Update(func(tx *bolt.Tx) error { + b, err := tx.CreateBucketIfNotExists([]byte(VISORBUCKET)) + if err != nil { + return err + } + + encoded, err := json.Marshal(visor) + if err != nil { + return err + } + return b.Put([]byte(visor.GetPK().Hex()), encoded) + }) + return err +} + +// Delete deletes the chat with the provided pk +func (r *VisorRepo) Delete(pk cipher.PubKey) error { + r.visorsMu.Lock() + defer r.visorsMu.Unlock() + + err := r.db.Update(func(tx *bolt.Tx) error { + b := tx.Bucket([]byte(VISORBUCKET)) + if b == nil { + // The bucket doesn't exist + return fmt.Errorf("no visors in repository") + } + return b.Delete([]byte(pk.Hex())) + }) + return err +} + +// Close closes the db +func (r *VisorRepo) Close() error { + return r.db.Close() +} From 46398bc979bb3354bfcdc992a4909af3f2c1fa0a Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Tue, 6 Jun 2023 20:15:04 +0200 Subject: [PATCH 46/72] relocate todos --- .../internal/app/chat/commands/todos.go | 55 ----------------- cmd/apps/skychat/todos.md | 61 +++++++++++++++++++ 2 files changed, 61 insertions(+), 55 deletions(-) delete mode 100644 cmd/apps/skychat/internal/app/chat/commands/todos.go create mode 100644 cmd/apps/skychat/todos.md diff --git a/cmd/apps/skychat/internal/app/chat/commands/todos.go b/cmd/apps/skychat/internal/app/chat/commands/todos.go deleted file mode 100644 index 60893a811..000000000 --- a/cmd/apps/skychat/internal/app/chat/commands/todos.go +++ /dev/null @@ -1,55 +0,0 @@ -package commands - -//-to-dos and brain-storming about the future of skychat - -//general -//TODO: Sending json that are bigger than one packet -> otherwise big lists and sending the image info won't work. -//TODO: message statuses: sent, received(achieved by implementing the peer to send a 'received-message' back) to check whether the message really was received by the peer -//TODO: database for user and visor repository -//FUTUREFEATUE: flags to setup if database or in-memory is used for repositories (data is lost when stoping app) -//--> maybe even a way on setting this up for each chat, so simultaneously persistent chats and "deleteable" chats are possible -//--> how about "self-deleting-messages"? deletes itself after (1hour, 24hour, etc...) -//TODO: cli-interface -//with cli-interface a connection with the systray app would be possible -> notifications about new messages, incoming calls etc. -//FUTUREFEATUE: encrypted messages (encrypted sending and encrypted saving on local storage) --> Password for app required - -//general-future -//FUTUREFEATUE: voip-channels -//FUTUREFEATUE: video-streams -//FUTUREFEATUE: sending-fiber via chat, with notification about received payments -> also sending-fiber-requests - -//UI -//TODO:Make UI more beautiful -//TODO:Implement to look into peer-book and set custom aliases -//TODO:Implement to look into server-info, and see all lists (admins, members, etc) - -//? How about a way on customizing the appearance of a group chat and saving the css-data inside the server and sending it to the peers - -//usecases-------------------------------------------- - -//p2p----------------------- -//make p2p room within own visor -> for informations from other apps or so? - -//server & rooms------------ -//TODO:send_set_route_info_message.go -//TODO:send_hire_admin_message.go //maybe only allow this action from server-host -//TODO:send_fire_admin_message.go //maybe only allow this action from server-host -//TODO:send_hire_moderator_message.go -//TODO:send_fire_moderator_message.go -//[x]send_mute_peer_message.go --> backend implemented, frontend missing -//[x]:send_unmute_peer_message.go --> backend implemented, frontend missing - -//TODO:send_add_room_message.go -//TODO:send_delete_room_message.go -//TODO:send_hide_room_message.go -//TODO:send_unhide_room_message.go -//TODO:send_set_route_info_message.go - -//send_hide_message.go //first a way to edit messages must be implemented -//send_unhide_message.go //first a way to edit messages must be implemented -//send_edit_message.go //first a way to edit messages must be implemented -//send_delete_message.go //first a way to edit messages must be implemented - -//send_invite_message.go //an option to send an invite message to a group which then can be accepted or rejected by the peer - -//transfer_local_server.go //a way to transfer ownership to another visor diff --git a/cmd/apps/skychat/todos.md b/cmd/apps/skychat/todos.md new file mode 100644 index 000000000..b960c47e2 --- /dev/null +++ b/cmd/apps/skychat/todos.md @@ -0,0 +1,61 @@ + +# ToDos and brain-storming about the future of skychat + +## General + +- TODO: message statuses: sent, received(achieved by implementing the peer to send a 'received-message' back) to check whether the message really was received by the peer +- [x] database for user repository +- [x] database for visor repository +- FUTUREFEATUE: flags to setup if database or in-memory is used for repositories (data is lost when stoping app) + --> maybe even a way on setting this up for each chat, so simultaneously persistent chats and "deleteable" chats are possible + --> how about "self-deleting-messages"? deletes itself after (1hour, 24hour, etc...) +- [x] cli-interface + with cli-interface a connection with the systray app would be possible -> notifications about new messages, incoming calls etc. +- FUTUREFEATUE: encrypted messages (encrypted sending and encrypted saving on local storage) --> Password for app required + +## General-Future + +- FUTUREFEATURE: voip-channels +- FUTUREFEATURE: video-streams +- FUTUREFEATURE: sending-fiber via chat, with notification about received payments -> also sending-fiber-payment-requests +- FUTUREFEATURE: Implement Interface to skycoin/fiber wallet to send and receive crypto inside the chat. (Also so open to use other wallets than fiber wallets? Or just implement other coins into fiberwallet) + +## UI + +- TODO:Make UI more beautiful +- TODO:Implement to look into peer-book and set custom aliases +- TODO:Implement to look into server-info, and see all lists (admins, members, etc) + +How about a way on customizing the appearance of a group chat and saving the css-data inside the server and sending it to the peers? + +## Usecases + +### P2P + +- make p2p room within own visor -> for informations from other apps or so + +### Server & Rooms + +- TODO:send_hire_admin_message.go //maybe only allow this action from server-host +- TODO:send_fire_admin_message.go //maybe only allow this action from server-host +[x]send_hire_moderator_message.go +[x]send_fire_moderator_message.go +[x]send_mute_peer_message.go --> backend implemented, frontend missing +[x]:send_unmute_peer_message.go --> backend implemented, frontend missing + +- TODO:send_add_room_message.go +- TODO:send_delete_room_message.go +- TODO:send_hide_room_message.go +- TODO:send_unhide_room_message.go +- TODO:send_set_route + +- []send_hide_message.go //first a way to edit messages must be implemented +- []send_unhide_message.go //first a way to edit messages must be implemented +- []send_edit_message.go //first a way to edit messages must be implemented +- []send_delete_message.go //first a way to edit messages must be implemented + +- []send_invite_message.go //an option to send an invite message to a group which then can be accepted or rejected by the peer + +- []transfer_local_server.go //a way to transfer ownership of a room or server to another visor + +- []implement DNS handles for Servers/Rooms and P2Ps From c8332860eea7b358eb43d8e665b290ca5f2463a5 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Tue, 6 Jun 2023 20:17:21 +0200 Subject: [PATCH 47/72] first refactoring for more readability Effort to make it easier to understand what happens inside the app. More refactoring might be needed inside the /app/chat (usecases) folder --- .../app/chat/commands/join_remote_route.go | 2 +- .../app/chat/commands/leave_remote_route.go | 2 +- .../internal/app/messenger/messenger.go | 2 +- .../skychat/internal/domain/client/client.go | 8 + cmd/apps/skychat/internal/domain/info/info.go | 3 - .../domain/message/default_messages.go | 244 +++++++ .../internal/domain/message/message.go | 296 ++------ .../skychat/internal/domain/peer/peerbook.go | 10 +- .../messenger/netcon/messenger_service.go | 684 ++++-------------- .../netcon/messenger_service_local_server.go | 5 +- .../netcon/messenger_service_send_messages.go | 326 +++++++++ 11 files changed, 819 insertions(+), 763 deletions(-) create mode 100644 cmd/apps/skychat/internal/domain/message/default_messages.go create mode 100644 cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_send_messages.go diff --git a/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go b/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go index 4557135f9..65ad3cc8b 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go +++ b/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go @@ -48,7 +48,7 @@ func (h joinRemoteRouteRequestHandler) Handle(command JoinRemoteRouteRequest) er return err } - go h.messengerService.Handle(command.Route.Visor) //nolint:errcheck + go h.messengerService.HandleConnection(command.Route.Visor) //nolint:errcheck return nil } diff --git a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go index ab857429d..43deb3799 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go +++ b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go @@ -86,7 +86,7 @@ func (h leaveRemoteRouteRequestHandler) Handle(command LeaveRemoteRouteRequest) // Send LeaveChatMessage to remote server err = h.ms.SendLeaveRouteMessage(command.Route) if err != nil { - return err + fmt.Println(err) } // Delete room from server diff --git a/cmd/apps/skychat/internal/app/messenger/messenger.go b/cmd/apps/skychat/internal/app/messenger/messenger.go index 4e764e44f..a6d884af6 100644 --- a/cmd/apps/skychat/internal/app/messenger/messenger.go +++ b/cmd/apps/skychat/internal/app/messenger/messenger.go @@ -9,7 +9,7 @@ import ( // Service interface is the interface to the service type Service interface { - Handle(pk cipher.PubKey) + HandleConnection(pk cipher.PubKey) Listen() //only used as client/p2p diff --git a/cmd/apps/skychat/internal/domain/client/client.go b/cmd/apps/skychat/internal/domain/client/client.go index 6d57b1002..8e014a2cd 100644 --- a/cmd/apps/skychat/internal/domain/client/client.go +++ b/cmd/apps/skychat/internal/domain/client/client.go @@ -63,6 +63,14 @@ func (c *Client) GetConnByPK(pk cipher.PubKey) (net.Conn, error) { return nil, fmt.Errorf("no conn available with the requested visor") } +// ConnectionToPkExists returns if a connection to the given pk is saved inside conns +func (c *Client) ConnectionToPkExists(pk cipher.PubKey) bool { + if _, ok := c.conns[pk]; ok { + return true + } + return false +} + // AddConn adds the given net.Conn to the map to keep track of active connections func (c *Client) AddConn(pk cipher.PubKey, conn net.Conn) error { //check if conn already added diff --git a/cmd/apps/skychat/internal/domain/info/info.go b/cmd/apps/skychat/internal/domain/info/info.go index 98557ce03..f558a21a6 100644 --- a/cmd/apps/skychat/internal/domain/info/info.go +++ b/cmd/apps/skychat/internal/domain/info/info.go @@ -76,9 +76,6 @@ func NewDefaultInfo() Info { return info } -// DefaultImage is the default image of all infos -//const DefaultImage = "0" - // DefaultImage is the default image of all infos --> This doesn't work atm as the packet size is to small to send this in one packet const DefaultImage = "iVBORw0KGgoAAAANSUhEUgAAAPoAAAD6CAIAAAAHjs1qAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyZpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNS1jMDIxIDc5LjE1NTc3MiwgMjAxNC8wMS8xMy0xOTo0NDowMCAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTQgKFdpbmRvd3MpIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjY5OTMyNUUzOTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjY5OTMyNUU0OTY0QjExRUI4MDZERkQ5M0JBOUY1NThGIj4gPHhtcE1NOkRlcml2ZWRGcm9tIHN0UmVmOmluc3RhbmNlSUQ9InhtcC5paWQ6Njk5MzI1RTE5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiIHN0UmVmOmRvY3VtZW50SUQ9InhtcC5kaWQ6Njk5MzI1RTI5NjRCMTFFQjgwNkRGRDkzQkE5RjU1OEYiLz4gPC9yZGY6RGVzY3JpcHRpb24+IDwvcmRmOlJERj4gPC94OnhtcG1ldGE+IDw/eHBhY2tldCBlbmQ9InIiPz7FIRCzAAAPn0lEQVR42uyd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" diff --git a/cmd/apps/skychat/internal/domain/message/default_messages.go b/cmd/apps/skychat/internal/domain/message/default_messages.go new file mode 100644 index 000000000..667cff20e --- /dev/null +++ b/cmd/apps/skychat/internal/domain/message/default_messages.go @@ -0,0 +1,244 @@ +package message + +import ( + "time" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// getUTCTimeStamp returns UTC TimeStamp +// This is used so local time of sender is unknown to receiver +func getUTCTimeStamp() time.Time { + loc, err := time.LoadLocation("UTC") + if err != nil { + return time.Now() + } + now := time.Now().In(loc) + return now +} + +// NewTextMessage returns a Message +func NewTextMessage(pkOrigin cipher.PubKey, routeDestination util.PKRoute, msg []byte) Message { + m := Message{} + m.Origin = pkOrigin + m.Root = util.NewP2PRoute(pkOrigin) + m.Dest = routeDestination + m.MsgType = TxtMsgType + m.MsgSubtype = 0 + m.Message = msg + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} + +// NewRouteRequestMessage returns a request Message +func NewRouteRequestMessage(pkOrigin cipher.PubKey, routeDestination util.PKRoute) Message { + m := Message{} + m.Origin = pkOrigin + m.Root = util.NewP2PRoute(pkOrigin) + m.Dest = routeDestination + m.MsgType = ConnMsgType + m.MsgSubtype = ConnMsgTypeRequest + m.Message = []byte("Chat Request") + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} + +// NewChatAcceptMessage returns a chat accepted message +// pk is the users pk to set the messages root +func NewChatAcceptMessage(root util.PKRoute, dest util.PKRoute) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = ConnMsgType + m.MsgSubtype = ConnMsgTypeAccept + m.Status = MsgStatusInitial + m.Message = []byte("Chat Accepted") + m.Time = getUTCTimeStamp() + return m +} + +// NewChatRejectMessage returns new chat rejected message +func NewChatRejectMessage(root util.PKRoute, dest util.PKRoute) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = ConnMsgType + m.MsgSubtype = ConnMsgTypeReject + m.Message = []byte("Chat Rejected") + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} + +// NewChatLeaveMessage returns new chat leave message +func NewChatLeaveMessage(root util.PKRoute, dest util.PKRoute) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = ConnMsgType + m.MsgSubtype = ConnMsgTypeLeave + m.Message = []byte("Chat Left") + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} + +// NewRouteDeletedMessage returns new message to info about deleted route +func NewRouteDeletedMessage(root util.PKRoute, dest util.PKRoute) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = ConnMsgType + m.MsgSubtype = ConnMsgTypeDelete + m.Message = []byte("Chat Deleted") + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} + +// NewChatInfoMessage returns new chat info +func NewChatInfoMessage(root util.PKRoute, dest util.PKRoute, info []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = InfoMsgType + m.MsgSubtype = InfoMsgTypeSingle + m.Message = info + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} + +// NewAddRoomMessage returns a Message +func NewAddRoomMessage(root util.PKRoute, dest util.PKRoute, info []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = CmdMsgType + m.MsgSubtype = CmdMsgTypeAddRoom + m.Message = info + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} + +// NewDeleteRoomMessage returns a Message +func NewDeleteRoomMessage(root util.PKRoute, dest util.PKRoute) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = CmdMsgType + m.MsgSubtype = CmdMsgTypeDeleteRoom + m.Message = []byte("Room Deleted") + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} + +// NewRoomMembersMessage returns a Message of room members +func NewRoomMembersMessage(root util.PKRoute, dest util.PKRoute, members []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = InfoMsgType + m.MsgSubtype = InfoMsgTypeRoomMembers + m.Message = members + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} + +// NewRoomModsMessage returns a Message of room moderators +func NewRoomModsMessage(root util.PKRoute, dest util.PKRoute, moderators []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = InfoMsgType + m.MsgSubtype = InfoMsgTypeRoomMembers + m.Message = moderators + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} + +// NewRoomMutedMessage returns a Message of muted pks of room +func NewRoomMutedMessage(root util.PKRoute, dest util.PKRoute, muted []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = InfoMsgType + m.MsgSubtype = InfoMsgTypeRoomMuted + m.Message = muted + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} + +// NewMutePeerMessage returns a Message to mute a peer +func NewMutePeerMessage(root util.PKRoute, dest util.PKRoute, pk []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = CmdMsgType + m.MsgSubtype = CmdMsgTypeMutePeer + m.Message = pk + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} + +// NewUnmutePeerMessage returns a Message to mute a peer +func NewUnmutePeerMessage(root util.PKRoute, dest util.PKRoute, pk []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = CmdMsgType + m.MsgSubtype = CmdMsgTypeUnmutePeer + m.Message = pk + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} + +// NewHireModeratorMessage returns a Message to hire a peer as moderator +func NewHireModeratorMessage(root util.PKRoute, dest util.PKRoute, pk []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = CmdMsgType + m.MsgSubtype = CmdMsgTypeHireModerator + m.Message = pk + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} + +// NewFireModeratorMessage returns a Message to fire a moderator +func NewFireModeratorMessage(root util.PKRoute, dest util.PKRoute, pk []byte) Message { + m := Message{} + m.Origin = root.Visor + m.Root = root + m.Dest = dest + m.MsgType = CmdMsgType + m.MsgSubtype = CmdMsgTypeFireModerator + m.Message = pk + m.Status = MsgStatusInitial + m.Time = getUTCTimeStamp() + return m +} diff --git a/cmd/apps/skychat/internal/domain/message/message.go b/cmd/apps/skychat/internal/domain/message/message.go index 427b74437..5225b4057 100644 --- a/cmd/apps/skychat/internal/domain/message/message.go +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -146,6 +146,22 @@ func NewJSONMessage(m Message) JSONMessage { } } +// NewMessageFromJSON returns a Message from a JSONMessage +func NewMessageFromJSON(m JSONMessage) Message { + return Message{ + m.ID, + m.Origin, + m.Time, + m.Root, + m.Dest, + m.MsgType, + m.MsgSubtype, + []byte(m.Message), + m.Status, + m.Seen, + } +} + // NewRAWMessage return a RAWMessage from a message func NewRAWMessage(m Message) RAWMessage { @@ -197,229 +213,26 @@ func (m Message) MarshalJSON() ([]byte, error) { return json.Marshal(NewJSONMessage(m)) } -// NewTextMessage returns a Message -func NewTextMessage(pkOrigin cipher.PubKey, routeDestination util.PKRoute, msg []byte) Message { - m := Message{} - m.Origin = pkOrigin - m.Root = util.NewP2PRoute(pkOrigin) - m.Dest = routeDestination - m.MsgType = TxtMsgType - m.MsgSubtype = 0 - m.Message = msg - m.Status = MsgStatusInitial - m.Time = time.Now() - return m -} - -// NewRouteRequestMessage returns a request Message -func NewRouteRequestMessage(pkOrigin cipher.PubKey, routeDestination util.PKRoute) Message { - m := Message{} - m.Origin = pkOrigin - m.Root = util.NewP2PRoute(pkOrigin) - m.Dest = routeDestination - m.MsgType = ConnMsgType - m.MsgSubtype = ConnMsgTypeRequest - m.Message = []byte("Chat Request") - m.Status = MsgStatusInitial - m.Time = time.Now() - return m -} - -// NewChatAcceptMessage returns a chat accepted message -// pk is the users pk to set the messages root -func NewChatAcceptMessage(root util.PKRoute, dest util.PKRoute) Message { - m := Message{} - m.Origin = root.Visor - m.Root = root - m.Dest = dest - m.MsgType = ConnMsgType - m.MsgSubtype = ConnMsgTypeAccept - m.Status = MsgStatusInitial - m.Message = []byte("Chat Accepted") - m.Time = time.Now() - return m -} - -// NewChatRejectMessage returns new chat rejected message -func NewChatRejectMessage(root util.PKRoute, dest util.PKRoute) Message { - m := Message{} - m.Origin = root.Visor - m.Root = root - m.Dest = dest - m.MsgType = ConnMsgType - m.MsgSubtype = ConnMsgTypeReject - m.Message = []byte("Chat Rejected") - m.Status = MsgStatusInitial - m.Time = time.Now() - return m -} - -// NewChatLeaveMessage returns new chat leave message -func NewChatLeaveMessage(root util.PKRoute, dest util.PKRoute) Message { - m := Message{} - m.Origin = root.Visor - m.Root = root - m.Dest = dest - m.MsgType = ConnMsgType - m.MsgSubtype = ConnMsgTypeLeave - m.Message = []byte("Chat Left") - m.Status = MsgStatusInitial - m.Time = time.Now() - return m -} - -// NewRouteDeletedMessage returns new message to info about deleted route -func NewRouteDeletedMessage(route util.PKRoute, dest util.PKRoute) Message { - m := Message{} - m.Origin = route.Visor - m.Root = route - m.Dest = dest - m.MsgType = ConnMsgType - m.MsgSubtype = ConnMsgTypeDelete - m.Message = []byte("Chat Deleted") - m.Status = MsgStatusInitial - m.Time = time.Now() - return m -} - -// NewChatInfoMessage returns new chat info -func NewChatInfoMessage(root util.PKRoute, dest util.PKRoute, info []byte) Message { - m := Message{} - m.Origin = root.Visor - m.Root = root - m.Dest = dest - m.MsgType = InfoMsgType - m.MsgSubtype = InfoMsgTypeSingle - m.Message = info - m.Status = MsgStatusInitial - m.Time = time.Now() - return m -} - -// NewAddRoomMessage returns a Message -func NewAddRoomMessage(root util.PKRoute, dest util.PKRoute, info []byte) Message { - m := Message{} - m.Origin = root.Visor - m.Root = root - m.Dest = dest - m.MsgType = CmdMsgType - m.MsgSubtype = CmdMsgTypeAddRoom - m.Message = info - m.Status = MsgStatusInitial - m.Time = time.Now() - return m -} - -// NewDeleteRoomMessage returns a Message -func NewDeleteRoomMessage(root util.PKRoute, dest util.PKRoute) Message { - m := Message{} - m.Origin = root.Visor - m.Root = root - m.Dest = dest - m.MsgType = CmdMsgType - m.MsgSubtype = CmdMsgTypeDeleteRoom - m.Message = []byte("Room Deleted") - m.Status = MsgStatusInitial - m.Time = time.Now() - return m -} - -// NewRoomMembersMessage returns a Message of room members -func NewRoomMembersMessage(root util.PKRoute, dest util.PKRoute, members []byte) Message { - m := Message{} - m.Origin = root.Visor - m.Root = root - m.Dest = dest - m.MsgType = InfoMsgType - m.MsgSubtype = InfoMsgTypeRoomMembers - m.Message = members - m.Status = MsgStatusInitial - m.Time = time.Now() - return m -} - -// NewRoomModsMessage returns a Message of room moderators -func NewRoomModsMessage(root util.PKRoute, dest util.PKRoute, moderators []byte) Message { - m := Message{} - m.Origin = root.Visor - m.Root = root - m.Dest = dest - m.MsgType = InfoMsgType - m.MsgSubtype = InfoMsgTypeRoomMembers - m.Message = moderators - m.Status = MsgStatusInitial - m.Time = time.Now() - return m -} - -// NewRoomMutedMessage returns a Message of muted pks of room -func NewRoomMutedMessage(root util.PKRoute, dest util.PKRoute, muted []byte) Message { - m := Message{} - m.Origin = root.Visor - m.Root = root - m.Dest = dest - m.MsgType = InfoMsgType - m.MsgSubtype = InfoMsgTypeRoomMuted - m.Message = muted - m.Status = MsgStatusInitial - m.Time = time.Now() - return m -} - -// NewMutePeerMessage returns a Message to mute a peer -func NewMutePeerMessage(root util.PKRoute, dest util.PKRoute, pk []byte) Message { - m := Message{} - m.Origin = root.Visor - m.Root = root - m.Dest = dest - m.MsgType = CmdMsgType - m.MsgSubtype = CmdMsgTypeMutePeer - m.Message = pk - m.Status = MsgStatusInitial - m.Time = time.Now() - return m -} - -// NewUnmutePeerMessage returns a Message to mute a peer -func NewUnmutePeerMessage(root util.PKRoute, dest util.PKRoute, pk []byte) Message { - m := Message{} - m.Origin = root.Visor - m.Root = root - m.Dest = dest - m.MsgType = CmdMsgType - m.MsgSubtype = CmdMsgTypeUnmutePeer - m.Message = pk - m.Status = MsgStatusInitial - m.Time = time.Now() - return m -} +// UnmarshalJSON returns unmarshaled bytes and error +func (m *Message) UnmarshalJSON(b []byte) error { + jm := JSONMessage{} + err := json.Unmarshal(b, &jm) + if err != nil { + return err + } -// NewHireModeratorMessage returns a Message to hire a peer as moderator -func NewHireModeratorMessage(root util.PKRoute, dest util.PKRoute, pk []byte) Message { - m := Message{} - m.Origin = root.Visor - m.Root = root - m.Dest = dest - m.MsgType = CmdMsgType - m.MsgSubtype = CmdMsgTypeHireModerator - m.Message = pk - m.Status = MsgStatusInitial - m.Time = time.Now() - return m -} + m.ID = jm.ID + m.Origin = jm.Origin + m.Time = jm.Time + m.Root = jm.Root + m.Dest = jm.Dest + m.MsgType = jm.MsgType + m.MsgSubtype = jm.MsgSubtype + m.Message = []byte(jm.Message) + m.Status = jm.Status + m.Seen = jm.Seen -// NewFireModeratorMessage returns a Message to fire a moderator -func NewFireModeratorMessage(root util.PKRoute, dest util.PKRoute, pk []byte) Message { - m := Message{} - m.Origin = root.Visor - m.Root = root - m.Dest = dest - m.MsgType = CmdMsgType - m.MsgSubtype = CmdMsgTypeFireModerator - m.Message = pk - m.Status = MsgStatusInitial - m.Time = time.Now() - return m + return nil } // GetID returns message ID @@ -491,3 +304,44 @@ func (m *Message) GetSeen() bool { func (m *Message) SetStatus(status int) { m.Status = status } + +// IsFromRemoteP2PToLocalP2P returns if the message is a p2p message from remote to local +func (m *Message) IsFromRemoteP2PToLocalP2P(localPK cipher.PubKey) bool { + return m.GetDestinationVisor() == localPK && m.GetDestinationServer() == localPK && m.GetDestinationRoom() == localPK && m.GetRootVisor() == m.GetRootServer() && m.GetRootServer() == m.GetRootRoom() +} + +// IsFromLocalToRemoteP2P returns if the message is a p2p message from local to remote +func (m *Message) IsFromLocalToRemoteP2P() bool { + return m.GetDestinationVisor() == m.GetDestinationServer() +} + +// IsFromRemoteServer returns if the message is a message of a remote server +func (m *Message) IsFromRemoteServer() bool { + return m.GetRootVisor() != m.GetRootServer() && m.GetRootServer() != m.GetRootRoom() +} + +// IsFromRemoteToLocalServer returns if the message is a message sent to the local server +func (m *Message) IsFromRemoteToLocalServer(localPK cipher.PubKey) bool { + return m.GetDestinationVisor() == localPK && m.GetDestinationVisor() != m.GetDestinationServer() && m.GetDestinationServer() != m.GetDestinationRoom() +} + +// FmtPrint uses fmt.Print for beautiful representation of message +func (m *Message) FmtPrint(printMessageBytes bool) { + fmt.Println("---------------------------------------------------------------------------------------------------") + fmt.Printf("Message: \n") + fmt.Printf("ID: %d \n", m.ID) + fmt.Printf("Origin: %s \n", m.Origin) + fmt.Printf("Time: %s \n", m.Time) + fmt.Printf("Root: %s \n", m.Root.String()) + fmt.Printf("Dest: %s \n", m.Dest.String()) + fmt.Printf("MsgType: %d \n", m.MsgType) + fmt.Printf("MsgSubType: %d \n", m.MsgSubtype) + + if printMessageBytes { + fmt.Printf("Message: %s \n", string(m.Message)) + } + + fmt.Printf("Status: %d \n", m.Status) + fmt.Printf("Seen: %t \n", m.Seen) + fmt.Println("---------------------------------------------------------------------------------------------------") +} diff --git a/cmd/apps/skychat/internal/domain/peer/peerbook.go b/cmd/apps/skychat/internal/domain/peer/peerbook.go index c5c580f39..e3f3cde94 100644 --- a/cmd/apps/skychat/internal/domain/peer/peerbook.go +++ b/cmd/apps/skychat/internal/domain/peer/peerbook.go @@ -9,12 +9,12 @@ import ( // Peerbook contains a map of peers type Peerbook struct { - peers map[cipher.PubKey]Peer + Peers map[cipher.PubKey]Peer } // GetPeerByPK returns a peer from the peerbook if it is available func (pb *Peerbook) GetPeerByPK(pk cipher.PubKey) (*Peer, error) { - if p, ok := pb.peers[pk]; ok { + if p, ok := pb.Peers[pk]; ok { return &p, nil } return nil, fmt.Errorf("peer not found") @@ -22,16 +22,16 @@ func (pb *Peerbook) GetPeerByPK(pk cipher.PubKey) (*Peer, error) { // SetPeer updates or adds the given peer in the peerbook func (pb *Peerbook) SetPeer(p Peer) { - pb.peers[p.GetPK()] = p + pb.Peers[p.GetPK()] = p } // DeletePeer deletes the given peer from the peerbook func (pb *Peerbook) DeletePeer(pk cipher.PubKey) { - delete(pb.peers, pk) + delete(pb.Peers, pk) } // AddPeer adds a new peer to the peerbook func (pb *Peerbook) AddPeer(i info.Info, alias string) { p := NewPeer(i, alias) - pb.peers[i.GetPK()] = *p + pb.Peers[i.GetPK()] = *p } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index 8b855af9a..f58564cf8 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -15,7 +15,6 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" @@ -36,10 +35,6 @@ type MessengerService struct { func NewMessengerService(ns notification.Service, cR client.Repository, uR user.Repository, chR chat.Repository) *MessengerService { ms := MessengerService{} - /*ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - ms.ctx = ctx*/ ms.ns = ns ms.cliRepo = cR ms.usrRepo = uR @@ -50,187 +45,187 @@ func NewMessengerService(ns notification.Service, cR client.Repository, uR user. return &ms } -// Handle handles the visor connection and incoming messages -func (ms MessengerService) Handle(pk cipher.PubKey) { - errs := ms.errs +// readMessageLengthFromConnection reads a prefix message of the connection to get the length of the upcoming message +func readMessageLengthFromConnection(conn net.Conn) (*uint32, error) { + prefixMessage := make([]byte, 4) + _, err := io.ReadFull(conn, prefixMessage) + if err != nil { + return nil, err + } + messageLength := binary.BigEndian.Uint32(prefixMessage) + return &messageLength, nil +} - pCli, err := ms.cliRepo.GetClient() +func writeMessageLengthPrefixToConnection(message []byte, conn net.Conn) error { + prefix := make([]byte, 4) + binary.BigEndian.PutUint32(prefix, uint32(len(message))) + fmt.Printf("Write prefix with %d Bytes to Conn: %s \n", len(prefix), conn.LocalAddr()) + _, err := conn.Write(prefix) if err != nil { - errs <- err - return + return fmt.Errorf("failed to write prefix: %v ", err) } + return nil +} + +// readNBytesFromConnection reads n bytes from the given connection if a max. packetSize of 1024 +func readNBytesFromConnection(n uint32, conn net.Conn) ([]byte, error) { + packetBuffer := make([]byte, 1024) - conn := pCli.GetConns()[pk] + receivedBytes := make([]byte, 0) + recievedBytesCounter := 0 + for recievedBytesCounter = 0; recievedBytesCounter < int(n); { + packetSize, err := conn.Read(packetBuffer) + if err != nil { + if err != io.EOF { + fmt.Printf("Read error - %s\n", err) + return nil, err + } + break + } + receivedBytes = append(receivedBytes, packetBuffer[:packetSize]...) + recievedBytesCounter += packetSize + fmt.Printf("Data: %d/%d (PacketSize: %d) \n", recievedBytesCounter, n, packetSize) + } + fmt.Printf("Received %d bytes \n", recievedBytesCounter) - localPK := pCli.GetAppClient().Config().VisorPK + return receivedBytes, nil +} - buf := make([]byte, 1024) +// HandleConnection handles the connection to the given Pubkey and incoming messages +func (ms MessengerService) HandleConnection(pk cipher.PubKey) { + + chatClient, err := ms.cliRepo.GetClient() + if err != nil { + ms.errs <- err + return + } + + connection, err := chatClient.GetConnByPK(pk) + if err != nil { + ms.errs <- err + return + } for { - // read the length prefix - prefix := make([]byte, 4) - _, err = io.ReadFull(conn, prefix) + + messageLength, err := readMessageLengthFromConnection(connection) if err != nil { - fmt.Printf("Error Prefix: %s", err) - errs <- err - return + ms.errs <- err + continue } - lengthFromPrefix := binary.BigEndian.Uint32(prefix) - fmt.Printf("Prefix length: %d \n", lengthFromPrefix) - - data := make([]byte, 0) - length := 0 - for length = 0; length < int(lengthFromPrefix); { - //read packets - n, err := conn.Read(buf) - if err != nil { - // log if not normal error - if err != io.EOF { - fmt.Printf("Read error - %s\n", err) - } - break - } - // append read data to full data - data = append(data, buf[:n]...) - - // update total read var - length += n - fmt.Printf("Data: %d/%d (PacketSize: %d) \n", length, lengthFromPrefix, n) + messageBytes, err := readNBytesFromConnection(*messageLength, connection) + if err != nil { + ms.errs <- err + continue } - fmt.Printf("Received %d bytes \n", length) - /* - if err != nil { - fmt.Println("Failed to read packet:", err) - //close and delete connection - //? close connection ? - err2 := pCli.DeleteConn(conn.RemoteAddr().(appnet.Addr).PubKey) - if err2 != nil { - errs <- err2 - return - } - errs <- err - return - }*/ - - //unmarshal the received bytes to a message.Message - m := message.RAWMessage{} - fmt.Println("---------------------------------------------------------------------------------------------------") - fmt.Println("New Raw Message") - fmt.Println("---------------------------------------------------------------------------------------------------") + receivedMessage, err := decodeReceivedBytesToMessage(messageBytes) + if err != nil { + ms.errs <- err + continue + } - err = json.Unmarshal(data, &m) + err = ms.handleReceivedMessage(*receivedMessage) if err != nil { - fmt.Printf("Failed to unmarshal json message: %v \n", err) - } else { - jm := message.NewMessage(m) - fmt.Println("---------------------------------------------------------------------------------------------------") - fmt.Printf("Message: \n") - fmt.Printf("ID: %d \n", jm.ID) - fmt.Printf("Origin: %s \n", jm.Origin) - fmt.Printf("Time: %s \n", jm.Time) - fmt.Printf("Root: %s \n", jm.Root.String()) - fmt.Printf("Dest: %s \n", jm.Dest.String()) - fmt.Printf("MsgType: %d \n", jm.MsgType) - fmt.Printf("MsgSubType: %d \n", jm.MsgSubtype) - //fmt.Printf("Message: %s \n", string(jm.Message)) - fmt.Printf("Status: %d \n", jm.Status) - fmt.Printf("Seen: %t \n", jm.Seen) - fmt.Println("---------------------------------------------------------------------------------------------------") - - if jm.GetDestinationVisor() == localPK && jm.GetDestinationServer() == localPK && jm.GetDestinationRoom() == localPK && jm.GetRootVisor() == jm.GetRootServer() && jm.GetRootServer() == jm.GetRootRoom() { - go ms.handleP2PMessage(jm) - } else if jm.GetRootVisor() != jm.GetRootServer() && jm.GetRootServer() != jm.GetRootRoom() { - go ms.handleRemoteServerMessage(jm) - } else if jm.GetDestinationVisor() == localPK && jm.GetDestinationVisor() != jm.GetDestinationServer() && jm.GetDestinationServer() != jm.GetDestinationRoom() { - go ms.handleLocalServerMessage(jm) - } else { - fmt.Println("received message that can't be matched to remote or local server or p2p chat") - } - if err != nil { - fmt.Println(err) - continue - } + ms.errs <- err + continue } + } +} + +// handleReceivedMessage handles a received message +func (ms MessengerService) handleReceivedMessage(receivedMessage message.Message) error { + chatClient, err := ms.cliRepo.GetClient() + if err != nil { + return err + } + + localPK := chatClient.GetAppClient().Config().VisorPK + + if receivedMessage.IsFromRemoteP2PToLocalP2P(localPK) { + go ms.handleP2PMessage(receivedMessage) + } else if receivedMessage.IsFromRemoteServer() { + go ms.handleRemoteServerMessage(receivedMessage) + } else if receivedMessage.IsFromRemoteToLocalServer(localPK) { + go ms.handleLocalServerMessage(receivedMessage) + } else { + return fmt.Errorf("received message that can't be matched to remote server, local server or p2p chat") + } + return nil +} +// decodeReceivedBytesToMessage decodes the given bytes to a message.Message +func decodeReceivedBytesToMessage(messageBytes []byte) (*message.Message, error) { + receivedRawMessage := message.RAWMessage{} + err := json.Unmarshal(messageBytes, &receivedRawMessage) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal json message: %v ", err) } + + receivedMessage := message.NewMessage(receivedRawMessage) + receivedMessage.FmtPrint(false) + return &receivedMessage, nil } -// Dial dials the remote chat -func (ms MessengerService) Dial(pk cipher.PubKey) (net.Conn, error) { +// DialPubKey dials the remote chat +func (ms MessengerService) DialPubKey(pk cipher.PubKey) (net.Conn, error) { - pCli, err := ms.cliRepo.GetClient() + chatClient, err := ms.cliRepo.GetClient() if err != nil { - fmt.Printf("Error Getting client") return nil, err } - conn, err := pCli.GetConnByPK(pk) + conn, err := chatClient.GetConnByPK(pk) if err == nil { - //? is this necessary - fmt.Printf("Connection already available, so delete old connection \n") - err = conn.Close() - if err != nil { - return nil, err - } - err = pCli.DeleteConn(pk) - if err != nil { - return nil, err - } - //save client in repo - err = ms.cliRepo.SetClient(*pCli) - if err != nil { - fmt.Println(err) - } + return conn, nil } addr := appnet.Addr{ - Net: pCli.GetNetType(), + Net: chatClient.GetNetType(), PubKey: pk, - Port: pCli.GetPort(), + Port: chatClient.GetPort(), } - var r = netutil.NewRetrier(pCli.GetLog(), 50*time.Millisecond, netutil.DefaultMaxBackoff, 2, 2) - + var r = netutil.NewRetrier(chatClient.GetLog(), 50*time.Millisecond, netutil.DefaultMaxBackoff, 2, 2) ctx, cancel := context.WithCancel(context.Background()) defer cancel() - ms.ctx = ctx - err = r.Do(ms.ctx, func() error { - //? notify that dialing is happening? - //? How about not deleting the visor, but saving the failed dials as a message so the user can see that something is happening. - conn, err = pCli.GetAppClient().Dial(addr) - //could not find a valid connection to a chat, so delete it. - err2 := ms.visorRepo.Delete(pk) - if err2 != nil { - return err2 - } + //TODO: notify that dialing is happening, and even notify failed attempts? + conn, err = chatClient.GetAppClient().Dial(addr) return err }) - if err != nil { return nil, err } - //save connection in pCli - err = pCli.AddConn(pk, conn) + err = chatClient.AddConn(pk, conn) if err != nil { return nil, err } - //save client in repo - err = ms.cliRepo.SetClient(*pCli) + + err = ms.cliRepo.SetClient(*chatClient) if err != nil { - fmt.Println(err) + return nil, err } return conn, nil } +// sendMessageAndSaveItToDatabase sends a message and saves it to the database +func (ms MessengerService) sendMessageAndSaveItToDatabase(pkroute util.PKRoute, m message.Message) error { + return ms.sendMessage(pkroute, m, true) +} + +// sendMessageAndDontSaveItToDatabase sends a message but doesn't save it to the database +func (ms MessengerService) sendMessageAndDontSaveItToDatabase(pkroute util.PKRoute, m message.Message) error { + return ms.sendMessage(pkroute, m, false) +} + // sendMessage sends a message to the given route func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, addToDatabase bool) error { - //check if visor exists + v, err := ms.visorRepo.GetByPK(pkroute.Visor) if err != nil { var v2 chat.Visor @@ -288,62 +283,38 @@ func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, } - pCli, err := ms.cliRepo.GetClient() + chatClient, err := ms.cliRepo.GetClient() if err != nil { - fmt.Printf("Error Getting client") return err } - fmt.Println("---------------------------------------------------------------------------------------------------") - fmt.Println("Sending Message:") - fmt.Printf("%s \n", pkroute.String()) - fmt.Println("---------------------------------------------------------------------------------------------------") - fmt.Printf("Message: \n") - fmt.Printf("ID: %d \n", m.ID) - fmt.Printf("Origin: %s \n", m.Origin) - fmt.Printf("Time: %s \n", m.Time) - fmt.Printf("Root: %s \n", m.Root.String()) - fmt.Printf("Dest: %s \n", m.Dest.String()) - fmt.Printf("MsgType: %d \n", m.MsgType) - fmt.Printf("MsgSubType: %d \n", m.MsgSubtype) - //fmt.Printf("Message: %s \n", string(m.Message)) - fmt.Printf("Status: %d \n", m.Status) - fmt.Printf("Seen: %t \n", m.Seen) - fmt.Println("---------------------------------------------------------------------------------------------------") - //fmt.Printf("Message Size: %T, %d\n", m, unsafe.Sizeof(m)) - fmt.Println("---------------------------------------------------------------------------------------------------") + m.FmtPrint(false) rm := message.NewRAWMessage(m) bytes, err := json.Marshal(rm) if err != nil { - fmt.Printf("Failed to marshal json: %v", err) + return fmt.Errorf("failed to marshal json: %v ", err) } - //Get connection from remote/destination visor of message - conn, err := pCli.GetConnByPK(m.Dest.Visor) + conn, err := chatClient.GetConnByPK(m.Dest.Visor) if err != nil { - conn, err = ms.Dial(m.Dest.Visor) + conn, err = ms.DialPubKey(m.Dest.Visor) if err != nil { return err } } - // create the length prefix - prefix := make([]byte, 4) - binary.BigEndian.PutUint32(prefix, uint32(len(bytes))) - fmt.Printf("Write prefix with %d Bytes to Conn: %s \n", len(prefix), conn.LocalAddr()) - _, err = conn.Write(prefix) + err = writeMessageLengthPrefixToConnection(bytes, conn) if err != nil { - fmt.Printf("Failed to write prefix: %v \n", err) - return err + fmt.Printf("Failed to write message length") } fmt.Printf("Write %d Bytes to Conn: %s \n", len(bytes), conn.LocalAddr()) _, err = conn.Write(bytes) if err != nil { - fmt.Printf("Failed to write bytes: %v \n", err) - return err + return fmt.Errorf("failed to write bytes: %v", err) + } if addToDatabase { @@ -353,296 +324,27 @@ func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, return err } } - return nil } -// sendMessageNirvana sends a message to the given route without saving it somewhere -func (ms MessengerService) sendMessageNirvana(route util.PKRoute, m message.Message) error { - - pCli, err := ms.cliRepo.GetClient() - if err != nil { - return err - } - - m.Dest = route - - bytes, err := json.Marshal(m) - if err != nil { - fmt.Printf("Failed to marshal json: %v", err) - } - - conn := pCli.GetConns()[route.Visor] - if conn == nil { - conn, err = ms.Dial(route.Visor) - if err != nil { - return err - } - } - - _, err = conn.Write(bytes) - if err != nil { - return err - } - - return nil -} - -// SendRouteRequestMessage sends a request message to join the specified route -// if route.Visor == route.Server == route.Room -> P2P request -// if route.Visor + route.Server == route.Room -> ServerJoinRequest -// if route.Visor + route.Server + route.Room -> RoomRequest -func (ms MessengerService) SendRouteRequestMessage(route util.PKRoute) error { - - usr, err := ms.usrRepo.GetUser() - if err != nil { - fmt.Printf("Error getting user from repository: %s", err) - return err - } - - m := message.NewRouteRequestMessage(usr.GetInfo().GetPK(), route) - - err = ms.sendMessage(route, m, true) - if err != nil { - return err - } - - //notify about the added route - an := notification.NewAddRouteNotification(route) - err = ms.ns.Notify(an) - if err != nil { - return err - } - return nil -} - -// SendTextMessage sends a text message to the given route -func (ms MessengerService) SendTextMessage(route util.PKRoute, msg []byte) error { - - usr, err := ms.usrRepo.GetUser() - if err != nil { - fmt.Printf("Error getting user from repository: %s", err) - return err - } - - m := message.NewTextMessage(usr.GetInfo().GetPK(), route, msg) - - if m.Dest.Visor == usr.GetInfo().GetPK() { - err = ms.sendMessageToLocalRoute(m) - if err != nil { - return err - } - } else { - err = ms.sendMessageToRemoteRoute(m) - if err != nil { - return err - } - } - - return nil -} - -// SendAddRoomMessage sends a command message to add a room to the given route -func (ms MessengerService) SendAddRoomMessage(route util.PKRoute, info info.Info) error { - usr, err := ms.usrRepo.GetUser() - if err != nil { - fmt.Printf("Error getting user from repository: %s", err) - return err - } - - bytes, err := json.Marshal(info) - if err != nil { - fmt.Printf("Failed to marshal json: %v", err) - return err - } - - root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) - - m := message.NewAddRoomMessage(root, route, bytes) - - if m.Dest.Visor == usr.GetInfo().GetPK() { - err = ms.sendMessageToLocalRoute(m) - if err != nil { - return err - } - } else { - err = ms.sendMessageToRemoteRoute(m) - if err != nil { - return err - } - } - - return nil -} - -// SendDeleteRoomMessage sends a command message to delete a room of the given route -func (ms MessengerService) SendDeleteRoomMessage(route util.PKRoute) error { - usr, err := ms.usrRepo.GetUser() - if err != nil { - fmt.Printf("Error getting user from repository: %s", err) - return err - } - - root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) - - m := message.NewDeleteRoomMessage(root, route) - - if m.Dest.Visor == usr.GetInfo().GetPK() { - err = ms.sendMessageToLocalRoute(m) - if err != nil { - return err - } - } else { - err = ms.sendMessageToRemoteRoute(m) - if err != nil { - return err - } - } - - return nil -} - -// SendMutePeerMessage sends a command message to mute a peer in the given route -func (ms MessengerService) SendMutePeerMessage(pkroute util.PKRoute, pk cipher.PubKey) error { - usr, err := ms.usrRepo.GetUser() - if err != nil { - fmt.Printf("Error getting user from repository: %s", err) - return err - } - - bytes, err := json.Marshal(pk) - if err != nil { - fmt.Printf("Failed to marshal json: %v", err) - return err - } - - root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) - - msg := message.NewMutePeerMessage(root, pkroute, bytes) - - if msg.Dest.Visor == usr.GetInfo().GetPK() { - err = ms.sendMessageToLocalRoute(msg) - if err != nil { - return err - } - } else { - err = ms.sendMessageToRemoteRoute(msg) - if err != nil { - return err - } - } - return nil -} - -// SendUnmutePeerMessage sends a command message to unmute a peer in the given route -func (ms MessengerService) SendUnmutePeerMessage(pkroute util.PKRoute, pk cipher.PubKey) error { - usr, err := ms.usrRepo.GetUser() - if err != nil { - fmt.Printf("Error getting user from repository: %s", err) - return err - } - - bytes, err := json.Marshal(pk) - if err != nil { - fmt.Printf("Failed to marshal json: %v", err) - return err - } - - root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) - - msg := message.NewUnmutePeerMessage(root, pkroute, bytes) - - if msg.Dest.Visor == usr.GetInfo().GetPK() { - err = ms.sendMessageToLocalRoute(msg) - if err != nil { - return err - } - } else { - err = ms.sendMessageToRemoteRoute(msg) - if err != nil { - return err - } - } - return nil -} - -// SendHireModeratorMessage sends a command message to hire a peer as moderator -func (ms MessengerService) SendHireModeratorMessage(pkroute util.PKRoute, pk cipher.PubKey) error { - usr, err := ms.usrRepo.GetUser() - if err != nil { - fmt.Printf("Error getting user from repository: %s", err) - return err - } - - bytes, err := json.Marshal(pk) - if err != nil { - fmt.Printf("Failed to marshal json: %v", err) - return err - } - - root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) - - msg := message.NewHireModeratorMessage(root, pkroute, bytes) - - if msg.Dest.Visor == usr.GetInfo().GetPK() { - err = ms.sendMessageToLocalRoute(msg) - if err != nil { - return err - } - } else { - err = ms.sendMessageToRemoteRoute(msg) - if err != nil { - return err - } - } - return nil -} - -// SendFireModeratorMessage sends a command message to fire a moderator -func (ms MessengerService) SendFireModeratorMessage(pkroute util.PKRoute, pk cipher.PubKey) error { - usr, err := ms.usrRepo.GetUser() - if err != nil { - fmt.Printf("Error getting user from repository: %s", err) - return err - } - - bytes, err := json.Marshal(pk) - if err != nil { - fmt.Printf("Failed to marshal json: %v", err) - return err - } - - root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) - - msg := message.NewFireModeratorMessage(root, pkroute, bytes) - - if msg.Dest.Visor == usr.GetInfo().GetPK() { - err = ms.sendMessageToLocalRoute(msg) +// sendMessageToRemoteRoute sends the given message to a remote route (as p2p and client) +func (ms MessengerService) sendMessageToRemoteRoute(msg message.Message) error { + //if the message goes to p2p we save it in database, if not we wait for the remote server to send us our message + //this way we can see that the message was received by the remote server + if msg.IsFromLocalToRemoteP2P() { + err := ms.sendMessageAndSaveItToDatabase(msg.Dest, msg) if err != nil { return err } } else { - err = ms.sendMessageToRemoteRoute(msg) + err := ms.sendMessageAndDontSaveItToDatabase(msg.Dest, msg) if err != nil { return err } } - return nil -} -// sendMessageToRemoteRoute sends the given message to a remote route (as p2p and client) -func (ms MessengerService) sendMessageToRemoteRoute(msg message.Message) error { - //if the message goes to p2p we save it in database, if not we wait for the remote server to send us our message - //this way we can see that the message was received by the remote server - saveInDatabase := (msg.Dest.Visor == msg.Dest.Server) - err := ms.sendMessage(msg.Dest, msg, saveInDatabase) - if err != nil { - return err - } - - //notify about sent text message n := notification.NewMsgNotification(msg.Dest, msg) - err = ms.ns.Notify(n) + err := ms.ns.Notify(n) if err != nil { return err } @@ -653,107 +355,34 @@ func (ms MessengerService) sendMessageToRemoteRoute(msg message.Message) error { // sendMessageToLocalRoute "sends" the message to local server, so local server handles it, as it was sent from a remote route (used for messages send from server host, but as client) func (ms MessengerService) sendMessageToLocalRoute(msg message.Message) error { go ms.handleLocalServerMessage(msg) - //notification is handled inside handleServerMessage return nil } -// SendInfoMessage sends an info message to the given chat and notifies about sent message -func (ms MessengerService) SendInfoMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute, info info.Info) error { - usr, err := ms.usrRepo.GetUser() - if err != nil { - fmt.Printf("Error getting user from repository: %s", err) - return err - } - - bytes, err := json.Marshal(info) - if err != nil { - fmt.Printf("Failed to marshal json: %v", err) - return err - } - - m := message.NewChatInfoMessage(root, dest, bytes) - - //send info to local route (we as host are a member also and have to update our info inside the server) - if m.Dest.Visor == usr.GetInfo().GetPK() { - err = ms.sendMessageToLocalRoute(m) - if err != nil { - return err - } - } else if pkroute.Visor != usr.GetInfo().GetPK() { - //Send info to a remote route (as peer and as client) - err = ms.sendMessageToRemoteRoute(m) - if err != nil { - return err - } - } - - return nil - -} - -// SendChatAcceptMessage sends an accept-message from the root to the destination -func (ms MessengerService) SendChatAcceptMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute) error { - m := message.NewChatAcceptMessage(root, dest) - err := ms.sendMessage(pkroute, m, true) - if err != nil { - return err - } - return nil -} - -// SendChatRejectMessage sends an reject-message from the root to the destination -func (ms MessengerService) SendChatRejectMessage(root util.PKRoute, dest util.PKRoute) error { - m := message.NewChatRejectMessage(root, dest) - err := ms.sendMessageNirvana(dest, m) - if err != nil { - return err - } - return nil -} - -// SendLeaveRouteMessage sends a leave-message from the root to the destination -func (ms MessengerService) SendLeaveRouteMessage(pkroute util.PKRoute) error { - usr, err := ms.usrRepo.GetUser() - if err != nil { - fmt.Printf("Error getting user from repository: %s", err) - return err - } - - root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) - - m := message.NewChatLeaveMessage(root, pkroute) - err = ms.sendMessage(pkroute, m, true) - if err != nil { - return err - } - return nil -} - -// Listen is used to listen for new incoming connections and pass them to the connection_handle routine +// Listen is used to listen for new incoming connections and pass them to the HandleConnection routine func (ms MessengerService) Listen() { - pCli, err := ms.cliRepo.GetClient() + chatClient, err := ms.cliRepo.GetClient() if err != nil { - fmt.Printf("Error getting client from repository: %s", err) + fmt.Printf("error getting client from repository: %s", err) } - l, err := pCli.GetAppClient().Listen(pCli.GetNetType(), pCli.GetPort()) + listener, err := chatClient.GetAppClient().Listen(chatClient.GetNetType(), chatClient.GetPort()) if err != nil { - fmt.Printf("Error listening network %v on port %d: %v\n", pCli.GetNetType(), pCli.GetPort(), err) + fmt.Printf("Error listening network %v on port %d: %v\n", chatClient.GetNetType(), chatClient.GetPort(), err) return } - pCli.SetAppPort(pCli.GetAppClient(), pCli.GetPort()) + chatClient.SetAppPort(chatClient.GetAppClient(), chatClient.GetPort()) go func() { if err := <-ms.errs; err != nil { - fmt.Printf("Error in go handle function: %s ", err) + fmt.Printf("Error in go HandleConnection function: %s ", err) } }() for { fmt.Println("Accepting skychat conn...") - conn, err := l.Accept() + conn, err := listener.Accept() if err != nil { fmt.Println("Failed to accept conn:", err) return @@ -763,18 +392,17 @@ func (ms MessengerService) Listen() { fmt.Printf("Accepted skychat conn on %s from %s\n", conn.LocalAddr(), raddr.PubKey) - //add connection to active connections of client - err = pCli.AddConn(raddr.PubKey, conn) + err = chatClient.AddConn(raddr.PubKey, conn) if err != nil { fmt.Println(err) } - err = ms.cliRepo.SetClient(*pCli) + err = ms.cliRepo.SetClient(*chatClient) if err != nil { fmt.Println(err) } //error handling in anonymous go func above - go ms.Handle(raddr.PubKey) + go ms.HandleConnection(raddr.PubKey) } } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go index 06120127b..aa7d52c78 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go @@ -769,8 +769,7 @@ func (ms MessengerService) sendMessageToPeers(v *chat.Visor, pkroute util.PKRout m.Root = pkroute m.Dest = util.NewP2PRoute(peer.GetPK()) - //send message to the peer, but don't save it again in database - err := ms.sendMessage(pkroute, m, false) + err := ms.sendMessageAndDontSaveItToDatabase(pkroute, m) if err != nil { fmt.Printf("error sending group message to peer: %v", err) continue @@ -790,7 +789,7 @@ func (ms MessengerService) sendLocalRouteInfoToPeer(pkroute util.PKRoute, dest u m := message.NewChatInfoMessage(pkroute, dest, bytes) - err = ms.sendMessage(pkroute, m, true) + err = ms.sendMessageAndSaveItToDatabase(pkroute, m) if err != nil { return err } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_send_messages.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_send_messages.go new file mode 100644 index 000000000..491dae232 --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_send_messages.go @@ -0,0 +1,326 @@ +package netcon + +import ( + "encoding/json" + "fmt" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// SendRouteRequestMessage sends a request message to join the specified route +// if route.Visor == route.Server == route.Room -> P2P request +// if route.Visor + route.Server == route.Room -> ServerJoinRequest +// if route.Visor + route.Server + route.Room -> RoomRequest +func (ms MessengerService) SendRouteRequestMessage(route util.PKRoute) error { + + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + m := message.NewRouteRequestMessage(usr.GetInfo().GetPK(), route) + + err = ms.sendMessageAndSaveItToDatabase(route, m) + if err != nil { + return err + } + + //notify about the added route + an := notification.NewAddRouteNotification(route) + err = ms.ns.Notify(an) + if err != nil { + return err + } + return nil +} + +// SendTextMessage sends a text message to the given route +func (ms MessengerService) SendTextMessage(route util.PKRoute, msg []byte) error { + + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + m := message.NewTextMessage(usr.GetInfo().GetPK(), route, msg) + + if m.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(m) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(m) + if err != nil { + return err + } + } + + return nil +} + +// SendAddRoomMessage sends a command message to add a room to the given route +func (ms MessengerService) SendAddRoomMessage(route util.PKRoute, info info.Info) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + bytes, err := json.Marshal(info) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) + + m := message.NewAddRoomMessage(root, route, bytes) + + if m.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(m) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(m) + if err != nil { + return err + } + } + + return nil +} + +// SendDeleteRoomMessage sends a command message to delete a room of the given route +func (ms MessengerService) SendDeleteRoomMessage(route util.PKRoute) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) + + m := message.NewDeleteRoomMessage(root, route) + + if m.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(m) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(m) + if err != nil { + return err + } + } + + return nil +} + +// SendMutePeerMessage sends a command message to mute a peer in the given route +func (ms MessengerService) SendMutePeerMessage(pkroute util.PKRoute, pk cipher.PubKey) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + bytes, err := json.Marshal(pk) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) + + msg := message.NewMutePeerMessage(root, pkroute, bytes) + + if msg.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(msg) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(msg) + if err != nil { + return err + } + } + return nil +} + +// SendUnmutePeerMessage sends a command message to unmute a peer in the given route +func (ms MessengerService) SendUnmutePeerMessage(pkroute util.PKRoute, pk cipher.PubKey) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + bytes, err := json.Marshal(pk) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) + + msg := message.NewUnmutePeerMessage(root, pkroute, bytes) + + if msg.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(msg) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(msg) + if err != nil { + return err + } + } + return nil +} + +// SendHireModeratorMessage sends a command message to hire a peer as moderator +func (ms MessengerService) SendHireModeratorMessage(pkroute util.PKRoute, pk cipher.PubKey) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + bytes, err := json.Marshal(pk) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) + + msg := message.NewHireModeratorMessage(root, pkroute, bytes) + + if msg.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(msg) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(msg) + if err != nil { + return err + } + } + return nil +} + +// SendFireModeratorMessage sends a command message to fire a moderator +func (ms MessengerService) SendFireModeratorMessage(pkroute util.PKRoute, pk cipher.PubKey) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + bytes, err := json.Marshal(pk) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + root := util.NewVisorOnlyRoute(usr.GetInfo().GetPK()) + + msg := message.NewFireModeratorMessage(root, pkroute, bytes) + + if msg.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(msg) + if err != nil { + return err + } + } else { + err = ms.sendMessageToRemoteRoute(msg) + if err != nil { + return err + } + } + return nil +} + +// SendInfoMessage sends an info message to the given chat and notifies about sent message +func (ms MessengerService) SendInfoMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute, info info.Info) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + bytes, err := json.Marshal(info) + if err != nil { + fmt.Printf("Failed to marshal json: %v", err) + return err + } + + m := message.NewChatInfoMessage(root, dest, bytes) + + //send info to local route (we as host are a member also and have to update our info inside the server) + if m.Dest.Visor == usr.GetInfo().GetPK() { + err = ms.sendMessageToLocalRoute(m) + if err != nil { + return err + } + } else if pkroute.Visor != usr.GetInfo().GetPK() { + //Send info to a remote route (as peer and as client) + err = ms.sendMessageToRemoteRoute(m) + if err != nil { + return err + } + } + + return nil + +} + +// SendChatAcceptMessage sends an accept-message from the root to the destination +func (ms MessengerService) SendChatAcceptMessage(pkroute util.PKRoute, root util.PKRoute, dest util.PKRoute) error { + m := message.NewChatAcceptMessage(root, dest) + err := ms.sendMessageAndSaveItToDatabase(pkroute, m) + if err != nil { + return err + } + return nil +} + +// SendChatRejectMessage sends an reject-message from the root to the destination +func (ms MessengerService) SendChatRejectMessage(root util.PKRoute, dest util.PKRoute) error { + m := message.NewChatRejectMessage(root, dest) + err := ms.sendMessageAndDontSaveItToDatabase(dest, m) + if err != nil { + return err + } + return nil +} + +// SendLeaveRouteMessage sends a leave-message from the root to the destination +func (ms MessengerService) SendLeaveRouteMessage(pkroute util.PKRoute) error { + usr, err := ms.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + return err + } + + root := util.NewP2PRoute(usr.GetInfo().GetPK()) + + m := message.NewChatLeaveMessage(root, pkroute) + err = ms.sendMessageAndSaveItToDatabase(pkroute, m) + if err != nil { + return err + } + return nil +} From 81bb6a0cd35282879d9f3c8b1d0a2f7679e703e7 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Sat, 10 Jun 2023 17:25:04 +0200 Subject: [PATCH 48/72] refactoring for better readability --- .../app/chat/commands/add_local_server.go | 142 ++++++++++++------ ...ator.go => send_fire_moderator_message.go} | 0 ...ator.go => send_hire_moderator_message.go} | 0 .../get_all_messages_from_room_by_route.go | 55 ++++--- .../app/chat/queries/get_all_visors.go | 14 +- .../app/chat/queries/get_room_by_route.go | 72 ++++++--- .../app/chat/queries/get_server_by_route.go | 15 +- .../app/chat/queries/get_visor_by_pk.go | 7 +- .../skychat/internal/domain/chat/visor.go | 27 ++++ .../internal/domain/util/default_pkroutes.go | 67 +++++++++ .../skychat/internal/domain/util/pkroute.go | 63 -------- .../skychat/internal/inputports/cli/root.go | 4 +- 12 files changed, 303 insertions(+), 163 deletions(-) rename cmd/apps/skychat/internal/app/chat/commands/{send_fire_moderator.go => send_fire_moderator_message.go} (100%) rename cmd/apps/skychat/internal/app/chat/commands/{send_hire_moderator.go => send_hire_moderator_message.go} (100%) create mode 100644 cmd/apps/skychat/internal/domain/util/default_pkroutes.go diff --git a/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go b/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go index 8ca933a50..13b5ea0e3 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go +++ b/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go @@ -1,7 +1,8 @@ -// Package commands contains commands to add a local server +// Package commands containotifService commands to add a local server package commands import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" @@ -21,91 +22,136 @@ type AddLocalServerRequestHandler interface { } type addLocalServerRequestHandler struct { - visorRepo chat.Repository - userRepo user.Repository - ns notification.Service + visorRepo chat.Repository + userRepo user.Repository + notifService notification.Service } // NewAddLocalServerRequestHandler Initializes an AddCommandHandler -func NewAddLocalServerRequestHandler(visorRepo chat.Repository, userRepo user.Repository, ns notification.Service) AddLocalServerRequestHandler { - return addLocalServerRequestHandler{visorRepo: visorRepo, userRepo: userRepo, ns: ns} +func NewAddLocalServerRequestHandler(visorRepo chat.Repository, userRepo user.Repository, notifService notification.Service) AddLocalServerRequestHandler { + return addLocalServerRequestHandler{visorRepo: visorRepo, userRepo: userRepo, notifService: notifService} } // Handle Handles the AddLocalServerRequest func (h addLocalServerRequestHandler) Handle(command AddLocalServerRequest) error { - //Get user - usr, err := h.userRepo.GetUser() + + visor, err := h.getLocalVisorOrAddIfNotExists() if err != nil { return err } - // Check if local visor exists, if not add the default local visor - var visor chat.Visor - pVisor, err := h.visorRepo.GetByPK(usr.GetInfo().GetPK()) + server, err := h.getNewServer(visor, command) if err != nil { - visor = chat.NewUndefinedVisor(usr.GetInfo().GetPK()) - err = h.visorRepo.Add(visor) - if err != nil { - return err - } - } else { - visor = *pVisor + return err } - visorBoolMap := visor.GetAllServerBoolMap() - - route := util.NewLocalServerRoute(visor.GetPK(), visorBoolMap) - server, err := chat.NewLocalServer(route, command.Info) + room, err := h.getNewRoom(server, command) if err != nil { return err } - //setup room - roomBoolMap := server.GetAllRoomsBoolMap() - roomRoute := util.NewLocalRoomRoute(server.PKRoute.Visor, server.PKRoute.Server, roomBoolMap) - r := chat.NewLocalRoom(roomRoute, command.Info, chat.DefaultRoomType) - - //setup user as peer for memberships - p := peer.NewPeer(*usr.GetInfo(), usr.GetInfo().Alias) - - //Add user as member from server - err = server.AddMember(*p) + err = server.AddRoom(*room) if err != nil { return err } - //Add user as admin, otherwise we can't send admin command messages to our own server - err = server.AddAdmin(p.GetPK()) + + err = visor.AddServer(*server) if err != nil { return err } - //Add user as member from room - err = r.AddMember(*p) + err = h.visorRepo.Set(*visor) if err != nil { return err } - //Add room to server - err = server.AddRoom(r) + n := notification.NewAddRouteNotification(room.GetPKRoute()) + err = h.notifService.Notify(n) if err != nil { return err } - // Add server to visor and then update repository - err = visor.AddServer(*server) + return nil +} + +func (h addLocalServerRequestHandler) getLocalVisorOrAddIfNotExists() (*chat.Visor, error) { + userPK, err := h.getUserPK() if err != nil { - return err + return nil, err } - err = h.visorRepo.Set(visor) + + visorIfExists, err := h.visorRepo.GetByPK(*userPK) if err != nil { - return err + newVisor := chat.NewUndefinedVisor(*userPK) + err = h.visorRepo.Add(newVisor) + if err != nil { + return nil, err + } + return &newVisor, nil } + return visorIfExists, nil +} - //notify about sent chat request message - n := notification.NewAddRouteNotification(roomRoute) - err = h.ns.Notify(n) +func (h addLocalServerRequestHandler) getUserPK() (*cipher.PubKey, error) { + usr, err := h.userRepo.GetUser() if err != nil { - return err + return nil, err } - return nil + pk := usr.GetInfo().GetPK() + return &pk, nil +} + +func (h addLocalServerRequestHandler) getNewServer(visor *chat.Visor, command AddLocalServerRequest) (*chat.Server, error) { + userAsPeer, err := h.getUserAsPeer() + if err != nil { + return nil, err + } + + visorBoolMap := visor.GetAllServerBoolMap() + + route := util.NewLocalServerRoute(visor.GetPK(), visorBoolMap) + server, err := chat.NewLocalServer(route, command.Info) + if err != nil { + return nil, err + } + + //Add user as member, otherwise we can't receive server messages //?? check if really needed. + err = server.AddMember(*userAsPeer) + if err != nil { + return nil, err + } + + //Add user as admin, otherwise we can't send admin command messages to our own server + err = server.AddAdmin(userAsPeer.GetPK()) + if err != nil { + return nil, err + } + return server, nil +} + +func (h addLocalServerRequestHandler) getNewRoom(server *chat.Server, command AddLocalServerRequest) (*chat.Room, error) { + + roomBoolMap := server.GetAllRoomsBoolMap() + roomRoute := util.NewLocalRoomRoute(server.PKRoute.Visor, server.PKRoute.Server, roomBoolMap) + room := chat.NewLocalRoom(roomRoute, command.Info, chat.DefaultRoomType) + + //Add user as member, otherwise we can't receive room messages //?? check if really needed. + userAsPeer, err := h.getUserAsPeer() + if err != nil { + return nil, err + } + err = room.AddMember(*userAsPeer) + if err != nil { + return nil, err + } + return &room, nil +} + +func (h addLocalServerRequestHandler) getUserAsPeer() (*peer.Peer, error) { + usr, err := h.userRepo.GetUser() + if err != nil { + return nil, err + } + p := peer.NewPeer(*usr.GetInfo(), usr.GetInfo().Alias) + return p, nil } diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_fire_moderator.go b/cmd/apps/skychat/internal/app/chat/commands/send_fire_moderator_message.go similarity index 100% rename from cmd/apps/skychat/internal/app/chat/commands/send_fire_moderator.go rename to cmd/apps/skychat/internal/app/chat/commands/send_fire_moderator_message.go diff --git a/cmd/apps/skychat/internal/app/chat/commands/send_hire_moderator.go b/cmd/apps/skychat/internal/app/chat/commands/send_hire_moderator_message.go similarity index 100% rename from cmd/apps/skychat/internal/app/chat/commands/send_hire_moderator.go rename to cmd/apps/skychat/internal/app/chat/commands/send_hire_moderator_message.go diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_room_by_route.go b/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_room_by_route.go index 1073f5f1d..d547290a4 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_room_by_route.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_room_by_route.go @@ -33,34 +33,49 @@ func NewGetAllMessagesFromRoomRequestHandler(visorRepo chat.Repository) GetAllMe // Handle Handlers the GetAllMessagesFromRoomRequest query func (h getAllMessagesFromRoomRequestHandler) Handle(query GetAllMessagesFromRoomRequest) (GetAllMessagesFromRoomResult, error) { + if query.isP2PRequest() { + return h.getP2PMessagesResult(query) + } else { + return h.getRoomMessagesResult(query) + } +} + +func (r *GetAllMessagesFromRoomRequest) isP2PRequest() bool { + return r.Route.Server == r.Route.Visor +} + +func (h getAllMessagesFromRoomRequestHandler) getP2PMessagesResult(query GetAllMessagesFromRoomRequest) (GetAllMessagesFromRoomResult, error) { var result GetAllMessagesFromRoomResult visor, err := h.visorRepo.GetByPK(query.Route.Visor) if err != nil { return result, err } - var msgs []message.Message - - if query.Route.Server == query.Route.Visor { - p2p, err := visor.GetP2P() - if err != nil { - return result, err - } - msgs = p2p.GetMessages() - } else { - server, err := visor.GetServerByPK(query.Route.Server) - if err != nil { - return result, err - } - room, err := server.GetRoomByPK(query.Route.Room) - if err != nil { - return result, err - } - msgs = room.GetMessages() + + msgs, err := visor.GetP2PMessages() + if err != nil { + return result, err } - if msgs != nil { - result = GetAllMessagesFromRoomResult{Messages: msgs} + result = GetAllMessagesFromRoomResult{Messages: msgs} + + return result, nil +} + +func (h getAllMessagesFromRoomRequestHandler) getRoomMessagesResult(query GetAllMessagesFromRoomRequest) (GetAllMessagesFromRoomResult, error) { + var result GetAllMessagesFromRoomResult + + visor, err := h.visorRepo.GetByPK(query.Route.Visor) + if err != nil { + return result, err } + + msgs, err := visor.GetRoomMessages(query.Route) + if err != nil { + return result, err + } + + result = GetAllMessagesFromRoomResult{Messages: msgs} + return result, nil } diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_all_visors.go b/cmd/apps/skychat/internal/app/chat/queries/get_all_visors.go index 2062a2f26..36686a6a1 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_all_visors.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_all_visors.go @@ -29,19 +29,25 @@ func NewGetAllVisorsRequestHandler(visorRepo chat.Repository) GetAllVisorsReques // Handle Handles the query func (h getAllVisorsRequestHandler) Handle() ([]GetAllVisorsResult, error) { + var result []GetAllVisorsResult - res, err := h.visorRepo.GetAll() + allVisors, err := h.visorRepo.GetAll() if err != nil { return nil, err } - var result []GetAllVisorsResult - for _, visor := range res { + + for _, visor := range allVisors { p2p, err := visor.GetP2P() if err != nil { return nil, err } - result = append(result, GetAllVisorsResult{Pk: visor.GetPK(), P2P: *p2p, Server: visor.GetAllServer()}) + + result = append(result, GetAllVisorsResult{ + Pk: visor.GetPK(), + P2P: *p2p, + Server: visor.GetAllServer(), + }) } return result, nil } diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go b/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go index 98736a258..5032476fa 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go @@ -45,39 +45,71 @@ func NewGetRoomByRouteRequestHandler(visorRepo chat.Repository) GetRoomByRouteRe return getRoomByRouteRequestHandler{visorRepo: visorRepo} } -// Handle Handles the query +// Handle handles the query func (h getRoomByRouteRequestHandler) Handle(query GetRoomByRouteRequest) (GetRoomByRouteResult, error) { + if query.isP2PRequest() { + return h.getP2PRoomResult(query) + } else { + return h.getRouteRoomResult(query) + } +} - visor, err := h.visorRepo.GetByPK(query.Route.Visor) +func (r *GetRoomByRouteRequest) isP2PRequest() bool { + return r.Route.Server == r.Route.Visor +} + +func (h getRoomByRouteRequestHandler) getP2PRoomResult(query GetRoomByRouteRequest) (GetRoomByRouteResult, error) { var result GetRoomByRouteResult + visor, err := h.visorRepo.GetByPK(query.Route.Visor) if err != nil { return result, err } - if query.Route.Visor == query.Route.Server { - p2p, err := visor.GetP2P() - if err != nil { - return result, err - } - - result = GetRoomByRouteResult{PKRoute: p2p.PKRoute, Info: p2p.Info, Msgs: p2p.Msgs, IsVisible: p2p.IsVisible, Type: p2p.Type, Members: p2p.Members, Mods: p2p.Mods, Muted: p2p.Muted, Blacklist: p2p.Blacklist, Whitelist: p2p.Whitelist} - - } else { + p2p, err := visor.GetP2P() + if err != nil { + return result, err + } - server, err := visor.GetServerByPK(query.Route.Server) + result = GetRoomByRouteResult{ + PKRoute: p2p.PKRoute, + Info: p2p.Info, + Msgs: p2p.Msgs, + IsVisible: p2p.IsVisible, + Type: p2p.Type, + Members: p2p.Members, + Mods: p2p.Mods, + Muted: p2p.Muted, + Blacklist: p2p.Blacklist, + Whitelist: p2p.Whitelist, + } + return result, nil +} - if err != nil { - return result, err - } +func (h getRoomByRouteRequestHandler) getRouteRoomResult(query GetRoomByRouteRequest) (GetRoomByRouteResult, error) { + var result GetRoomByRouteResult - room, err := server.GetRoomByPK(query.Route.Room) + visor, err := h.visorRepo.GetByPK(query.Route.Visor) + if err != nil { + return result, err + } - if err != nil { - return result, err - } + room, err := visor.GetRoomByRoute(query.Route) + if err != nil { + return result, err + } - result = GetRoomByRouteResult{PKRoute: room.PKRoute, Info: room.Info, Msgs: room.Msgs, IsVisible: room.IsVisible, Type: room.Type, Members: room.Members, Mods: room.Mods, Muted: room.Muted, Blacklist: server.Blacklist, Whitelist: server.Whitelist} + result = GetRoomByRouteResult{ + PKRoute: room.PKRoute, + Info: room.Info, + Msgs: room.Msgs, + IsVisible: room.IsVisible, + Type: room.Type, + Members: room.Members, + Mods: room.Mods, + Muted: room.Muted, + Blacklist: room.Blacklist, + Whitelist: room.Whitelist, } return result, nil } diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_server_by_route.go b/cmd/apps/skychat/internal/app/chat/queries/get_server_by_route.go index 27c0ca852..29c3e0676 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_server_by_route.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_server_by_route.go @@ -42,21 +42,28 @@ func NewGetServerByRouteRequestHandler(visorRepo chat.Repository) GetServerByRou // Handle Handles the query func (h getServerByRouteRequestHandler) Handle(query GetServerByRouteRequest) (GetServerByRouteResult, error) { - - visor, err := h.visorRepo.GetByPK(query.Route.Visor) var result GetServerByRouteResult + visor, err := h.visorRepo.GetByPK(query.Route.Visor) if err != nil { return result, err } server, err := visor.GetServerByPK(query.Route.Server) - if err != nil { return result, err } - result = GetServerByRouteResult{PKRoute: server.PKRoute, Info: server.Info, Members: server.Members, Admins: server.Admins, Muted: server.Muted, Blacklist: server.Blacklist, Whitelist: server.Whitelist, Rooms: server.Rooms} + result = GetServerByRouteResult{ + PKRoute: server.PKRoute, + Info: server.Info, + Members: server.Members, + Admins: server.Admins, + Muted: server.Muted, + Blacklist: server.Blacklist, + Whitelist: server.Whitelist, + Rooms: server.Rooms, + } return result, nil } diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_visor_by_pk.go b/cmd/apps/skychat/internal/app/chat/queries/get_visor_by_pk.go index db912bfa4..8d8728478 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_visor_by_pk.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_visor_by_pk.go @@ -34,7 +34,6 @@ func NewGetVisorByPKRequestHandler(visorRepo chat.Repository) GetVisorByPKReques // Handle Handles the query func (h getVisorByPKRequestHandler) Handle(query GetVisorByPKRequest) (GetVisorByPKResult, error) { - var result GetVisorByPKResult visor, err := h.visorRepo.GetByPK(query.Pk) @@ -47,7 +46,11 @@ func (h getVisorByPKRequestHandler) Handle(query GetVisorByPKRequest) (GetVisorB return GetVisorByPKResult{}, err } - result = GetVisorByPKResult{Pk: visor.GetPK(), P2P: *p2p, Server: visor.GetAllServer()} + result = GetVisorByPKResult{ + Pk: visor.GetPK(), + P2P: *p2p, + Server: visor.GetAllServer(), + } return result, nil } diff --git a/cmd/apps/skychat/internal/domain/chat/visor.go b/cmd/apps/skychat/internal/domain/chat/visor.go index 969775c0d..3828fe01d 100644 --- a/cmd/apps/skychat/internal/domain/chat/visor.go +++ b/cmd/apps/skychat/internal/domain/chat/visor.go @@ -32,6 +32,33 @@ func (v *Visor) GetP2P() (*Room, error) { return &v.P2P, nil } +// GetP2PMessages returns the messages from the visors p2p room +func (v *Visor) GetP2PMessages() ([]message.Message, error) { + p2p, err := v.GetP2P() + if err != nil { + return nil, err + } + return p2p.GetMessages(), nil +} + +// GetRoomMessages returns the messages from the given room route +func (v *Visor) GetRoomMessages(route util.PKRoute) ([]message.Message, error) { + room, err := v.GetRoomByRoute(route) + if err != nil { + return nil, err + } + return room.GetMessages(), nil +} + +// GetRoomByRoute returns the room from the given route +func (v *Visor) GetRoomByRoute(route util.PKRoute) (*Room, error) { + server, err := v.GetServerByPK(route.Server) + if err != nil { + return nil, err + } + return server.GetRoomByPK(route.Room) +} + // P2PIsEmpty returns a bool depending on if the visor has got a p2p func (v *Visor) P2PIsEmpty() bool { return reflect.DeepEqual(v.P2P, Room{}) diff --git a/cmd/apps/skychat/internal/domain/util/default_pkroutes.go b/cmd/apps/skychat/internal/domain/util/default_pkroutes.go new file mode 100644 index 000000000..3a5b66f98 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/util/default_pkroutes.go @@ -0,0 +1,67 @@ +// Package util collects all structs and functions needed inside skychat +package util + +import "github.com/skycoin/skywire-utilities/pkg/cipher" + +// NewVisorOnlyRoute returns a route with only the visor pubkey +func NewVisorOnlyRoute(pk cipher.PubKey) PKRoute { + pkr := PKRoute{} + pkr.Visor = pk + return pkr +} + +// NewP2PRoute returns a route with visor pubkey == server pubkey +func NewP2PRoute(visorpk cipher.PubKey) PKRoute { + pkr := PKRoute{} + pkr.Visor = visorpk + pkr.Server = visorpk + pkr.Room = visorpk + return pkr +} + +// NewServerRoute returns a new route of a server +// This is achieved by setting Room == Server +func NewServerRoute(visorpk cipher.PubKey, serverpk cipher.PubKey) PKRoute { + pkr := PKRoute{} + pkr.Visor = visorpk + pkr.Server = serverpk + pkr.Room = serverpk + return pkr +} + +// NewRoomRoute returns a new route of a room +func NewRoomRoute(visorpk cipher.PubKey, serverpk cipher.PubKey, roompk cipher.PubKey) PKRoute { + pkr := PKRoute{} + pkr.Visor = visorpk + pkr.Server = serverpk + pkr.Room = roompk + return pkr +} + +// NewLocalServerRoute sets up a new local defined server route +func NewLocalServerRoute(visorPK cipher.PubKey, existingServer map[cipher.PubKey]bool) PKRoute { + + serverPK := cipher.PubKey{} + + for ok := true; ok; ok = !existingServer[serverPK] { + serverPK, _ = cipher.GenerateKeyPair() + existingServer[serverPK] = true + + } + + r := NewServerRoute(visorPK, serverPK) + return r +} + +// NewLocalRoomRoute sets up a new local defined room route +func NewLocalRoomRoute(visorPK cipher.PubKey, serverPK cipher.PubKey, existingRooms map[cipher.PubKey]bool) PKRoute { + roomPK := cipher.PubKey{} + + for ok := true; ok; ok = !existingRooms[roomPK] { + roomPK, _ = cipher.GenerateKeyPair() + existingRooms[roomPK] = true + } + + r := NewRoomRoute(visorPK, serverPK, roomPK) + return r +} diff --git a/cmd/apps/skychat/internal/domain/util/pkroute.go b/cmd/apps/skychat/internal/domain/util/pkroute.go index 5fb40cae3..ea8a52fbf 100644 --- a/cmd/apps/skychat/internal/domain/util/pkroute.go +++ b/cmd/apps/skychat/internal/domain/util/pkroute.go @@ -12,70 +12,7 @@ type PKRoute struct { Room cipher.PubKey // P2P: Room=nil // Server: PK of room } -// NewVisorOnlyRoute returns a route with only the visor pubkey -func NewVisorOnlyRoute(pk cipher.PubKey) PKRoute { - pkr := PKRoute{} - pkr.Visor = pk - return pkr -} - -// NewP2PRoute returns a route with visor pubkey == server pubkey -func NewP2PRoute(visorpk cipher.PubKey) PKRoute { - pkr := PKRoute{} - pkr.Visor = visorpk - pkr.Server = visorpk - pkr.Room = visorpk - return pkr -} - -// NewServerRoute returns a new route of a server -// This is achieved by setting Room == Server -func NewServerRoute(visorpk cipher.PubKey, serverpk cipher.PubKey) PKRoute { - pkr := PKRoute{} - pkr.Visor = visorpk - pkr.Server = serverpk - pkr.Room = serverpk - return pkr -} - -// NewRoomRoute returns a new route of a room -func NewRoomRoute(visorpk cipher.PubKey, serverpk cipher.PubKey, roompk cipher.PubKey) PKRoute { - pkr := PKRoute{} - pkr.Visor = visorpk - pkr.Server = serverpk - pkr.Room = roompk - return pkr -} - // String returns a string representation of PKRoute func (r *PKRoute) String() string { return "pkVisor: " + r.Visor.Hex() + " pkServer: " + r.Server.Hex() + " pkRoom: " + r.Room.Hex() } - -// NewLocalServerRoute sets up a new local defined server route -func NewLocalServerRoute(visorPK cipher.PubKey, existingServer map[cipher.PubKey]bool) PKRoute { - - serverPK := cipher.PubKey{} - - for ok := true; ok; ok = !existingServer[serverPK] { - serverPK, _ = cipher.GenerateKeyPair() - existingServer[serverPK] = true - - } - - r := NewServerRoute(visorPK, serverPK) - return r -} - -// NewLocalRoomRoute sets up a new local defined room route -func NewLocalRoomRoute(visorPK cipher.PubKey, serverPK cipher.PubKey, existingRooms map[cipher.PubKey]bool) PKRoute { - roomPK := cipher.PubKey{} - - for ok := true; ok; ok = !existingRooms[roomPK] { - roomPK, _ = cipher.GenerateKeyPair() - existingRooms[roomPK] = true - } - - r := NewRoomRoute(visorPK, serverPK, roomPK) - return r -} diff --git a/cmd/apps/skychat/internal/inputports/cli/root.go b/cmd/apps/skychat/internal/inputports/cli/root.go index 50e1fbf0b..d133cc80c 100644 --- a/cmd/apps/skychat/internal/inputports/cli/root.go +++ b/cmd/apps/skychat/internal/inputports/cli/root.go @@ -51,11 +51,11 @@ var rootCmd = &cobra.Command{ //messengerService listen go interfaceadapters.InterfaceAdapterServices.MessengerService.Listen() - //rpc-server + //rpc-server for cli functionality rpcport = ":4040" go inputports.InputportsServices.RPCServer.ListenAndServe(&rpcport) - //http-server + //http-server for web-ui inputports.InputportsServices.HTTPServer.ListenAndServe(&httpport) }, } From a314f0537e52d3652ffb9874f272ed4ffd18597b Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Tue, 20 Jun 2023 22:04:41 +0200 Subject: [PATCH 49/72] refactor delete to only delete local instances of chats and groups --- .../app/chat/commands/delete_local_route.go | 97 ------- .../app/chat/commands/delete_route.go | 240 ++++++++++++++++++ .../skychat/internal/app/chat/services.go | 4 +- .../skychat/internal/domain/util/pkroute.go | 24 +- .../internal/inputports/http/chat/handler.go | 16 +- .../internal/inputports/http/server.go | 2 +- .../inputports/http/static/index.html | 1 + .../internal/inputports/http/static/index.js | 56 +++- 8 files changed, 327 insertions(+), 113 deletions(-) delete mode 100644 cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go create mode 100644 cmd/apps/skychat/internal/app/chat/commands/delete_route.go diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go b/cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go deleted file mode 100644 index 7713f5675..000000000 --- a/cmd/apps/skychat/internal/app/chat/commands/delete_local_route.go +++ /dev/null @@ -1,97 +0,0 @@ -// Package commands contains commands to delete local route -package commands - -import ( - "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" -) - -// DeleteLocalRouteRequest of DeleteLocalRouteRequestHandler -type DeleteLocalRouteRequest struct { - Route util.PKRoute -} - -// DeleteLocalRouteRequestHandler struct that allows handling DeleteLocalRouteRequest -type DeleteLocalRouteRequestHandler interface { - Handle(command DeleteLocalRouteRequest) error -} - -type deleteLocalRouteRequestHandler struct { - messengerService messenger.Service - visorRepo chat.Repository -} - -// NewDeleteLocalRouteRequestHandler Initializes an AddCommandHandler -func NewDeleteLocalRouteRequestHandler(messengerService messenger.Service, visorRepo chat.Repository) DeleteLocalRouteRequestHandler { - return deleteLocalRouteRequestHandler{messengerService: messengerService, visorRepo: visorRepo} -} - -// Handle Handles the DeleteLocalRouteRequest -func (h deleteLocalRouteRequestHandler) Handle(command DeleteLocalRouteRequest) error { - // Check if visor exists - visor, err := h.visorRepo.GetByPK(command.Route.Visor) - if err != nil { - return err - } - // Check if server exists - server, err := visor.GetServerByPK(command.Route.Server) - if err != nil { - return err - } - - // if this, then we want to delete the whole server - if command.Route.Server == command.Route.Room { - //Send Server-Delete-Message to Server members -> they then have to delete or disable the function to send new messages to the server - serverroute := util.NewServerRoute(command.Route.Visor, command.Route.Server) - err = h.messengerService.SendRouteDeletedMessage(serverroute) - if err != nil { - return err - } - - //Delete server from visor - err = visor.DeleteServer(command.Route.Server) - if err != nil { - return err - } - - //update visorrepository - return h.visorRepo.Set(*visor) - } - - // Check if room exists - room, err := server.GetRoomByPK(command.Route.Room) - if err != nil { - return err - } - - //Send Room-Deleted-Message to room members - err = h.messengerService.SendRouteDeletedMessage(command.Route) - if err != nil { - return err - } - - //if room is public/visibile also send message to server members - if room.GetIsVisible() { - serverroute := util.NewServerRoute(command.Route.Visor, command.Route.Server) - err = h.messengerService.SendRouteDeletedMessage(serverroute) - if err != nil { - return err - } - } - - //delete room from server - err = server.DeleteRoom(command.Route.Room) - if err != nil { - return err - } - - //update visor - err = visor.SetServer(*server) - if err != nil { - return err - } - - //update visorrepository - return h.visorRepo.Set(*visor) -} diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_route.go b/cmd/apps/skychat/internal/app/chat/commands/delete_route.go new file mode 100644 index 000000000..e29cfa05d --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/delete_route.go @@ -0,0 +1,240 @@ +// Package commands contains commands to delete local route +package commands + +import ( + "fmt" + + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// DeleteRouteRequest of DeleteRouteRequestHandler +type DeleteRouteRequest struct { + Route util.PKRoute +} + +// DeleteRouteRequestHandler struct that allows handling DeleteRouteRequest +type DeleteRouteRequestHandler interface { + Handle(command DeleteRouteRequest) error +} + +type deleteRouteRequestHandler struct { + messengerService messenger.Service + visorRepo chat.Repository + usrRepo user.Repository +} + +// NewDeleteRouteRequestHandler Initializes an AddCommandHandler +func NewDeleteRouteRequestHandler(messengerService messenger.Service, visorRepo chat.Repository, usrRepo user.Repository) DeleteRouteRequestHandler { + return deleteRouteRequestHandler{messengerService: messengerService, visorRepo: visorRepo, usrRepo: usrRepo} +} + +// Handle Handles the DeleteRouteRequest +func (h deleteRouteRequestHandler) Handle(command DeleteRouteRequest) error { + if h.routeIsOfOwnVisor(command.Route) { + err := h.deleteLocalRoute(command) + if err != nil { + return err + } + } + + err := h.deleteRemoteRoute(command) + if err != nil { + return err + } + + return nil +} + +func (h deleteRouteRequestHandler) routeIsOfOwnVisor(route util.PKRoute) bool { + usr, err := h.usrRepo.GetUser() + if err != nil { + fmt.Printf("Error getting user from repository: %s", err) + //return err + //TODO: handle different? + return true + } + + if route.Visor == usr.GetInfo().GetPK() { + return true + } + + return false +} + +func (h deleteRouteRequestHandler) deleteLocalRoute(command DeleteRouteRequest) error { + if command.isDeleteServerRouteCommand() { + //TODO: Send_Route_Deleted_Message + err := h.deleteServerRoute(command.Route) + if err != nil { + return err + } + err = h.deleteVisorIfEmpty(command.Route) + if err != nil { + return err + } + return nil + } + + if command.isDeleteRoomRouteCommand() { + //TODO: Send_Route_Deleted_Message + err := h.deleteRoomRoute(command.Route) + if err != nil { + return err + } + err = h.deleteServerIfEmpty(command.Route) + if err != nil { + return err + } + err = h.deleteVisorIfEmpty(command.Route) + if err != nil { + return err + } + } + + return nil +} + +func (h deleteRouteRequestHandler) deleteRemoteRoute(command DeleteRouteRequest) error { + if command.isDeleteP2PRouteCommand() { + err := h.deleteP2PRoute(command.Route) + if err != nil { + return err + } + err = h.deleteVisorIfEmpty(command.Route) + if err != nil { + return err + } + return nil + } + + if command.isDeleteServerRouteCommand() { + err := h.deleteServerRoute(command.Route) + if err != nil { + return err + } + err = h.deleteVisorIfEmpty(command.Route) + if err != nil { + return err + } + return nil + } + + if command.isDeleteRoomRouteCommand() { + err := h.deleteRoomRoute(command.Route) + if err != nil { + return err + } + err = h.deleteServerIfEmpty(command.Route) + if err != nil { + return err + } + err = h.deleteVisorIfEmpty(command.Route) + if err != nil { + return err + } + } + + return nil +} + +func (c DeleteRouteRequest) isDeleteP2PRouteCommand() bool { + return c.Route.IsP2PRoute() +} + +func (c DeleteRouteRequest) isDeleteServerRouteCommand() bool { + return c.Route.IsServerRoute() +} + +func (c DeleteRouteRequest) isDeleteRoomRouteCommand() bool { + return c.Route.IsRoomRoute() +} + +func (h deleteRouteRequestHandler) deleteVisorIfEmpty(route util.PKRoute) error { + visor, err := h.visorRepo.GetByPK(route.Visor) + if err != nil { + return err + } + + if len(visor.GetAllServer()) == 0 && visor.P2PIsEmpty() { + return h.visorRepo.Delete(route.Visor) + } + + return nil +} + +func (h deleteRouteRequestHandler) deleteServerIfEmpty(route util.PKRoute) error { + visor, err := h.visorRepo.GetByPK(route.Visor) + if err != nil { + return err + } + + server, err := visor.GetServerByPK(route.Server) + if err != nil { + return err + } + + if len(server.GetAllRooms()) == 0 { + err = visor.DeleteServer(route.Server) + if err != nil { + return err + } + return h.visorRepo.Set(*visor) + } + + return nil +} + +func (h deleteRouteRequestHandler) deleteP2PRoute(route util.PKRoute) error { + visor, err := h.visorRepo.GetByPK(route.Visor) + if err != nil { + return err + } + + err = visor.DeleteP2P() + if err != nil { + return err + } + + return h.visorRepo.Set(*visor) +} + +func (h deleteRouteRequestHandler) deleteServerRoute(route util.PKRoute) error { + visor, err := h.visorRepo.GetByPK(route.Visor) + if err != nil { + return err + } + + err = visor.DeleteServer(route.Server) + if err != nil { + return err + } + + return h.visorRepo.Set(*visor) +} + +func (h deleteRouteRequestHandler) deleteRoomRoute(route util.PKRoute) error { + visor, err := h.visorRepo.GetByPK(route.Visor) + if err != nil { + return err + } + + server, err := visor.GetServerByPK(route.Server) + if err != nil { + return err + } + + err = server.DeleteRoom(route.Room) + if err != nil { + return err + } + + err = visor.SetServer(*server) + if err != nil { + return err + } + + return h.visorRepo.Set(*visor) +} diff --git a/cmd/apps/skychat/internal/app/chat/services.go b/cmd/apps/skychat/internal/app/chat/services.go index 81b0e0919..4b543f927 100644 --- a/cmd/apps/skychat/internal/app/chat/services.go +++ b/cmd/apps/skychat/internal/app/chat/services.go @@ -24,7 +24,7 @@ type Queries struct { type Commands struct { AddLocalServerHandler commands.AddLocalServerRequestHandler JoinRemoteRouteHandler commands.JoinRemoteRouteRequestHandler - DeleteLocalRouteHandler commands.DeleteLocalRouteRequestHandler + DeleteRouteHandler commands.DeleteRouteRequestHandler LeaveRemoteRouteHandler commands.LeaveRemoteRouteRequestHandler SendAddRoomMessageHandler commands.SendAddRoomMessageRequestHandler SendDeleteRoomMessageHandler commands.SendDeleteRoomMessageRequestHandler @@ -54,7 +54,7 @@ func NewServices(cliRepo client.Repository, visorRepo chat.Repository, userRepo Commands: Commands{ AddLocalServerHandler: commands.NewAddLocalServerRequestHandler(visorRepo, userRepo, ns), JoinRemoteRouteHandler: commands.NewJoinRemoteRouteRequestHandler(visorRepo, ms), - DeleteLocalRouteHandler: commands.NewDeleteLocalRouteRequestHandler(ms, visorRepo), + DeleteRouteHandler: commands.NewDeleteRouteRequestHandler(ms, visorRepo, userRepo), LeaveRemoteRouteHandler: commands.NewLeaveRemoteRouteRequestHandler(ms, visorRepo, userRepo), SendAddRoomMessageHandler: commands.NewSendAddRoomMessageRequestHandler(ms), SendDeleteRoomMessageHandler: commands.NewSendDeleteRoomMessageRequestHandler(ms), diff --git a/cmd/apps/skychat/internal/domain/util/pkroute.go b/cmd/apps/skychat/internal/domain/util/pkroute.go index ea8a52fbf..16fd0681c 100644 --- a/cmd/apps/skychat/internal/domain/util/pkroute.go +++ b/cmd/apps/skychat/internal/domain/util/pkroute.go @@ -6,13 +6,31 @@ import ( ) // PKRoute defines the routing inside the skychat app if a root or destination is from a p2p chat or a specific room of a specific server. +// P2PRoute: VisorPK == ServerPK == RoomPK +// ServerRoute: VisorPK != ServerPK && ServerPK == RoomPK +// RoomRoute: VisorPK != ServerPK && ServerPK != RoomPK type PKRoute struct { - Visor cipher.PubKey // PK of visor - Server cipher.PubKey // P2P: Server=Visor // Server: PK of server - Room cipher.PubKey // P2P: Room=nil // Server: PK of room + Visor cipher.PubKey + Server cipher.PubKey + Room cipher.PubKey } // String returns a string representation of PKRoute func (r *PKRoute) String() string { return "pkVisor: " + r.Visor.Hex() + " pkServer: " + r.Server.Hex() + " pkRoom: " + r.Room.Hex() } + +// IsP2PRoute returns if the route is a p2p route +func (r *PKRoute) IsP2PRoute() bool { + return r.Visor == r.Server && r.Server == r.Room +} + +// IsServerRoute returns if the route is a server route +func (r *PKRoute) IsServerRoute() bool { + return r.Visor != r.Server && r.Server == r.Room +} + +// IsRoomRoute returns if the route is a room route +func (r *PKRoute) IsRoomRoute() bool { + return r.Visor != r.Server && r.Server != r.Room +} diff --git a/cmd/apps/skychat/internal/inputports/http/chat/handler.go b/cmd/apps/skychat/internal/inputports/http/chat/handler.go index 8c340f3d2..41436fe77 100644 --- a/cmd/apps/skychat/internal/inputports/http/chat/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/chat/handler.go @@ -567,19 +567,19 @@ func (c Handler) SendFireModMessage(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) } -// DeleteLocalRouteURLParam contains the parameter identifier to be parsed by the handler -const DeleteLocalRouteURLParam = "DeleteLocalRoute" +// DeleteRouteURLParam contains the parameter identifier to be parsed by the handler +const DeleteRouteURLParam = "deleteRoute" -// DeleteLocalRouteRequestModel represents the request model expected for Delete request -type DeleteLocalRouteRequestModel struct { +// DeleteRouteRequestModel represents the request model expected for Delete request +type DeleteRouteRequestModel struct { VisorPk string `json:"visorpk"` ServerPk string `json:"serverpk"` RoomPk string `json:"roompk"` } -// DeleteLocalRoute adds a room to the local visor/server -func (c Handler) DeleteLocalRoute(w http.ResponseWriter, r *http.Request) { - var requestModel DeleteLocalRouteRequestModel +// DeleteRoute adds a room to the local visor/server +func (c Handler) DeleteRoute(w http.ResponseWriter, r *http.Request) { + var requestModel DeleteRouteRequestModel decodeErr := json.NewDecoder(r.Body).Decode(&requestModel) if decodeErr != nil { w.WriteHeader(http.StatusBadRequest) @@ -619,7 +619,7 @@ func (c Handler) DeleteLocalRoute(w http.ResponseWriter, r *http.Request) { } } - err = c.chatServices.Commands.DeleteLocalRouteHandler.Handle(commands.DeleteLocalRouteRequest{ + err = c.chatServices.Commands.DeleteRouteHandler.Handle(commands.DeleteRouteRequest{ Route: route, }) if err != nil { diff --git a/cmd/apps/skychat/internal/inputports/http/server.go b/cmd/apps/skychat/internal/inputports/http/server.go index c8fca9145..a97663b83 100644 --- a/cmd/apps/skychat/internal/inputports/http/server.go +++ b/cmd/apps/skychat/internal/inputports/http/server.go @@ -62,9 +62,9 @@ func (httpServer *Server) AddChatHTTPRoutes() { //Local httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.AddLocalServerURLParam, chat.NewHandler(httpServer.appServices.ChatServices).AddLocalServer).Methods("POST") - httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.DeleteLocalRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).DeleteLocalRoute).Methods("POST") //Both + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.DeleteRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).DeleteRoute).Methods("POST") httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendAddRoomMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendAddRoomMessage).Methods("POST") httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendDeleteRoomMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendDeleteRoomMessage).Methods("POST") httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.SendTextMessageURLParam, chat.NewHandler(httpServer.appServices.ChatServices).SendTextMessage).Methods("POST") diff --git a/cmd/apps/skychat/internal/inputports/http/static/index.html b/cmd/apps/skychat/internal/inputports/http/static/index.html index 4150c85ef..0877f2660 100644 --- a/cmd/apps/skychat/internal/inputports/http/static/index.html +++ b/cmd/apps/skychat/internal/inputports/http/static/index.html @@ -31,6 +31,7 @@
              diff --git a/cmd/apps/skychat/internal/inputports/http/static/index.js b/cmd/apps/skychat/internal/inputports/http/static/index.js index c83dc7a21..223642af3 100644 --- a/cmd/apps/skychat/internal/inputports/http/static/index.js +++ b/cmd/apps/skychat/internal/inputports/http/static/index.js @@ -1143,7 +1143,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa } //// DELETE - //tries to delete the given route + //tries to leave the given route leaveRemoteRoute() { if (!this.chat) { return; @@ -1160,7 +1160,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa return; } - const response = window.confirm("Are you sure you want to delete the chat?"); + const response = window.confirm("Are you sure you want to leave the chat?"); const visorpk = route.visor const serverpk = route.server @@ -1195,6 +1195,58 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa } } + //tries to delete the given route + deleteRoute() { + if (!this.chat) { + return; + } + + let route = null + Object.keys(this.chats).forEach(c => { + if (this.chats[c].pk == this.chat){ + route = this.chats[c].route; + } + }) + + if (route == null){ + return; + } + + const response = window.confirm("Are you sure you want to delete the chat?"); + + const visorpk = route.visor + const serverpk = route.server + const roompk = route.room + + if (response) { + fetch('chats' + '/deleteRoute', { method: 'POST', body: JSON.stringify({ visorpk: visorpk, serverpk: serverpk, roompk: roompk}) }) + .then(res => { + if (res.ok) { + res.text().then(); + this.chats = this.chats.filter(v => v.pk != roompk); + + document.getElementById('messages').innerHTML = ''; + document.getElementById('chatButtonsContainer').classList.add('hidden'); + document.getElementById('msgForm').classList.add('hidden'); + document.querySelectorAll('.destination').forEach(item => { + + const pkArea = item.getElementsByClassName('pk')[0]; + + if (pkArea.innerText === roompk) { + item.parentNode.removeChild(item); + }}); + this.chat = null; + } else { + res.text().then(text => alert(`Failed to delete chat:\n visor:\n${visorpk}\nserver:\n${serverpk}\nroom:\n${roompk}\nreason:\n${text}`)); + } + }) + + } + else{ + return; + } + } + ///////////////////////////////////////////////////////////// //// HTTP /notification ///////////////////////////////////////////////////////////// From 542f28f5533b3e4eef88d0a91178ad5a143754b7 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Tue, 20 Jun 2023 22:05:40 +0200 Subject: [PATCH 50/72] refactoring for better readability --- .../app/chat/commands/join_remote_route.go | 29 ++- .../app/chat/commands/leave_remote_route.go | 190 ++++++++++++++---- 2 files changed, 168 insertions(+), 51 deletions(-) diff --git a/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go b/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go index 65ad3cc8b..3b5f46c11 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go +++ b/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go @@ -31,19 +31,11 @@ func NewJoinRemoteRouteRequestHandler(visorRepo chat.Repository, messengerServic // Handle Handles the JoinRemoteRouteRequest func (h joinRemoteRouteRequestHandler) Handle(command JoinRemoteRouteRequest) error { - visor, err := h.visorRepo.GetByPK(command.Route.Visor) - if err == nil { - server, err := visor.GetServerByPK(command.Route.Server) - if err == nil { - _, err := server.GetRoomByPK(command.Route.Room) - if err == nil { - return fmt.Errorf("room %s already added", command.Route.String()) - } - } - + if h.roomAlreadyJoined(command) { + return fmt.Errorf("already member of route %s", command.Route.String()) } - err = h.messengerService.SendRouteRequestMessage(command.Route) + err := h.messengerService.SendRouteRequestMessage(command.Route) if err != nil { return err } @@ -52,3 +44,18 @@ func (h joinRemoteRouteRequestHandler) Handle(command JoinRemoteRouteRequest) er return nil } + +// roomAlreadyJoined returns if the user already is member of the route he wants to join +func (h joinRemoteRouteRequestHandler) roomAlreadyJoined(command JoinRemoteRouteRequest) bool { + visor, err := h.visorRepo.GetByPK(command.Route.Visor) + if err == nil { + server, err := visor.GetServerByPK(command.Route.Server) + if err == nil { + _, err := server.GetRoomByPK(command.Route.Room) + if err == nil { + return true + } + } + } + return false +} diff --git a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go index 43deb3799..10b2f9b21 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go +++ b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go @@ -33,88 +33,198 @@ func NewLeaveRemoteRouteRequestHandler(ms messenger.Service, visorRepo chat.Repo // Handle Handles the LeaveRemoteRouteRequest request func (h leaveRemoteRouteRequestHandler) Handle(command LeaveRemoteRouteRequest) error { + if h.routeIsOfOwnVisor(command.Route) { + return fmt.Errorf("cannot leave route of own server") + } + + if command.isLeavingP2PRouteCommand() { + err := h.leaveAndDeleteP2PRoute(command.Route) + if err != nil { + return err + } + err = h.deleteVisorIfEmpty(command.Route) + if err != nil { + return err + } + return nil + } + + if command.isLeavingServerRouteCommand() { + err := h.leaveAndDeleteServerRoute(command.Route) + if err != nil { + return err + } + err = h.deleteVisorIfEmpty(command.Route) + if err != nil { + return err + } + return nil + } + + if command.isLeavingRoomRouteCommand() { + err := h.leaveAndDeleteRoomRoute(command.Route) + if err != nil { + return err + } + + err = h.deleteServerIfEmpty(command.Route) + if err != nil { + return err + } + + err = h.deleteVisorIfEmpty(command.Route) + if err != nil { + return err + } + return nil + } + return nil +} + +func (h leaveRemoteRouteRequestHandler) routeIsOfOwnVisor(route util.PKRoute) bool { usr, err := h.usrRepo.GetUser() if err != nil { fmt.Printf("Error getting user from repository: %s", err) - return err + //return err + //TODO: handle different? + return true } - // Make sure that we don't leave a room of our own server - if command.Route.Visor == usr.GetInfo().GetPK() { - return fmt.Errorf("cannot leave route of own server") + if route.Visor == usr.GetInfo().GetPK() { + return true } - // Check if visor exists - visor, err := h.visorRepo.GetByPK(command.Route.Visor) + return false +} + +func (c LeaveRemoteRouteRequest) isLeavingP2PRouteCommand() bool { + return c.Route.IsP2PRoute() +} + +func (c LeaveRemoteRouteRequest) isLeavingServerRouteCommand() bool { + return c.Route.IsServerRoute() +} + +func (c LeaveRemoteRouteRequest) isLeavingRoomRouteCommand() bool { + return c.Route.IsRoomRoute() +} + +func (h leaveRemoteRouteRequestHandler) leaveAndDeleteP2PRoute(route util.PKRoute) error { + visor, err := h.visorRepo.GetByPK(route.Visor) if err != nil { return err } - // Check if handling p2p room - if command.Route.Server == command.Route.Room { - if !visor.P2PIsEmpty() { - err = h.ms.SendLeaveRouteMessage(command.Route) - if err != nil { - return err - } - err = visor.DeleteP2P() - if err != nil { - return err - } + if !visor.P2PIsEmpty() { + err = h.ms.SendLeaveRouteMessage(route) + if err != nil { + return err } - - // Check if visor has servers, if not delete visor - if len(visor.GetAllServer()) == 0 { - return h.visorRepo.Delete(command.Route.Visor) + err = visor.DeleteP2P() + if err != nil { + return err } + } - return h.visorRepo.Set(*visor) + return h.visorRepo.Set(*visor) +} + +func (h leaveRemoteRouteRequestHandler) leaveAndDeleteServerRoute(route util.PKRoute) error { + visor, err := h.visorRepo.GetByPK(route.Visor) + if err != nil { + return err + } + + _, err = visor.GetServerByPK(route.Server) + if err != nil { + return err + } + + err = h.ms.SendLeaveRouteMessage(route) + if err != nil { + fmt.Println(err) + } + + err = visor.DeleteServer(route.Server) + if err != nil { + return err } - // Check if server exists - server, err := visor.GetServerByPK(command.Route.Server) + return h.visorRepo.Set(*visor) +} + +func (h leaveRemoteRouteRequestHandler) leaveAndDeleteRoomRoute(route util.PKRoute) error { + visor, err := h.visorRepo.GetByPK(route.Visor) if err != nil { return err } - // Check if room exists - _, err = server.GetRoomByPK(command.Route.Room) + server, err := visor.GetServerByPK(route.Server) if err != nil { return err } - // Send LeaveChatMessage to remote server - err = h.ms.SendLeaveRouteMessage(command.Route) + _, err = server.GetRoomByPK(route.Room) + if err != nil { + return err + } + + err = h.ms.SendLeaveRouteMessage(route) if err != nil { fmt.Println(err) } - // Delete room from server - err = server.DeleteRoom(command.Route.Room) + err = server.DeleteRoom(route.Room) + if err != nil { + return err + } + + err = visor.SetServer(*server) + if err != nil { + return err + } + + return h.visorRepo.Set(*visor) +} + +func (h leaveRemoteRouteRequestHandler) deleteVisorIfEmpty(route util.PKRoute) error { + visor, err := h.visorRepo.GetByPK(route.Visor) + if err != nil { + return err + } + + if len(visor.GetAllServer()) == 0 && visor.P2PIsEmpty() { + return h.visorRepo.Delete(route.Visor) + } + + return nil +} + +func (h leaveRemoteRouteRequestHandler) deleteServerIfEmpty(route util.PKRoute) error { + visor, err := h.visorRepo.GetByPK(route.Visor) + if err != nil { + return err + } + + server, err := visor.GetServerByPK(route.Server) if err != nil { return err } - //check if this was the last room of the server if len(server.GetAllRooms()) == 0 { //Prepare ServerRoute - serverroute := util.NewServerRoute(command.Route.Server, command.Route.Server) + serverroute := util.NewServerRoute(route.Server, route.Server) // Send LeaveChatMessage to remote server err = h.ms.SendLeaveRouteMessage(serverroute) if err != nil { return err } - err = visor.DeleteServer(command.Route.Server) + err = visor.DeleteServer(route.Server) if err != nil { return err } + return h.visorRepo.Set(*visor) } - // Check if visor has any other servers or p2p, if not delete visor - if len(visor.GetAllServer()) == 0 && visor.P2PIsEmpty() { - return h.visorRepo.Delete(command.Route.Visor) - } - - // Update repository with changed visor - return h.visorRepo.Set(*visor) + return nil } From 7d2fb402c634b7d98e651e33201f7d5a0920f553 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Wed, 5 Jul 2023 16:43:43 +0200 Subject: [PATCH 51/72] further refactoring and bufixing --- .../app/chat/commands/delete_route.go | 1 + .../app/chat/commands/join_remote_route.go | 8 +- .../app/chat/commands/leave_remote_route.go | 69 +--- .../internal/app/messenger/messenger.go | 1 + .../internal/app/notification/notification.go | 3 +- .../skychat/internal/domain/chat/server.go | 13 + .../skychat/internal/domain/chat/visor.go | 13 + cmd/apps/skychat/internal/domain/user/user.go | 3 - .../messenger/netcon/messenger_service.go | 343 +++++++++++------- .../netcon/messenger_service_local_server.go | 8 +- .../messenger/netcon/messenger_service_p2p.go | 10 +- .../netcon/messenger_service_remote_server.go | 60 ++- .../netcon/messenger_service_send_messages.go | 2 +- cmd/apps/skychat/skychat.go | 2 +- 14 files changed, 324 insertions(+), 212 deletions(-) diff --git a/cmd/apps/skychat/internal/app/chat/commands/delete_route.go b/cmd/apps/skychat/internal/app/chat/commands/delete_route.go index e29cfa05d..aa756738a 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/delete_route.go +++ b/cmd/apps/skychat/internal/app/chat/commands/delete_route.go @@ -159,6 +159,7 @@ func (h deleteRouteRequestHandler) deleteVisorIfEmpty(route util.PKRoute) error } if len(visor.GetAllServer()) == 0 && visor.P2PIsEmpty() { + //TODO: delete connection to Visor in client struct return h.visorRepo.Delete(route.Visor) } diff --git a/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go b/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go index 3b5f46c11..7d2764663 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go +++ b/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go @@ -31,7 +31,7 @@ func NewJoinRemoteRouteRequestHandler(visorRepo chat.Repository, messengerServic // Handle Handles the JoinRemoteRouteRequest func (h joinRemoteRouteRequestHandler) Handle(command JoinRemoteRouteRequest) error { - if h.roomAlreadyJoined(command) { + if h.routeAlreadyJoined(command) { return fmt.Errorf("already member of route %s", command.Route.String()) } @@ -40,13 +40,11 @@ func (h joinRemoteRouteRequestHandler) Handle(command JoinRemoteRouteRequest) er return err } - go h.messengerService.HandleConnection(command.Route.Visor) //nolint:errcheck - return nil } -// roomAlreadyJoined returns if the user already is member of the route he wants to join -func (h joinRemoteRouteRequestHandler) roomAlreadyJoined(command JoinRemoteRouteRequest) bool { +// routeAlreadyJoined returns if the user already is member of the route he wants to join +func (h joinRemoteRouteRequestHandler) routeAlreadyJoined(command JoinRemoteRouteRequest) bool { visor, err := h.visorRepo.GetByPK(command.Route.Visor) if err == nil { server, err := visor.GetServerByPK(command.Route.Server) diff --git a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go index 10b2f9b21..8cb175f20 100644 --- a/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go +++ b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go @@ -38,11 +38,7 @@ func (h leaveRemoteRouteRequestHandler) Handle(command LeaveRemoteRouteRequest) } if command.isLeavingP2PRouteCommand() { - err := h.leaveAndDeleteP2PRoute(command.Route) - if err != nil { - return err - } - err = h.deleteVisorIfEmpty(command.Route) + err := h.leaveP2PRoute(command.Route) if err != nil { return err } @@ -50,11 +46,7 @@ func (h leaveRemoteRouteRequestHandler) Handle(command LeaveRemoteRouteRequest) } if command.isLeavingServerRouteCommand() { - err := h.leaveAndDeleteServerRoute(command.Route) - if err != nil { - return err - } - err = h.deleteVisorIfEmpty(command.Route) + err := h.leaveServerRoute(command.Route) if err != nil { return err } @@ -62,20 +54,16 @@ func (h leaveRemoteRouteRequestHandler) Handle(command LeaveRemoteRouteRequest) } if command.isLeavingRoomRouteCommand() { - err := h.leaveAndDeleteRoomRoute(command.Route) + err := h.leaveRoomRoute(command.Route) if err != nil { return err } - err = h.deleteServerIfEmpty(command.Route) + err = h.leaveServerIfEmpty(command.Route) if err != nil { return err } - err = h.deleteVisorIfEmpty(command.Route) - if err != nil { - return err - } return nil } return nil @@ -109,7 +97,7 @@ func (c LeaveRemoteRouteRequest) isLeavingRoomRouteCommand() bool { return c.Route.IsRoomRoute() } -func (h leaveRemoteRouteRequestHandler) leaveAndDeleteP2PRoute(route util.PKRoute) error { +func (h leaveRemoteRouteRequestHandler) leaveP2PRoute(route util.PKRoute) error { visor, err := h.visorRepo.GetByPK(route.Visor) if err != nil { return err @@ -120,16 +108,12 @@ func (h leaveRemoteRouteRequestHandler) leaveAndDeleteP2PRoute(route util.PKRout if err != nil { return err } - err = visor.DeleteP2P() - if err != nil { - return err - } } return h.visorRepo.Set(*visor) } -func (h leaveRemoteRouteRequestHandler) leaveAndDeleteServerRoute(route util.PKRoute) error { +func (h leaveRemoteRouteRequestHandler) leaveServerRoute(route util.PKRoute) error { visor, err := h.visorRepo.GetByPK(route.Visor) if err != nil { return err @@ -145,15 +129,10 @@ func (h leaveRemoteRouteRequestHandler) leaveAndDeleteServerRoute(route util.PKR fmt.Println(err) } - err = visor.DeleteServer(route.Server) - if err != nil { - return err - } - return h.visorRepo.Set(*visor) } -func (h leaveRemoteRouteRequestHandler) leaveAndDeleteRoomRoute(route util.PKRoute) error { +func (h leaveRemoteRouteRequestHandler) leaveRoomRoute(route util.PKRoute) error { visor, err := h.visorRepo.GetByPK(route.Visor) if err != nil { return err @@ -174,33 +153,10 @@ func (h leaveRemoteRouteRequestHandler) leaveAndDeleteRoomRoute(route util.PKRou fmt.Println(err) } - err = server.DeleteRoom(route.Room) - if err != nil { - return err - } - - err = visor.SetServer(*server) - if err != nil { - return err - } - - return h.visorRepo.Set(*visor) -} - -func (h leaveRemoteRouteRequestHandler) deleteVisorIfEmpty(route util.PKRoute) error { - visor, err := h.visorRepo.GetByPK(route.Visor) - if err != nil { - return err - } - - if len(visor.GetAllServer()) == 0 && visor.P2PIsEmpty() { - return h.visorRepo.Delete(route.Visor) - } - return nil } -func (h leaveRemoteRouteRequestHandler) deleteServerIfEmpty(route util.PKRoute) error { +func (h leaveRemoteRouteRequestHandler) leaveServerIfEmpty(route util.PKRoute) error { visor, err := h.visorRepo.GetByPK(route.Visor) if err != nil { return err @@ -213,17 +169,14 @@ func (h leaveRemoteRouteRequestHandler) deleteServerIfEmpty(route util.PKRoute) if len(server.GetAllRooms()) == 0 { //Prepare ServerRoute - serverroute := util.NewServerRoute(route.Server, route.Server) + serverroute := util.NewServerRoute(route.Visor, route.Server) // Send LeaveChatMessage to remote server err = h.ms.SendLeaveRouteMessage(serverroute) if err != nil { return err } - err = visor.DeleteServer(route.Server) - if err != nil { - return err - } - return h.visorRepo.Set(*visor) + + return nil } return nil diff --git a/cmd/apps/skychat/internal/app/messenger/messenger.go b/cmd/apps/skychat/internal/app/messenger/messenger.go index a6d884af6..797c18cf4 100644 --- a/cmd/apps/skychat/internal/app/messenger/messenger.go +++ b/cmd/apps/skychat/internal/app/messenger/messenger.go @@ -10,6 +10,7 @@ import ( // Service interface is the interface to the service type Service interface { HandleConnection(pk cipher.PubKey) + DeleteConnFromHandled(pk cipher.PubKey) error //TODO: refactor to better handling -> this is not beautiful Listen() //only used as client/p2p diff --git a/cmd/apps/skychat/internal/app/notification/notification.go b/cmd/apps/skychat/internal/app/notification/notification.go index 43b3e6a3d..4df967a07 100644 --- a/cmd/apps/skychat/internal/app/notification/notification.go +++ b/cmd/apps/skychat/internal/app/notification/notification.go @@ -6,7 +6,6 @@ import ( "fmt" "github.com/skycoin/skywire-utilities/pkg/cipher" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) @@ -31,7 +30,7 @@ type Notification struct { } // NewMsgNotification notifies the user of a new message -func NewMsgNotification(route util.PKRoute, msg message.Message) Notification { +func NewMsgNotification(route util.PKRoute) Notification { clientMsg, err := json.Marshal(map[string]string{"visorpk": route.Visor.Hex(), "serverpk": route.Server.Hex(), "roompk": route.Room.Hex()}) if err != nil { diff --git a/cmd/apps/skychat/internal/domain/chat/server.go b/cmd/apps/skychat/internal/domain/chat/server.go index 3493f4ad8..a937743d3 100644 --- a/cmd/apps/skychat/internal/domain/chat/server.go +++ b/cmd/apps/skychat/internal/domain/chat/server.go @@ -103,6 +103,19 @@ func (s *Server) GetRoomByPK(pk cipher.PubKey) (*Room, error) { return nil, fmt.Errorf("no room with pk %s found in visor %s and server %s", pk.Hex(), s.PKRoute.Visor, s.PKRoute.Server) } +func (s *Server) GetRoomByRouteOrAddNewIfNotExists(pkroute util.PKRoute) (*Room, error) { + room, err := s.GetRoomByPK(pkroute.Room) + if err != nil { + r := NewDefaultRemoteRoom(pkroute) + err = s.AddRoom(r) + if err != nil { + return nil, err + } + return &r, nil + } + return room, nil +} + // SetRoom updates the given room func (s *Server) SetRoom(room Room) error { //check if room exists diff --git a/cmd/apps/skychat/internal/domain/chat/visor.go b/cmd/apps/skychat/internal/domain/chat/visor.go index 3828fe01d..2089604fa 100644 --- a/cmd/apps/skychat/internal/domain/chat/visor.go +++ b/cmd/apps/skychat/internal/domain/chat/visor.go @@ -152,6 +152,19 @@ func (v *Visor) GetServerByPK(pk cipher.PubKey) (*Server, error) { return nil, fmt.Errorf("no server with pk %s found in visor %s", pk.Hex(), v.PK) } +func (v *Visor) GetServerByRouteOrAddNewIfNotExists(pkroute util.PKRoute) (*Server, error) { + server, err := v.GetServerByPK(pkroute.Server) + if err != nil { + s := NewDefaultServer(pkroute) + err := v.AddServer(s) + if err != nil { + return nil, err + } + return &s, nil + } + return server, nil +} + // AddMessage Adds the given message to the given visor depending on the destination of the message func (v *Visor) AddMessage(pkroute util.PKRoute, m message.Message) { if pkroute.Server == pkroute.Visor { diff --git a/cmd/apps/skychat/internal/domain/user/user.go b/cmd/apps/skychat/internal/domain/user/user.go index 10742d9b8..932b984d2 100644 --- a/cmd/apps/skychat/internal/domain/user/user.go +++ b/cmd/apps/skychat/internal/domain/user/user.go @@ -2,8 +2,6 @@ package user import ( - "fmt" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/peer" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/settings" @@ -48,7 +46,6 @@ func (u *User) SetPeerbook(p peer.Peerbook) { // NewDefaultUser returns *User func NewDefaultUser() *User { - fmt.Println("user - NewDefaultUser") u := User{} u.Info = info.NewDefaultInfo() diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index f58564cf8..1fa379c75 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -7,6 +7,7 @@ import ( "encoding/json" "fmt" "io" + "math/rand" "net" "time" @@ -23,12 +24,14 @@ import ( // MessengerService provides a netcon implementation of the Service type MessengerService struct { - ctx context.Context - ns notification.Service - cliRepo client.Repository - usrRepo user.Repository - visorRepo chat.Repository - errs chan error + ctx context.Context + ns notification.Service + cliRepo client.Repository + usrRepo user.Repository + visorRepo chat.Repository + errs chan error + conns map[cipher.PubKey]net.Conn //TODO: find better way on handling active conns + handledConns map[cipher.PubKey]net.Conn //TODO: find better way on handling active conns } // NewMessengerService constructor for MessengerService @@ -40,11 +43,72 @@ func NewMessengerService(ns notification.Service, cR client.Repository, uR user. ms.usrRepo = uR ms.visorRepo = chR + ms.conns = make(map[cipher.PubKey]net.Conn) ms.errs = make(chan error, 1) return &ms } +// HandleConnection handles the connection to the given Pubkey and incoming messages +func (ms MessengerService) HandleConnection(pk cipher.PubKey) { + + //for debug purposes: + rand.Seed(time.Now().UnixNano()) + min := 10 + max := 1000 + randomNumber := rand.Intn(max-min+1) + min + fmt.Printf("HandleConnection random number: %d \n", randomNumber) + + connection, err := ms.GetConnByPK(pk) + if err != nil { + ms.errs <- err + return + } + + if ms.ConnectionToPkHandled(pk) { + ms.errs <- fmt.Errorf("connection already handled") + return + } + + err = ms.AddConnToHandled(pk, connection) + if err != nil { + ms.errs <- err + return + } + + for { + + messageLength, err := readMessageLengthFromConnection(connection) + if err != nil { + ms.errs <- err + continue + } + + fmt.Printf("readMessageLengthFromConnection - Message Length: %d (%d)\n", messageLength, randomNumber) + + messageBytes, err := readNBytesFromConnection(*messageLength, connection) + if err != nil { + ms.errs <- err + continue + } + + fmt.Printf("readNBytesFromConnection - Message Length: %d (%d)\n", messageLength, randomNumber) + + receivedMessage, err := decodeReceivedBytesToMessage(messageBytes) + if err != nil { + ms.errs <- err + continue + } + + err = ms.handleReceivedMessage(*receivedMessage) + if err != nil { + ms.errs <- err + continue + } + } + +} + // readMessageLengthFromConnection reads a prefix message of the connection to get the length of the upcoming message func readMessageLengthFromConnection(conn net.Conn) (*uint32, error) { prefixMessage := make([]byte, 4) @@ -53,6 +117,7 @@ func readMessageLengthFromConnection(conn net.Conn) (*uint32, error) { return nil, err } messageLength := binary.BigEndian.Uint32(prefixMessage) + fmt.Printf("readMessageLengthFromConnection - Message Length: %d \n", messageLength) return &messageLength, nil } @@ -62,7 +127,7 @@ func writeMessageLengthPrefixToConnection(message []byte, conn net.Conn) error { fmt.Printf("Write prefix with %d Bytes to Conn: %s \n", len(prefix), conn.LocalAddr()) _, err := conn.Write(prefix) if err != nil { - return fmt.Errorf("failed to write prefix: %v ", err) + return fmt.Errorf("failed to write prefix: %v", err) } return nil } @@ -84,56 +149,13 @@ func readNBytesFromConnection(n uint32, conn net.Conn) ([]byte, error) { } receivedBytes = append(receivedBytes, packetBuffer[:packetSize]...) recievedBytesCounter += packetSize - fmt.Printf("Data: %d/%d (PacketSize: %d) \n", recievedBytesCounter, n, packetSize) + fmt.Printf("Data: %d/%d (PacketSize: %d) \n", recievedBytesCounter, n, packetSize) } fmt.Printf("Received %d bytes \n", recievedBytesCounter) return receivedBytes, nil } -// HandleConnection handles the connection to the given Pubkey and incoming messages -func (ms MessengerService) HandleConnection(pk cipher.PubKey) { - - chatClient, err := ms.cliRepo.GetClient() - if err != nil { - ms.errs <- err - return - } - - connection, err := chatClient.GetConnByPK(pk) - if err != nil { - ms.errs <- err - return - } - - for { - - messageLength, err := readMessageLengthFromConnection(connection) - if err != nil { - ms.errs <- err - continue - } - - messageBytes, err := readNBytesFromConnection(*messageLength, connection) - if err != nil { - ms.errs <- err - continue - } - - receivedMessage, err := decodeReceivedBytesToMessage(messageBytes) - if err != nil { - ms.errs <- err - continue - } - - err = ms.handleReceivedMessage(*receivedMessage) - if err != nil { - ms.errs <- err - continue - } - } -} - // handleReceivedMessage handles a received message func (ms MessengerService) handleReceivedMessage(receivedMessage message.Message) error { chatClient, err := ms.cliRepo.GetClient() @@ -200,16 +222,6 @@ func (ms MessengerService) DialPubKey(pk cipher.PubKey) (net.Conn, error) { return nil, err } - err = chatClient.AddConn(pk, conn) - if err != nil { - return nil, err - } - - err = ms.cliRepo.SetClient(*chatClient) - if err != nil { - return nil, err - } - return conn, nil } @@ -223,67 +235,24 @@ func (ms MessengerService) sendMessageAndDontSaveItToDatabase(pkroute util.PKRou return ms.sendMessage(pkroute, m, false) } -// sendMessage sends a message to the given route -func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, addToDatabase bool) error { - - v, err := ms.visorRepo.GetByPK(pkroute.Visor) - if err != nil { - var v2 chat.Visor - //visor doesn't exist so we add a new remote route - if pkroute.Visor == pkroute.Server { // --> P2P remote route - v2 = chat.NewDefaultP2PVisor(pkroute.Visor) - } else { - v2 = chat.NewDefaultVisor(pkroute) - } - err2 := ms.visorRepo.Add(v2) - if err2 != nil { - return err2 - } - v = &v2 - fmt.Printf("New skychat added: %s\n", pkroute.String()) - } - - // if the message is a p2p message we have to check if the p2p room exists in the server - if pkroute.Visor == pkroute.Server { - //maybe we already have a visor, but not yet a p2p-room so check if we have that. - if v.P2PIsEmpty() { - p2p := chat.NewDefaultP2PRoom(pkroute.Visor) - err = v.AddP2P(p2p) - if err != nil { - return err - } - fmt.Printf("New P2P room added: %s\n", pkroute.String()) - } - } else { - // the message we want to send is a server / room message - server, err := v.GetServerByPK(pkroute.Server) +func addP2PIfEmpty(v *chat.Visor) error { + if v.P2PIsEmpty() { + p2p := chat.NewDefaultP2PRoom(v.GetPK()) + err := v.AddP2P(p2p) if err != nil { - s := chat.NewDefaultServer(pkroute) - err = v.AddServer(s) - if err != nil { - return err - } - fmt.Printf("New Server added: %s\n", pkroute.String()) - } else { - //the server exists so we have to check if the room already exists - _, err := server.GetRoomByPK(pkroute.Room) - if err != nil { - r := chat.NewDefaultRemoteRoom(pkroute) - err = server.AddRoom(r) - if err != nil { - return err - } - err = v.SetServer(*server) - if err != nil { - return err - } - fmt.Printf("New Room added: %s\n", pkroute.String()) - } + return err } - + fmt.Printf("New P2P room added to visor %s\n", v.GetPK().String()) } + return nil +} - chatClient, err := ms.cliRepo.GetClient() +// sendMessage sends a message to the given route +// +// if addToDatabase is true the message will be saved locally, otherwise not. +func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, addToDatabase bool) error { + + v, err := ms.getVisorAndSetupIfNecessary(pkroute) if err != nil { return err } @@ -297,12 +266,19 @@ func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, return fmt.Errorf("failed to marshal json: %v ", err) } - conn, err := chatClient.GetConnByPK(m.Dest.Visor) + conn, err := ms.GetConnByPK(m.Dest.Visor) if err != nil { conn, err = ms.DialPubKey(m.Dest.Visor) if err != nil { return err } + err = ms.AddConn(pkroute.Visor, conn) + if err != nil { + return err + } + fmt.Printf("added conn %s %s\n", conn.RemoteAddr().String(), conn.RemoteAddr().Network()) + + go ms.HandleConnection(pkroute.Visor) //nolint:errcheck } err = writeMessageLengthPrefixToConnection(bytes, conn) @@ -327,6 +303,63 @@ func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, return nil } +func (ms MessengerService) getVisorAndSetupIfNecessary(pkroute util.PKRoute) (*chat.Visor, error) { + v, err := ms.getExistingVisorOrAddNewIfNotExists(pkroute) + if err != nil { + return nil, err + } + + if pkroute.IsP2PRoute() { + err = addP2PIfEmpty(v) + if err != nil { + return nil, err + } + } else { + server, err := v.GetServerByRouteOrAddNewIfNotExists(pkroute) + if err != nil { + return nil, err + } + + _, err = server.GetRoomByRouteOrAddNewIfNotExists(pkroute) + if err != nil { + return nil, err + } + + err = v.SetServer(*server) + if err != nil { + return nil, err + } + } + return v, nil +} + +func (ms MessengerService) getExistingVisorOrAddNewIfNotExists(pkroute util.PKRoute) (*chat.Visor, error) { + + if ms.visorExists(pkroute) { + return ms.visorRepo.GetByPK(pkroute.Visor) + } + + var v chat.Visor + + if pkroute.IsP2PRoute() { + v = chat.NewDefaultP2PVisor(pkroute.Visor) + } else { + v = chat.NewDefaultVisor(pkroute) + } + + err := ms.visorRepo.Add(v) + if err != nil { + return nil, err + } + return &v, nil + +} + +func (ms MessengerService) visorExists(pkroute util.PKRoute) bool { + _, err := ms.visorRepo.GetByPK(pkroute.Visor) + return err == nil +} + // sendMessageToRemoteRoute sends the given message to a remote route (as p2p and client) func (ms MessengerService) sendMessageToRemoteRoute(msg message.Message) error { //if the message goes to p2p we save it in database, if not we wait for the remote server to send us our message @@ -343,7 +376,7 @@ func (ms MessengerService) sendMessageToRemoteRoute(msg message.Message) error { } } - n := notification.NewMsgNotification(msg.Dest, msg) + n := notification.NewMsgNotification(msg.Dest) err := ms.ns.Notify(n) if err != nil { return err @@ -376,7 +409,7 @@ func (ms MessengerService) Listen() { go func() { if err := <-ms.errs; err != nil { - fmt.Printf("Error in go HandleConnection function: %s ", err) + fmt.Printf("Error in go HandleConnection function: %s \n", err) } }() @@ -392,17 +425,75 @@ func (ms MessengerService) Listen() { fmt.Printf("Accepted skychat conn on %s from %s\n", conn.LocalAddr(), raddr.PubKey) - err = chatClient.AddConn(raddr.PubKey, conn) - if err != nil { - fmt.Println(err) - } - err = ms.cliRepo.SetClient(*chatClient) + err = ms.AddConn(raddr.PubKey, conn) if err != nil { fmt.Println(err) } + fmt.Printf("added conn %s %s\n", conn.RemoteAddr().String(), conn.RemoteAddr().Network()) //error handling in anonymous go func above go ms.HandleConnection(raddr.PubKey) + defer func() { + err = ms.DeleteConnFromHandled(raddr.PubKey) + fmt.Println(err.Error()) + }() + + } +} + +// GetConnByPK returns the conn of the given visor pk or an error if there is no open connection to the requested visor +func (ms *MessengerService) GetConnByPK(pk cipher.PubKey) (net.Conn, error) { + //check if conn already added + if conn, ok := ms.conns[pk]; ok { + return conn, nil + } + return nil, fmt.Errorf("no conn available with the requested visor") +} + +// AddConn adds the given net.Conn to the map to keep track of active connections +func (ms *MessengerService) AddConn(pk cipher.PubKey, conn net.Conn) error { + //check if conn already added + if _, ok := ms.conns[pk]; ok { + return fmt.Errorf("conn already added") + } + ms.conns[pk] = conn + return nil +} + +// DeleteConn removes the given net.Conn from the map +func (ms *MessengerService) DeleteConn(pk cipher.PubKey) error { + //check if conn is added + if _, ok := ms.conns[pk]; ok { + delete(ms.conns, pk) + return nil + } + return fmt.Errorf("pk has no connection") //? handle as error? +} + +// ConnectionToPkExists returns if a connection to the given pk is saved inside conns +func (ms *MessengerService) ConnectionToPkHandled(pk cipher.PubKey) bool { + if _, ok := ms.handledConns[pk]; ok { + return true + } + return false +} + +// AddConnToHandled adds the given net.Conn to the map to keep track of active connections +func (ms *MessengerService) AddConnToHandled(pk cipher.PubKey, conn net.Conn) error { + //check if conn already added + if _, ok := ms.handledConns[pk]; ok { + return fmt.Errorf("conn already added") + } + ms.conns[pk] = conn + return nil +} +// DeleteConnFromHandled removes the given net.Conn from the map +func (ms *MessengerService) DeleteConnFromHandled(pk cipher.PubKey) error { + //check if conn is added + if _, ok := ms.handledConns[pk]; ok { + delete(ms.handledConns, pk) + return nil } + return fmt.Errorf("pk has no connection") //? handle as error? } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go index aa7d52c78..6f8eb814d 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go @@ -174,7 +174,7 @@ func (ms MessengerService) handleLocalServerConnMsgType(visor *chat.Visor, m mes //add remote peer to server err = server.AddMember(*dummyPeer) if err != nil { - return err + fmt.Println(err) } //add remote peer to room err = room.AddMember(*dummyPeer) @@ -654,7 +654,7 @@ func (ms MessengerService) handleLocalServerInfoMsgType(v *chat.Visor, m message } //notify about new info message - n := notification.NewMsgNotification(pkroute, m) + n := notification.NewMsgNotification(pkroute) err = ms.ns.Notify(n) if err != nil { return err @@ -711,7 +711,7 @@ func (ms MessengerService) handleLocalRoomTextMsgType(visor *chat.Visor, m messa } //notify about a new TextMessage - n := notification.NewMsgNotification(pkroute, m) + n := notification.NewMsgNotification(pkroute) err = ms.ns.Notify(n) if err != nil { return err @@ -795,7 +795,7 @@ func (ms MessengerService) sendLocalRouteInfoToPeer(pkroute util.PKRoute, dest u } //notify about sent text message - n := notification.NewMsgNotification(pkroute, m) + n := notification.NewMsgNotification(pkroute) err = ms.ns.Notify(n) if err != nil { return err diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go index 03c012810..66d7881eb 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go @@ -206,7 +206,7 @@ func (ms MessengerService) handleP2PConnMsgType(m message.Message) error { } //notify that we received an accept message - n := notification.NewMsgNotification(pkroute, m) + n := notification.NewMsgNotification(pkroute) err = ms.ns.Notify(n) if err != nil { return err @@ -231,7 +231,7 @@ func (ms MessengerService) handleP2PConnMsgType(m message.Message) error { return err } - n := notification.NewMsgNotification(pkroute, m) + n := notification.NewMsgNotification(pkroute) err = ms.ns.Notify(n) if err != nil { return err @@ -251,7 +251,7 @@ func (ms MessengerService) handleP2PConnMsgType(m message.Message) error { } //notify that we received an accept message - n := notification.NewMsgNotification(pkroute, m) + n := notification.NewMsgNotification(pkroute) err = ms.ns.Notify(n) if err != nil { return err @@ -294,7 +294,7 @@ func (ms MessengerService) handleP2PInfoMsgType(v *chat.Visor, m message.Message } //notify about new info message - n := notification.NewMsgNotification(pkroute, m) + n := notification.NewMsgNotification(pkroute) err = ms.ns.Notify(n) if err != nil { return err @@ -315,7 +315,7 @@ func (ms MessengerService) handleP2PTextMsgType(m message.Message) error { fmt.Println("---------------------------------------------------------------------------------------------------") //notify about a new TextMessage - n := notification.NewMsgNotification(pkroute, m) + n := notification.NewMsgNotification(pkroute) err := ms.ns.Notify(n) if err != nil { return err diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go index a36560b34..89840b6f4 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go @@ -25,12 +25,18 @@ func (ms MessengerService) handleRemoteServerMessage(m message.Message) { ms.errs <- fmt.Errorf("message dumped: no member of remote, visor not even known") return } - _, err = visor.GetServerByPK(pkroute.Server) + server, err := visor.GetServerByPK(pkroute.Server) if err != nil { ms.errs <- fmt.Errorf("message dumped: no member of remote server") return } + _, err = server.GetRoomByPK(pkroute.Room) + if err != nil { + ms.errs <- fmt.Errorf("message dumped: no member of remote room") + return + } + switch m.GetMessageType() { case message.ConnMsgType: //add the message to the visor and update repository @@ -102,7 +108,7 @@ func (ms MessengerService) handleRemoteRoomConnMsgType(m message.Message) error switch m.MsgSubtype { case message.ConnMsgTypeAccept: //notify that we received an accept message - n := notification.NewMsgNotification(m.Root, m) + n := notification.NewMsgNotification(m.Root) err := ms.ns.Notify(n) if err != nil { return err @@ -116,7 +122,7 @@ func (ms MessengerService) handleRemoteRoomConnMsgType(m message.Message) error case message.ConnMsgTypeReject: //notify that we send a reject message - n := notification.NewMsgNotification(m.Root, m) + n := notification.NewMsgNotification(m.Root) err := ms.ns.Notify(n) if err != nil { return err @@ -124,6 +130,11 @@ func (ms MessengerService) handleRemoteRoomConnMsgType(m message.Message) error //? do we have to delete something here? //? maybe we don't even have to notify the user, that a rejection happened? return nil + case message.ConnMsgTypeLeave: + err = ms.removeOwnPkfromRoomForMessageFiltering(m) + if err != nil { + return err + } case message.ConnMsgTypeDelete: //? do we have to delete something here? --> maybe the peer wants to save the chat history and not delete it, therefore we would have to add some kind of flag or so, that //? stops the peers from sending any messages to the deleted chat/server @@ -134,6 +145,39 @@ func (ms MessengerService) handleRemoteRoomConnMsgType(m message.Message) error } +func (ms MessengerService) removeOwnPkfromRoomForMessageFiltering(m message.Message) error { + visor, err := ms.visorRepo.GetByPK(m.GetRootVisor()) + if err != nil { + return err + } + server, err := visor.GetServerByPK(m.GetRootServer()) + if err != nil { + return err + } + room, err := server.GetRoomByPK(m.GetRootRoom()) + if err != nil { + return err + } + err = room.DeleteMember(m.GetDestinationVisor()) + if err != nil { + return err + } + err = server.SetRoom(*room) + if err != nil { + return err + } + err = visor.SetServer(*server) + if err != nil { + return err + } + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + + return nil +} + // handleRemoteRoomInfoMsgType handles messages of type info of peers func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message.Message) error { fmt.Println("handleRemoteRoomInfoMsgType") @@ -168,7 +212,7 @@ func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message. } //notify about new info message - n := notification.NewMsgNotification(pkroute, m) + n := notification.NewMsgNotification(pkroute) err = ms.ns.Notify(n) if err != nil { return err @@ -208,7 +252,7 @@ func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message. } //notify about new info message - n := notification.NewMsgNotification(pkroute, m) + n := notification.NewMsgNotification(pkroute) err = ms.ns.Notify(n) if err != nil { return err @@ -248,7 +292,7 @@ func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message. } //notify about new info message - n := notification.NewMsgNotification(pkroute, m) + n := notification.NewMsgNotification(pkroute) err = ms.ns.Notify(n) if err != nil { return err @@ -261,13 +305,15 @@ func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message. func (ms MessengerService) handleRemoteRoomTextMsgType(c *chat.Visor, m message.Message) error { fmt.Println("handleRemoteRoomTextMsgType") + pkroute := util.NewRoomRoute(m.GetRootVisor(), m.GetRootServer(), m.GetRootRoom()) + fmt.Println("---------------------------------------------------------------------------------------------------") fmt.Printf("TextMessage: \n") fmt.Printf("Text: %s \n", m.Message) fmt.Println("---------------------------------------------------------------------------------------------------") //notify about a new TextMessage - n := notification.NewMsgNotification(util.NewP2PRoute(c.GetPK()), message.NewTextMessage(m.Root.Visor, m.Dest, m.Message)) + n := notification.NewMsgNotification(pkroute) err := ms.ns.Notify(n) if err != nil { return err diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_send_messages.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_send_messages.go index 491dae232..888345518 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_send_messages.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_send_messages.go @@ -318,7 +318,7 @@ func (ms MessengerService) SendLeaveRouteMessage(pkroute util.PKRoute) error { root := util.NewP2PRoute(usr.GetInfo().GetPK()) m := message.NewChatLeaveMessage(root, pkroute) - err = ms.sendMessageAndSaveItToDatabase(pkroute, m) + err = ms.sendMessageAndDontSaveItToDatabase(pkroute, m) if err != nil { return err } diff --git a/cmd/apps/skychat/skychat.go b/cmd/apps/skychat/skychat.go index d2d2ffca6..21e394458 100644 --- a/cmd/apps/skychat/skychat.go +++ b/cmd/apps/skychat/skychat.go @@ -18,4 +18,4 @@ func main() { // cd .. // mingw32-make build-windows // .\skywire-cli.exe config gen -i -r -o .\skywire-config.json -// .\skywire-visor.exe -c .\skywire-config.json --loglvl debug +// .\build\skywire-visor.exe -c .\skywire-config.json --loglvl debug From 1f75d5d7586aaede0f0e877d3be4168c464f5a2c Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Wed, 5 Jul 2023 16:58:37 +0200 Subject: [PATCH 52/72] fix make check errs --- .../get_all_messages_from_room_by_route.go | 4 ++-- .../app/chat/queries/get_room_by_route.go | 4 ++-- .../skychat/internal/domain/chat/server.go | 1 + cmd/apps/skychat/internal/domain/chat/visor.go | 1 + .../messenger/netcon/messenger_service.go | 18 +++--------------- .../netcon/messenger_service_remote_server.go | 6 +++--- 6 files changed, 12 insertions(+), 22 deletions(-) diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_room_by_route.go b/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_room_by_route.go index d547290a4..4050b0c27 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_room_by_route.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_room_by_route.go @@ -35,9 +35,9 @@ func NewGetAllMessagesFromRoomRequestHandler(visorRepo chat.Repository) GetAllMe func (h getAllMessagesFromRoomRequestHandler) Handle(query GetAllMessagesFromRoomRequest) (GetAllMessagesFromRoomResult, error) { if query.isP2PRequest() { return h.getP2PMessagesResult(query) - } else { - return h.getRoomMessagesResult(query) } + return h.getRoomMessagesResult(query) + } func (r *GetAllMessagesFromRoomRequest) isP2PRequest() bool { diff --git a/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go b/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go index 5032476fa..94e4e2751 100644 --- a/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go +++ b/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go @@ -49,9 +49,9 @@ func NewGetRoomByRouteRequestHandler(visorRepo chat.Repository) GetRoomByRouteRe func (h getRoomByRouteRequestHandler) Handle(query GetRoomByRouteRequest) (GetRoomByRouteResult, error) { if query.isP2PRequest() { return h.getP2PRoomResult(query) - } else { - return h.getRouteRoomResult(query) } + return h.getRouteRoomResult(query) + } func (r *GetRoomByRouteRequest) isP2PRequest() bool { diff --git a/cmd/apps/skychat/internal/domain/chat/server.go b/cmd/apps/skychat/internal/domain/chat/server.go index a937743d3..0a3adfb72 100644 --- a/cmd/apps/skychat/internal/domain/chat/server.go +++ b/cmd/apps/skychat/internal/domain/chat/server.go @@ -103,6 +103,7 @@ func (s *Server) GetRoomByPK(pk cipher.PubKey) (*Room, error) { return nil, fmt.Errorf("no room with pk %s found in visor %s and server %s", pk.Hex(), s.PKRoute.Visor, s.PKRoute.Server) } +// GetRoomByRouteOrAddNewIfNotExists does exactly what it's named func (s *Server) GetRoomByRouteOrAddNewIfNotExists(pkroute util.PKRoute) (*Room, error) { room, err := s.GetRoomByPK(pkroute.Room) if err != nil { diff --git a/cmd/apps/skychat/internal/domain/chat/visor.go b/cmd/apps/skychat/internal/domain/chat/visor.go index 2089604fa..b4f8f2f18 100644 --- a/cmd/apps/skychat/internal/domain/chat/visor.go +++ b/cmd/apps/skychat/internal/domain/chat/visor.go @@ -152,6 +152,7 @@ func (v *Visor) GetServerByPK(pk cipher.PubKey) (*Server, error) { return nil, fmt.Errorf("no server with pk %s found in visor %s", pk.Hex(), v.PK) } +// GetServerByRouteOrAddNewIfNotExists does what it is named func (v *Visor) GetServerByRouteOrAddNewIfNotExists(pkroute util.PKRoute) (*Server, error) { server, err := v.GetServerByPK(pkroute.Server) if err != nil { diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go index 1fa379c75..49a4ec969 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go @@ -7,7 +7,6 @@ import ( "encoding/json" "fmt" "io" - "math/rand" "net" "time" @@ -52,13 +51,6 @@ func NewMessengerService(ns notification.Service, cR client.Repository, uR user. // HandleConnection handles the connection to the given Pubkey and incoming messages func (ms MessengerService) HandleConnection(pk cipher.PubKey) { - //for debug purposes: - rand.Seed(time.Now().UnixNano()) - min := 10 - max := 1000 - randomNumber := rand.Intn(max-min+1) + min - fmt.Printf("HandleConnection random number: %d \n", randomNumber) - connection, err := ms.GetConnByPK(pk) if err != nil { ms.errs <- err @@ -84,16 +76,12 @@ func (ms MessengerService) HandleConnection(pk cipher.PubKey) { continue } - fmt.Printf("readMessageLengthFromConnection - Message Length: %d (%d)\n", messageLength, randomNumber) - messageBytes, err := readNBytesFromConnection(*messageLength, connection) if err != nil { ms.errs <- err continue } - fmt.Printf("readNBytesFromConnection - Message Length: %d (%d)\n", messageLength, randomNumber) - receivedMessage, err := decodeReceivedBytesToMessage(messageBytes) if err != nil { ms.errs <- err @@ -470,7 +458,7 @@ func (ms *MessengerService) DeleteConn(pk cipher.PubKey) error { return fmt.Errorf("pk has no connection") //? handle as error? } -// ConnectionToPkExists returns if a connection to the given pk is saved inside conns +// ConnectionToPkHandled returns if a connection to the given pk is handled in a go routine func (ms *MessengerService) ConnectionToPkHandled(pk cipher.PubKey) bool { if _, ok := ms.handledConns[pk]; ok { return true @@ -478,7 +466,7 @@ func (ms *MessengerService) ConnectionToPkHandled(pk cipher.PubKey) bool { return false } -// AddConnToHandled adds the given net.Conn to the map to keep track of active connections +// AddConnToHandled adds the given net.Conn to the map to keep track of handled connections func (ms *MessengerService) AddConnToHandled(pk cipher.PubKey, conn net.Conn) error { //check if conn already added if _, ok := ms.handledConns[pk]; ok { @@ -488,7 +476,7 @@ func (ms *MessengerService) AddConnToHandled(pk cipher.PubKey, conn net.Conn) er return nil } -// DeleteConnFromHandled removes the given net.Conn from the map +// DeleteConnFromHandled removes the given net.Conn from the handledConns map func (ms *MessengerService) DeleteConnFromHandled(pk cipher.PubKey) error { //check if conn is added if _, ok := ms.handledConns[pk]; ok { diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go index 89840b6f4..b00fe4308 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go @@ -73,7 +73,7 @@ func (ms MessengerService) handleRemoteServerMessage(m message.Message) { return } //handle the message - err := ms.handleRemoteRoomTextMsgType(visor, m) + err := ms.handleRemoteRoomTextMsgType(m) if err != nil { ms.errs <- err return @@ -301,8 +301,8 @@ func (ms MessengerService) handleRemoteRoomInfoMsgType(v *chat.Visor, m message. return nil } -// handleRemoteRoomTextMstType handles messages of type text of the remote chat -func (ms MessengerService) handleRemoteRoomTextMsgType(c *chat.Visor, m message.Message) error { +// handleRemoteRoomTextMsgType handles messages of type text of the remote chat +func (ms MessengerService) handleRemoteRoomTextMsgType(m message.Message) error { fmt.Println("handleRemoteRoomTextMsgType") pkroute := util.NewRoomRoute(m.GetRootVisor(), m.GetRootServer(), m.GetRootRoom()) From edadf7e5a4876347a19491165644b654a64731dd Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Wed, 26 Jul 2023 23:45:13 +0200 Subject: [PATCH 53/72] fix make check errs had to update to golanci-lint > 1.52.1 to catch new errs --- cmd/apps/skychat/internal/app/chat/services.go | 3 +-- cmd/apps/skychat/internal/app/services.go | 5 ++--- cmd/apps/skychat/internal/domain/chat/room.go | 2 +- cmd/apps/skychat/internal/domain/chat/server.go | 2 +- .../internal/inputports/cli/chat/send/textmessage.go | 2 +- cmd/apps/skychat/internal/inputports/cli/root.go | 1 - cmd/apps/skychat/internal/inputports/http/user/handler.go | 6 +++--- cmd/apps/skychat/internal/inputports/rpc/chat/handler.go | 2 +- 8 files changed, 10 insertions(+), 13 deletions(-) diff --git a/cmd/apps/skychat/internal/app/chat/services.go b/cmd/apps/skychat/internal/app/chat/services.go index 4b543f927..0312b1198 100644 --- a/cmd/apps/skychat/internal/app/chat/services.go +++ b/cmd/apps/skychat/internal/app/chat/services.go @@ -7,7 +7,6 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) @@ -42,7 +41,7 @@ type ChatServices struct { } // NewServices Bootstraps Application Layer dependencies -func NewServices(cliRepo client.Repository, visorRepo chat.Repository, userRepo user.Repository, ms messenger.Service, ns notification.Service) ChatServices { +func NewServices(visorRepo chat.Repository, userRepo user.Repository, ms messenger.Service, ns notification.Service) ChatServices { return ChatServices{ Queries: Queries{ GetRoomByRouteHandler: queries.NewGetRoomByRouteRequestHandler(visorRepo), diff --git a/cmd/apps/skychat/internal/app/services.go b/cmd/apps/skychat/internal/app/services.go index 2f28dda3d..6c22f97ad 100644 --- a/cmd/apps/skychat/internal/app/services.go +++ b/cmd/apps/skychat/internal/app/services.go @@ -7,7 +7,6 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" userservices "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/user" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" ) @@ -22,9 +21,9 @@ type Services struct { } // NewServices Bootstraps Application Layer dependencies -func NewServices(cliRepo client.Repository, usrRepo user.Repository, visorRepo chat.Repository, notifyService notification.Service, ms messenger.Service) Services { +func NewServices(usrRepo user.Repository, visorRepo chat.Repository, notifyService notification.Service, ms messenger.Service) Services { return Services{ NotificationService: notifyService, - ChatServices: chatservices.NewServices(cliRepo, visorRepo, usrRepo, ms, notifyService), + ChatServices: chatservices.NewServices(visorRepo, usrRepo, ms, notifyService), UserServices: userservices.NewServices(usrRepo, ms, visorRepo)} } diff --git a/cmd/apps/skychat/internal/domain/chat/room.go b/cmd/apps/skychat/internal/domain/chat/room.go index 41f926891..38e750ee4 100644 --- a/cmd/apps/skychat/internal/domain/chat/room.go +++ b/cmd/apps/skychat/internal/domain/chat/room.go @@ -247,7 +247,7 @@ func (r *Room) DeleteFromWhitelist(pk cipher.PubKey) error { } // GetWhitelist returns all whitelisted members/peers -func (r *Room) GetWhitelist(pk cipher.PubKey) map[cipher.PubKey]bool { +func (r *Room) GetWhitelist() map[cipher.PubKey]bool { return r.Whitelist } diff --git a/cmd/apps/skychat/internal/domain/chat/server.go b/cmd/apps/skychat/internal/domain/chat/server.go index 0a3adfb72..21579e221 100644 --- a/cmd/apps/skychat/internal/domain/chat/server.go +++ b/cmd/apps/skychat/internal/domain/chat/server.go @@ -316,7 +316,7 @@ func (s *Server) DeleteFromWhitelist(pk cipher.PubKey) error { } // GetWhitelist returns all whitelisted members/peers -func (s *Server) GetWhitelist(pk cipher.PubKey) map[cipher.PubKey]bool { +func (s *Server) GetWhitelist() map[cipher.PubKey]bool { return s.Whitelist } diff --git a/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go b/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go index ae2e563d6..345743d72 100644 --- a/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go +++ b/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go @@ -32,7 +32,7 @@ var textMessageCmd = &cobra.Command{ } // ParsePK parses a public key -func ParsePK(cmdFlags *pflag.FlagSet, name, v string) cipher.PubKey { +func ParsePK(_ *pflag.FlagSet, name, v string) cipher.PubKey { var pk cipher.PubKey err := pk.Set(v) if err != nil { diff --git a/cmd/apps/skychat/internal/inputports/cli/root.go b/cmd/apps/skychat/internal/inputports/cli/root.go index d133cc80c..7c1b7a80d 100644 --- a/cmd/apps/skychat/internal/inputports/cli/root.go +++ b/cmd/apps/skychat/internal/inputports/cli/root.go @@ -40,7 +40,6 @@ var rootCmd = &cobra.Command{ }() app.AppServices = app.NewServices( - interfaceadapters.InterfaceAdapterServices.ClientRepository, interfaceadapters.InterfaceAdapterServices.UserRepository, interfaceadapters.InterfaceAdapterServices.VisorRepository, interfaceadapters.InterfaceAdapterServices.NotificationService, diff --git a/cmd/apps/skychat/internal/inputports/http/user/handler.go b/cmd/apps/skychat/internal/inputports/http/user/handler.go index 7a82e3019..01834be88 100644 --- a/cmd/apps/skychat/internal/inputports/http/user/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/user/handler.go @@ -219,7 +219,7 @@ func (c Handler) SetSettings(w http.ResponseWriter, r *http.Request) { const GetInfoURLParam = "getInfo" // GetInfo Returns the info of the user -func (c Handler) GetInfo(w http.ResponseWriter, r *http.Request) { +func (c Handler) GetInfo(w http.ResponseWriter, _ *http.Request) { info, err := c.userServices.Queries.GetUserInfoHandler.Handle() if err == nil && info == nil { w.WriteHeader(http.StatusNotFound) @@ -244,7 +244,7 @@ func (c Handler) GetInfo(w http.ResponseWriter, r *http.Request) { const GetPeerbookURLParam = "getPeerbook" // GetPeerbook returns the peerbook of the user -func (c Handler) GetPeerbook(w http.ResponseWriter, r *http.Request) { +func (c Handler) GetPeerbook(w http.ResponseWriter, _ *http.Request) { info, err := c.userServices.Queries.GetUserPeerBookHandler.Handle() if err == nil && info == nil { w.WriteHeader(http.StatusNotFound) @@ -269,7 +269,7 @@ func (c Handler) GetPeerbook(w http.ResponseWriter, r *http.Request) { const GetSettingsURLParam = "getSettings" // GetSettings Returns the settings of the user -func (c Handler) GetSettings(w http.ResponseWriter, r *http.Request) { +func (c Handler) GetSettings(w http.ResponseWriter, _ *http.Request) { settings, err := c.userServices.Queries.GetUserSettingsHandler.Handle() if err == nil && settings == nil { w.WriteHeader(http.StatusNotFound) diff --git a/cmd/apps/skychat/internal/inputports/rpc/chat/handler.go b/cmd/apps/skychat/internal/inputports/rpc/chat/handler.go index 597bc7bc4..c2e564456 100644 --- a/cmd/apps/skychat/internal/inputports/rpc/chat/handler.go +++ b/cmd/apps/skychat/internal/inputports/rpc/chat/handler.go @@ -33,7 +33,7 @@ type SendTextMessageRequestModel struct { } // SendTextMessage sends a text message to the given route -func (c Handler) SendTextMessage(r SendTextMessageRequestModel, reply *int) error { +func (c Handler) SendTextMessage(r SendTextMessageRequestModel, _ *int) error { fmt.Println("RPC: SendTextMessage via cli (rpc)") fmt.Printf("RPC: Message: %s\n v: %s\n s: %s\n r: %s\n", r.Msg, r.VisorPk.Hex(), r.ServerPk.Hex(), r.RoomPk.Hex()) From ad5892ea257520aea696b241f0369e4663270ca3 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Mon, 31 Jul 2023 23:27:30 +0200 Subject: [PATCH 54/72] fix make check errs --- .../skychat/internal/inputports/cli/chat/send/textmessage.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go b/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go index 345743d72..32b396357 100644 --- a/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go +++ b/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go @@ -32,7 +32,7 @@ var textMessageCmd = &cobra.Command{ } // ParsePK parses a public key -func ParsePK(_ *pflag.FlagSet, name, v string) cipher.PubKey { +func ParsePK(_ *pflag.FlagSet, _, v string) cipher.PubKey { var pk cipher.PubKey err := pk.Set(v) if err != nil { From 6b92e524e139871733c8adc2ad226e795527ecd1 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Wed, 30 Aug 2023 22:59:49 +0200 Subject: [PATCH 55/72] fix ipc client naming --- cmd/apps/skysocks/skysocks.go | 4 ++-- go.mod | 2 +- go.sum | 4 ++-- internal/skysocks/client.go | 2 +- internal/skysocks/server.go | 2 +- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/cmd/apps/skysocks/skysocks.go b/cmd/apps/skysocks/skysocks.go index 6ca34c066..e09d82f5c 100644 --- a/cmd/apps/skysocks/skysocks.go +++ b/cmd/apps/skysocks/skysocks.go @@ -57,10 +57,10 @@ func main() { fmt.Println("Starting serving proxy server") if runtime.GOOS == "windows" { - ipcClient, err := ipc.StartClient(visorconfig.VPNClientName, nil) + ipcClient, err := ipc.StartClient(visorconfig.SkysocksName, nil) if err != nil { setAppError(appCl, err) - print(fmt.Sprintf("Error creating ipc server for VPN client: %v\n", err)) + print(fmt.Sprintf("Error creating ipc server for skysocks client: %v\n", err)) os.Exit(1) } go srv.ListenIPC(ipcClient) diff --git a/go.mod b/go.mod index e5acf50af..0da44fe8a 100644 --- a/go.mod +++ b/go.mod @@ -18,7 +18,7 @@ require ( github.com/hashicorp/go-version v1.6.0 github.com/hashicorp/yamux v0.1.1 github.com/ivanpirog/coloredcobra v1.0.1 - github.com/james-barrow/golang-ipc v1.2.4 + github.com/james-barrow/golang-ipc v1.1.0 github.com/jaypipes/ghw v0.12.0 github.com/konsorten/go-windows-terminal-sequences v1.0.3 github.com/lib/pq v1.10.9 diff --git a/go.sum b/go.sum index 7ea7a57d5..2929eb6ae 100644 --- a/go.sum +++ b/go.sum @@ -167,8 +167,8 @@ github.com/itchyny/timefmt-go v0.1.5 h1:G0INE2la8S6ru/ZI5JecgyzbbJNs5lG1RcBqa7Jm github.com/itchyny/timefmt-go v0.1.5/go.mod h1:nEP7L+2YmAbT2kZ2HfSs1d8Xtw9LY8D2stDBckWakZ8= github.com/ivanpirog/coloredcobra v1.0.1 h1:aURSdEmlR90/tSiWS0dMjdwOvCVUeYLfltLfbgNxrN4= github.com/ivanpirog/coloredcobra v1.0.1/go.mod h1:iho4nEKcnwZFiniGSdcgdvRgZNjxm+h20acv8vqmN6Q= -github.com/james-barrow/golang-ipc v1.2.4 h1:d4NXRQxq6OWviWU8uAaob8R0YZGy/PhAkXGLpBNpkA4= -github.com/james-barrow/golang-ipc v1.2.4/go.mod h1:+egiWSbOWmiPucFGSl4GNB1YSzrVGehyl7/7pW4N8F0= +github.com/james-barrow/golang-ipc v1.1.0 h1:/195vE/wvgc4iGNQ6fn1l6W1awI4DcOTGjQeNhRlgBQ= +github.com/james-barrow/golang-ipc v1.1.0/go.mod h1:+egiWSbOWmiPucFGSl4GNB1YSzrVGehyl7/7pW4N8F0= github.com/jaypipes/ghw v0.12.0 h1:xU2/MDJfWmBhJnujHY9qwXQLs3DBsf0/Xa9vECY0Tho= github.com/jaypipes/ghw v0.12.0/go.mod h1:jeJGbkRB2lL3/gxYzNYzEDETV1ZJ56OKr+CSeSEym+g= github.com/jaypipes/pcidb v1.0.0 h1:vtZIfkiCUE42oYbJS0TAq9XSfSmcsgo9IdxSm9qzYU8= diff --git a/internal/skysocks/client.go b/internal/skysocks/client.go index c1b85b8de..b6d418f60 100644 --- a/internal/skysocks/client.go +++ b/internal/skysocks/client.go @@ -162,7 +162,7 @@ func (c *Client) close() { // ListenIPC starts named-pipe based connection server for windows or unix socket for other OSes func (c *Client) ListenIPC(client *ipc.Client) { - listenIPC(client, skyenv.SkychatName+"-client", func() { + listenIPC(client, skyenv.SkysocksName+"-client", func() { client.Close() if err := c.Close(); err != nil { print(fmt.Sprintf("Error closing skysocks-client: %v\n", err)) diff --git a/internal/skysocks/server.go b/internal/skysocks/server.go index 93b325c7c..6b437d399 100644 --- a/internal/skysocks/server.go +++ b/internal/skysocks/server.go @@ -93,7 +93,7 @@ func (s *Server) Serve(l net.Listener) error { // ListenIPC starts named-pipe based connection server for windows or unix socket in Linux/Mac func (s *Server) ListenIPC(client *ipc.Client) { - listenIPC(client, skyenv.SkychatName, func() { + listenIPC(client, skyenv.SkysocksName, func() { client.Close() if err := s.Close(); err != nil { fmt.Println("Error closing skysocks server: ", err.Error()) From 026efb61ea4bc15820e400ec4ee4f1eb1549c91a Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Wed, 30 Aug 2023 23:11:12 +0200 Subject: [PATCH 56/72] fix build path for autodetection of config gen --- cmd/skywire-cli/README.md | 2 +- cmd/skywire-cli/commands/config/gen.go | 4 ++-- pkg/skyenv/skyenv.go | 2 +- pkg/skyenv/skyenv_linux.go | 2 +- pkg/skyenv/skyenv_windows.go | 2 +- pkg/visor/visorconfig/values_windows.go | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/cmd/skywire-cli/README.md b/cmd/skywire-cli/README.md index e72d4871b..561004318 100644 --- a/cmd/skywire-cli/README.md +++ b/cmd/skywire-cli/README.md @@ -370,7 +370,7 @@ $ skywire-cli config gen -bpirxn --version 1.3.0 "service_discovery": "http://sd.skycoin.com", "apps": null, "server_addr": "localhost:5505", - "bin_path": "./apps", + "bin_path": "./build/apps", "display_node_ip": false }, "survey_whitelist": [ diff --git a/cmd/skywire-cli/commands/config/gen.go b/cmd/skywire-cli/commands/config/gen.go index 9bf3f9de9..26db626c2 100644 --- a/cmd/skywire-cli/commands/config/gen.go +++ b/cmd/skywire-cli/commands/config/gen.go @@ -1222,7 +1222,7 @@ const envfileLinux = `# #VERSION='' #-- Set app bin_path -#BINPATH='./apps' +#BINPATH='./build/apps' #-- Set server public key for proxy client to connect to #PROXYCLIENTPK='' @@ -1322,7 +1322,7 @@ const envfileWindows = `# #$VERSION='' #-- Set app bin_path -#$BINPATH='./apps' +#$BINPATH='./build/apps' #-- Set server public key for proxy client to connect to #$PROXYCLIENTPK='' diff --git a/pkg/skyenv/skyenv.go b/pkg/skyenv/skyenv.go index 2ce8e906b..e2b1c6686 100644 --- a/pkg/skyenv/skyenv.go +++ b/pkg/skyenv/skyenv.go @@ -76,7 +76,7 @@ const ( AppSrvAddr = "localhost:5505" // AppSrvAddr ... ServiceDiscUpdateInterval = time.Minute // ServiceDiscUpdateInterval ... - AppBinPath = "./apps" // AppBinPath ... + AppBinPath = "./build/apps" // AppBinPath ... LogLevel = "info" // LogLevel ... // Routing constants diff --git a/pkg/skyenv/skyenv_linux.go b/pkg/skyenv/skyenv_linux.go index a352aaeea..ed4b29f01 100644 --- a/pkg/skyenv/skyenv_linux.go +++ b/pkg/skyenv/skyenv_linux.go @@ -20,7 +20,7 @@ const ( // PackageConfig contains installation paths (for linux) func PackageConfig() PkgConfig { pkgConfig := PkgConfig{ - LauncherBinPath: "/opt/skywire/apps", + LauncherBinPath: "/opt/skywire/build/apps", LocalPath: "/opt/skywire/local", Hypervisor: Hypervisor{ DbPath: "/opt/skywire/users.db", diff --git a/pkg/skyenv/skyenv_windows.go b/pkg/skyenv/skyenv_windows.go index 8ac6adf91..d196b9362 100644 --- a/pkg/skyenv/skyenv_windows.go +++ b/pkg/skyenv/skyenv_windows.go @@ -23,7 +23,7 @@ const ( // PackageConfig contains installation paths (for windows) func PackageConfig() PkgConfig { pkgConfig := PkgConfig{ - LauncherBinPath: "C:/Program Files/Skywire/apps", + LauncherBinPath: "C:/Program Files/Skywire/build/apps", LocalPath: "C:/Program Files/Skywire/local", Hypervisor: Hypervisor{ DbPath: "C:/Program Files/Skywire/users.db", diff --git a/pkg/visor/visorconfig/values_windows.go b/pkg/visor/visorconfig/values_windows.go index 0cd63c17f..6b607cdc9 100644 --- a/pkg/visor/visorconfig/values_windows.go +++ b/pkg/visor/visorconfig/values_windows.go @@ -16,7 +16,7 @@ import ( // UserConfig contains installation paths for running skywire as the user func UserConfig() skyenv.PkgConfig { usrConfig := skyenv.PkgConfig{ - LauncherBinPath: "C:/Program Files/Skywire/apps", + LauncherBinPath: "C:/Program Files/Skywire/build/apps", LocalPath: HomePath() + "/.skywire/local", Hypervisor: skyenv.Hypervisor{ DbPath: HomePath() + "/.skywire/users.db", From 1f2f1a30e56916a9a2e2e555962776482efd939b Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Wed, 30 Aug 2023 23:15:21 +0200 Subject: [PATCH 57/72] fix skychat default flag --- cmd/skywire-cli/commands/config/gen.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/skywire-cli/commands/config/gen.go b/cmd/skywire-cli/commands/config/gen.go index 26db626c2..7e956d758 100644 --- a/cmd/skywire-cli/commands/config/gen.go +++ b/cmd/skywire-cli/commands/config/gen.go @@ -895,7 +895,7 @@ var genConfigCmd = &cobra.Command{ Binary: visorconfig.SkychatName, AutoStart: true, Port: routing.Port(skyenv.SkychatPort), - Args: []string{"-addr", visorconfig.SkychatAddr}, + Args: []string{"--httpport=" + visorconfig.SkychatAddr}, }, { Name: visorconfig.SkysocksName, From 70a2c8c4cda4357556f3d992596e4bec880285f5 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Wed, 30 Aug 2023 23:17:34 +0200 Subject: [PATCH 58/72] add dependencies for skychat --- go.mod | 2 + go.sum | 4 + .../ActiveState/termtest/conpty/term_other.go | 1 - .../termtest/conpty/term_windows.go | 1 - .../Azure/go-ansiterm/winterm/ansi.go | 1 - .../Azure/go-ansiterm/winterm/api.go | 1 - .../go-ansiterm/winterm/attr_translation.go | 1 - .../go-ansiterm/winterm/cursor_helpers.go | 1 - .../go-ansiterm/winterm/erase_helpers.go | 1 - .../go-ansiterm/winterm/scroll_helper.go | 1 - .../Azure/go-ansiterm/winterm/utilities.go | 1 - .../go-ansiterm/winterm/win_event_handler.go | 1 - .../StackExchange/wmi/swbemservices.go | 1 - vendor/github.com/StackExchange/wmi/wmi.go | 1 - vendor/github.com/boltdb/bolt/.gitignore | 4 + vendor/github.com/boltdb/bolt/LICENSE | 20 + vendor/github.com/boltdb/bolt/Makefile | 18 + vendor/github.com/boltdb/bolt/README.md | 916 +++++++++++++++ vendor/github.com/boltdb/bolt/appveyor.yml | 18 + vendor/github.com/boltdb/bolt/bolt_386.go | 10 + vendor/github.com/boltdb/bolt/bolt_amd64.go | 10 + vendor/github.com/boltdb/bolt/bolt_arm.go | 28 + vendor/github.com/boltdb/bolt/bolt_arm64.go | 12 + vendor/github.com/boltdb/bolt/bolt_linux.go | 10 + vendor/github.com/boltdb/bolt/bolt_openbsd.go | 27 + vendor/github.com/boltdb/bolt/bolt_ppc.go | 9 + vendor/github.com/boltdb/bolt/bolt_ppc64.go | 12 + vendor/github.com/boltdb/bolt/bolt_ppc64le.go | 12 + vendor/github.com/boltdb/bolt/bolt_s390x.go | 12 + vendor/github.com/boltdb/bolt/bolt_unix.go | 89 ++ .../boltdb/bolt/bolt_unix_solaris.go | 90 ++ vendor/github.com/boltdb/bolt/bolt_windows.go | 144 +++ .../github.com/boltdb/bolt/boltsync_unix.go | 8 + vendor/github.com/boltdb/bolt/bucket.go | 777 ++++++++++++ vendor/github.com/boltdb/bolt/cursor.go | 400 +++++++ vendor/github.com/boltdb/bolt/db.go | 1039 +++++++++++++++++ vendor/github.com/boltdb/bolt/doc.go | 44 + vendor/github.com/boltdb/bolt/errors.go | 71 ++ vendor/github.com/boltdb/bolt/freelist.go | 252 ++++ vendor/github.com/boltdb/bolt/node.go | 604 ++++++++++ vendor/github.com/boltdb/bolt/page.go | 197 ++++ vendor/github.com/boltdb/bolt/tx.go | 684 +++++++++++ .../github.com/davecgh/go-spew/spew/bypass.go | 1 - .../davecgh/go-spew/spew/bypasssafe.go | 1 - .../github.com/gen2brain/dlgs/color_darwin.go | 1 - vendor/github.com/gen2brain/dlgs/color_js.go | 1 - .../github.com/gen2brain/dlgs/color_linux.go | 1 - .../gen2brain/dlgs/color_unsupported.go | 1 - .../gen2brain/dlgs/color_windows.go | 1 - .../github.com/gen2brain/dlgs/date_darwin.go | 1 - vendor/github.com/gen2brain/dlgs/date_js.go | 1 - .../github.com/gen2brain/dlgs/date_linux.go | 1 - .../gen2brain/dlgs/date_unsupported.go | 1 - .../github.com/gen2brain/dlgs/date_windows.go | 1 - .../github.com/gen2brain/dlgs/dlgs_darwin.go | 1 - .../github.com/gen2brain/dlgs/dlgs_linux.go | 1 - .../github.com/gen2brain/dlgs/dlgs_windows.go | 1 - .../github.com/gen2brain/dlgs/entry_darwin.go | 1 - vendor/github.com/gen2brain/dlgs/entry_js.go | 1 - .../github.com/gen2brain/dlgs/entry_linux.go | 1 - .../gen2brain/dlgs/entry_unsupported.go | 1 - .../gen2brain/dlgs/entry_windows.go | 1 - .../github.com/gen2brain/dlgs/file_darwin.go | 1 - vendor/github.com/gen2brain/dlgs/file_js.go | 3 +- .../github.com/gen2brain/dlgs/file_linux.go | 11 +- .../gen2brain/dlgs/file_unsupported.go | 1 - .../github.com/gen2brain/dlgs/file_windows.go | 1 - .../github.com/gen2brain/dlgs/list_darwin.go | 1 - vendor/github.com/gen2brain/dlgs/list_js.go | 3 +- .../github.com/gen2brain/dlgs/list_linux.go | 1 - .../gen2brain/dlgs/list_unsupported.go | 1 - .../github.com/gen2brain/dlgs/list_windows.go | 1 - .../gen2brain/dlgs/message_darwin.go | 1 - .../github.com/gen2brain/dlgs/message_js.go | 1 - .../gen2brain/dlgs/message_linux.go | 1 - .../gen2brain/dlgs/message_unsupported.go | 1 - .../gen2brain/dlgs/message_windows.go | 1 - .../gen2brain/dlgs/password_darwin.go | 1 - .../github.com/gen2brain/dlgs/password_js.go | 1 - .../gen2brain/dlgs/password_linux.go | 1 - .../gen2brain/dlgs/password_unsupported.go | 1 - .../gen2brain/dlgs/password_windows.go | 1 - vendor/github.com/go-ole/go-ole/com.go | 1 - vendor/github.com/go-ole/go-ole/com_func.go | 1 - vendor/github.com/go-ole/go-ole/error_func.go | 1 - .../github.com/go-ole/go-ole/error_windows.go | 1 - .../go-ole/go-ole/iconnectionpoint_func.go | 1 - .../go-ole/go-ole/iconnectionpoint_windows.go | 1 - .../go-ole/iconnectionpointcontainer_func.go | 1 - .../iconnectionpointcontainer_windows.go | 1 - .../go-ole/go-ole/idispatch_func.go | 1 - .../go-ole/go-ole/ienumvariant_func.go | 1 - .../go-ole/go-ole/ienumvariant_windows.go | 1 - .../go-ole/go-ole/iinspectable_func.go | 1 - .../go-ole/go-ole/iinspectable_windows.go | 1 - .../go-ole/go-ole/iprovideclassinfo_func.go | 1 - .../go-ole/iprovideclassinfo_windows.go | 1 - .../go-ole/go-ole/itypeinfo_func.go | 1 - .../go-ole/go-ole/itypeinfo_windows.go | 1 - .../github.com/go-ole/go-ole/iunknown_func.go | 1 - .../go-ole/go-ole/iunknown_windows.go | 1 - .../go-ole/go-ole/oleutil/connection.go | 1 - .../go-ole/go-ole/oleutil/connection_func.go | 1 - .../go-ole/oleutil/connection_windows.go | 1 - .../go-ole/go-ole/oleutil/go-get.go | 1 - .../go-ole/go-ole/safearray_func.go | 1 - .../go-ole/go-ole/safearray_windows.go | 1 - .../go-ole/go-ole/safearrayconversion.go | 2 +- .../go-ole/go-ole/safearrayslices.go | 1 - vendor/github.com/go-ole/go-ole/variables.go | 1 - .../github.com/go-ole/go-ole/variant_386.go | 1 - .../github.com/go-ole/go-ole/variant_amd64.go | 1 - .../github.com/go-ole/go-ole/variant_arm.go | 1 - .../go-ole/go-ole/variant_date_386.go | 1 - .../go-ole/go-ole/variant_date_amd64.go | 1 - .../go-ole/go-ole/variant_date_arm.go | 1 - .../go-ole/go-ole/variant_ppc64le.go | 1 - .../github.com/go-ole/go-ole/variant_s390x.go | 1 - vendor/github.com/go-ole/go-ole/winrt.go | 1 - vendor/github.com/go-ole/go-ole/winrt_doc.go | 1 - .../github.com/godbus/dbus/v5/conn_other.go | 1 - vendor/github.com/godbus/dbus/v5/conn_unix.go | 3 +- .../github.com/godbus/dbus/v5/conn_windows.go | 3 +- .../godbus/dbus/v5/sequential_handler.go | 2 +- .../godbus/dbus/v5/transport_nonce_tcp.go | 3 +- .../godbus/dbus/v5/transport_unix.go | 3 +- vendor/github.com/google/uuid/node_js.go | 1 - vendor/github.com/google/uuid/node_net.go | 1 - .../github.com/gorilla/securecookie/fuzz.go | 1 - .../mousetrap/trap_windows_1.4.go | 46 - .../james-barrow/golang-ipc/README.md | 130 +-- .../james-barrow/golang-ipc/client_all.go | 95 +- .../james-barrow/golang-ipc/connect_other.go | 44 +- .../golang-ipc/connect_windows.go | 43 +- .../james-barrow/golang-ipc/encryption.go | 19 +- .../james-barrow/golang-ipc/handshake.go | 14 +- .../james-barrow/golang-ipc/server_all.go | 244 ++-- .../james-barrow/golang-ipc/shared.go | 7 +- .../james-barrow/golang-ipc/types.go | 54 +- vendor/github.com/json-iterator/go/any.go | 3 +- .../json-iterator/go/iter_skip_sloppy.go | 3 +- .../json-iterator/go/iter_skip_strict.go | 3 +- .../json-iterator/go/reflect_array.go | 3 +- .../json-iterator/go/reflect_dynamic.go | 3 +- .../json-iterator/go/reflect_extension.go | 3 +- .../json-iterator/go/reflect_json_number.go | 3 +- .../go/reflect_json_raw_message.go | 3 +- .../json-iterator/go/reflect_map.go | 3 +- .../json-iterator/go/reflect_optional.go | 3 +- .../json-iterator/go/reflect_slice.go | 3 +- .../go/reflect_struct_encoder.go | 3 +- .../klauspost/compress/flate/gen_inflate.go | 277 ----- .../klauspost/cpuid/detect_intel.go | 18 - .../github.com/klauspost/cpuid/detect_ref.go | 24 - .../reedsolomon/galoisAvx512_amd64.go | 337 ------ .../github.com/klauspost/reedsolomon/gen.go | 250 ---- .../sequences.go | 1 - .../sequences_dummy.go | 1 - .../modern-go/concurrent/go_above_19.go | 3 +- .../modern-go/concurrent/go_below_19.go | 3 +- vendor/github.com/modern-go/concurrent/log.go | 6 +- .../concurrent/unbounded_executor.go | 2 +- .../modern-go/reflect2/go_above_118.go | 5 +- .../modern-go/reflect2/go_above_19.go | 3 +- .../modern-go/reflect2/go_below_118.go | 5 +- .../github.com/modern-go/reflect2/type_map.go | 1 - vendor/github.com/pkg/errors/go113.go | 1 - .../sirupsen/logrus/hooks/syslog/syslog.go | 1 - .../logrus/terminal_check_appengine.go | 1 - .../sirupsen/logrus/terminal_check_bsd.go | 1 - .../sirupsen/logrus/terminal_check_js.go | 1 - .../logrus/terminal_check_no_terminal.go | 1 - .../logrus/terminal_check_notappengine.go | 1 - .../sirupsen/logrus/terminal_check_unix.go | 1 - .../sirupsen/logrus/terminal_check_windows.go | 1 - .../servermetrics/victoria_metrics.go | 1 - .../skycoin/dmsg/pkg/disc/client.go | 1 - .../skycoin/dmsg/pkg/dmsg/entity_common.go | 1 - .../skycoin/dmsg/pkg/dmsg/server.go | 1 - .../skycoin/dmsg/pkg/dmsgget/dmsgget.go | 1 - .../skycoin/dmsg/pkg/dmsgpty/cli.go | 1 - .../skycoin/dmsg/pkg/dmsgpty/host.go | 1 - .../skycoin/dmsg/pkg/dmsgpty/pty_client.go | 1 - .../github.com/skycoin/dmsg/pkg/dmsgpty/ui.go | 3 +- .../skycoin/dmsg/pkg/dmsgtest/env.go | 3 +- .../github.com/skycoin/dmsg/pkg/noise/net.go | 1 - .../skycoin/dmsg/pkg/noise/noise.go | 1 - vendor/github.com/skycoin/noise/patterns.go | 2 +- .../secp256k1-go/secp256k1-go2/secp256k1.go | 4 +- .../github.com/songgao/water/params_others.go | 1 - .../songgao/water/syscalls_darwin_go1.11.go | 1 - .../songgao/water/syscalls_darwin_legacy.go | 1 - .../songgao/water/syscalls_linux_go1.11.go | 1 - .../songgao/water/syscalls_linux_legacy.go | 1 - .../songgao/water/syscalls_other.go | 1 - .../stretchr/testify/require/require.go | 3 +- .../testify/require/require_forward.go | 3 +- .../capability/capability_noop.go | 1 - .../github.com/templexxx/cpufeat/cpu_x86.go | 1 - vendor/github.com/templexxx/xor/xor_other.go | 1 - vendor/github.com/tjfoc/gmsm/sm4/sm4.go | 4 + .../xtaci/kcp-go/readloop_generic.go | 1 - .../github.com/xtaci/kcp-go/readloop_linux.go | 1 - vendor/github.com/xtaci/kcp-go/tx_generic.go | 1 - vendor/github.com/xtaci/kcp-go/tx_linux.go | 1 - vendor/modules.txt | 5 +- 206 files changed, 5915 insertions(+), 1458 deletions(-) create mode 100644 vendor/github.com/boltdb/bolt/.gitignore create mode 100644 vendor/github.com/boltdb/bolt/LICENSE create mode 100644 vendor/github.com/boltdb/bolt/Makefile create mode 100644 vendor/github.com/boltdb/bolt/README.md create mode 100644 vendor/github.com/boltdb/bolt/appveyor.yml create mode 100644 vendor/github.com/boltdb/bolt/bolt_386.go create mode 100644 vendor/github.com/boltdb/bolt/bolt_amd64.go create mode 100644 vendor/github.com/boltdb/bolt/bolt_arm.go create mode 100644 vendor/github.com/boltdb/bolt/bolt_arm64.go create mode 100644 vendor/github.com/boltdb/bolt/bolt_linux.go create mode 100644 vendor/github.com/boltdb/bolt/bolt_openbsd.go create mode 100644 vendor/github.com/boltdb/bolt/bolt_ppc.go create mode 100644 vendor/github.com/boltdb/bolt/bolt_ppc64.go create mode 100644 vendor/github.com/boltdb/bolt/bolt_ppc64le.go create mode 100644 vendor/github.com/boltdb/bolt/bolt_s390x.go create mode 100644 vendor/github.com/boltdb/bolt/bolt_unix.go create mode 100644 vendor/github.com/boltdb/bolt/bolt_unix_solaris.go create mode 100644 vendor/github.com/boltdb/bolt/bolt_windows.go create mode 100644 vendor/github.com/boltdb/bolt/boltsync_unix.go create mode 100644 vendor/github.com/boltdb/bolt/bucket.go create mode 100644 vendor/github.com/boltdb/bolt/cursor.go create mode 100644 vendor/github.com/boltdb/bolt/db.go create mode 100644 vendor/github.com/boltdb/bolt/doc.go create mode 100644 vendor/github.com/boltdb/bolt/errors.go create mode 100644 vendor/github.com/boltdb/bolt/freelist.go create mode 100644 vendor/github.com/boltdb/bolt/node.go create mode 100644 vendor/github.com/boltdb/bolt/page.go create mode 100644 vendor/github.com/boltdb/bolt/tx.go delete mode 100644 vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go delete mode 100644 vendor/github.com/klauspost/compress/flate/gen_inflate.go delete mode 100644 vendor/github.com/klauspost/cpuid/detect_intel.go delete mode 100644 vendor/github.com/klauspost/cpuid/detect_ref.go delete mode 100644 vendor/github.com/klauspost/reedsolomon/galoisAvx512_amd64.go delete mode 100644 vendor/github.com/klauspost/reedsolomon/gen.go diff --git a/go.mod b/go.mod index 0da44fe8a..19f7b9b24 100644 --- a/go.mod +++ b/go.mod @@ -8,12 +8,14 @@ require ( github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 github.com/bitfield/script v0.22.0 github.com/blang/semver/v4 v4.0.0 + github.com/boltdb/bolt v1.3.1 github.com/ccding/go-stun/stun v0.0.0-20200514191101-4dc67bcdb029 github.com/gen2brain/dlgs v0.0.0-20220603100644-40c77870fa8d github.com/gin-gonic/gin v1.9.1 github.com/go-chi/chi/v5 v5.0.10 github.com/gocarina/gocsv v0.0.0-20230616125104-99d496ca653d github.com/google/uuid v1.3.1 + github.com/gorilla/mux v1.8.0 github.com/gorilla/securecookie v1.1.1 github.com/hashicorp/go-version v1.6.0 github.com/hashicorp/yamux v0.1.1 diff --git a/go.sum b/go.sum index 2929eb6ae..b5f561035 100644 --- a/go.sum +++ b/go.sum @@ -35,6 +35,8 @@ github.com/bitfield/script v0.22.0 h1:LA7QHuEsXMPD52YLtxWrlqCCy+9FOpzNYfsRHC5Gsr github.com/bitfield/script v0.22.0/go.mod h1:ms4w+9B8f2/W0mbsgWDVTtl7K94bYuZc3AunnJC4Ebs= github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= +github.com/boltdb/bolt v1.3.1 h1:JQmyP4ZBrce+ZQu0dY660FMfatumYDLun9hBCUVIkF4= +github.com/boltdb/bolt v1.3.1/go.mod h1:clJnj/oiGkjum5o1McbSZDSLxVThjynRyGBgiAx27Ps= github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM= github.com/bytedance/sonic v1.10.0 h1:qtNZduETEIWJVIyDl01BeNxur2rW9OwTQ/yBqFRkKEk= @@ -149,6 +151,8 @@ github.com/gookit/color v1.5.4 h1:FZmqs7XOyGgCAxmWyPslpiok1k05wmY3SJTytgvYFs0= github.com/gookit/color v1.5.4/go.mod h1:pZJOeOS8DM43rXbp4AZo1n9zCU2qjpcRko0b6/QJi9w= github.com/gopherjs/gopherjs v1.17.2 h1:fQnZVsXk8uxXIStYb0N4bGk7jeyTalG/wsZjQ25dO0g= github.com/gopherjs/gopherjs v1.17.2/go.mod h1:pRRIvn/QzFLrKfvEz3qUuEhtE/zLCWfreZ6J5gM2i+k= +github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI= +github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM= diff --git a/vendor/github.com/ActiveState/termtest/conpty/term_other.go b/vendor/github.com/ActiveState/termtest/conpty/term_other.go index 834d06230..daef1c079 100644 --- a/vendor/github.com/ActiveState/termtest/conpty/term_other.go +++ b/vendor/github.com/ActiveState/termtest/conpty/term_other.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package conpty diff --git a/vendor/github.com/ActiveState/termtest/conpty/term_windows.go b/vendor/github.com/ActiveState/termtest/conpty/term_windows.go index b4d2ad00d..df091b5bb 100644 --- a/vendor/github.com/ActiveState/termtest/conpty/term_windows.go +++ b/vendor/github.com/ActiveState/termtest/conpty/term_windows.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package conpty diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go index bf71684f4..5599082ae 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/ansi.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/api.go b/vendor/github.com/Azure/go-ansiterm/winterm/api.go index 2f297601b..6055e33b9 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/api.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/api.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go index 644d8b2b4..cbec8f728 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/attr_translation.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go index 6b4b8a1ef..3ee06ea72 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/cursor_helpers.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go index 1298544a3..244b5fa25 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/erase_helpers.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go index 03ab280c1..2d27fa1d0 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/scroll_helper.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go index 3535349f0..afa7635d7 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/utilities.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go index 1e19ea0c3..2d40fb75a 100644 --- a/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go +++ b/vendor/github.com/Azure/go-ansiterm/winterm/win_event_handler.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package winterm diff --git a/vendor/github.com/StackExchange/wmi/swbemservices.go b/vendor/github.com/StackExchange/wmi/swbemservices.go index a250c846d..3ff875630 100644 --- a/vendor/github.com/StackExchange/wmi/swbemservices.go +++ b/vendor/github.com/StackExchange/wmi/swbemservices.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package wmi diff --git a/vendor/github.com/StackExchange/wmi/wmi.go b/vendor/github.com/StackExchange/wmi/wmi.go index 0d9f9702d..b4bb4f090 100644 --- a/vendor/github.com/StackExchange/wmi/wmi.go +++ b/vendor/github.com/StackExchange/wmi/wmi.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows /* diff --git a/vendor/github.com/boltdb/bolt/.gitignore b/vendor/github.com/boltdb/bolt/.gitignore new file mode 100644 index 000000000..c7bd2b7a5 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/.gitignore @@ -0,0 +1,4 @@ +*.prof +*.test +*.swp +/bin/ diff --git a/vendor/github.com/boltdb/bolt/LICENSE b/vendor/github.com/boltdb/bolt/LICENSE new file mode 100644 index 000000000..004e77fe5 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Ben Johnson + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/boltdb/bolt/Makefile b/vendor/github.com/boltdb/bolt/Makefile new file mode 100644 index 000000000..e035e63ad --- /dev/null +++ b/vendor/github.com/boltdb/bolt/Makefile @@ -0,0 +1,18 @@ +BRANCH=`git rev-parse --abbrev-ref HEAD` +COMMIT=`git rev-parse --short HEAD` +GOLDFLAGS="-X main.branch $(BRANCH) -X main.commit $(COMMIT)" + +default: build + +race: + @go test -v -race -test.run="TestSimulate_(100op|1000op)" + +# go get github.com/kisielk/errcheck +errcheck: + @errcheck -ignorepkg=bytes -ignore=os:Remove github.com/boltdb/bolt + +test: + @go test -v -cover . + @go test -v ./cmd/bolt + +.PHONY: fmt test diff --git a/vendor/github.com/boltdb/bolt/README.md b/vendor/github.com/boltdb/bolt/README.md new file mode 100644 index 000000000..7d43a15b2 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/README.md @@ -0,0 +1,916 @@ +Bolt [![Coverage Status](https://coveralls.io/repos/boltdb/bolt/badge.svg?branch=master)](https://coveralls.io/r/boltdb/bolt?branch=master) [![GoDoc](https://godoc.org/github.com/boltdb/bolt?status.svg)](https://godoc.org/github.com/boltdb/bolt) ![Version](https://img.shields.io/badge/version-1.2.1-green.svg) +==== + +Bolt is a pure Go key/value store inspired by [Howard Chu's][hyc_symas] +[LMDB project][lmdb]. The goal of the project is to provide a simple, +fast, and reliable database for projects that don't require a full database +server such as Postgres or MySQL. + +Since Bolt is meant to be used as such a low-level piece of functionality, +simplicity is key. The API will be small and only focus on getting values +and setting values. That's it. + +[hyc_symas]: https://twitter.com/hyc_symas +[lmdb]: http://symas.com/mdb/ + +## Project Status + +Bolt is stable, the API is fixed, and the file format is fixed. Full unit +test coverage and randomized black box testing are used to ensure database +consistency and thread safety. Bolt is currently used in high-load production +environments serving databases as large as 1TB. Many companies such as +Shopify and Heroku use Bolt-backed services every day. + +## Table of Contents + +- [Getting Started](#getting-started) + - [Installing](#installing) + - [Opening a database](#opening-a-database) + - [Transactions](#transactions) + - [Read-write transactions](#read-write-transactions) + - [Read-only transactions](#read-only-transactions) + - [Batch read-write transactions](#batch-read-write-transactions) + - [Managing transactions manually](#managing-transactions-manually) + - [Using buckets](#using-buckets) + - [Using key/value pairs](#using-keyvalue-pairs) + - [Autoincrementing integer for the bucket](#autoincrementing-integer-for-the-bucket) + - [Iterating over keys](#iterating-over-keys) + - [Prefix scans](#prefix-scans) + - [Range scans](#range-scans) + - [ForEach()](#foreach) + - [Nested buckets](#nested-buckets) + - [Database backups](#database-backups) + - [Statistics](#statistics) + - [Read-Only Mode](#read-only-mode) + - [Mobile Use (iOS/Android)](#mobile-use-iosandroid) +- [Resources](#resources) +- [Comparison with other databases](#comparison-with-other-databases) + - [Postgres, MySQL, & other relational databases](#postgres-mysql--other-relational-databases) + - [LevelDB, RocksDB](#leveldb-rocksdb) + - [LMDB](#lmdb) +- [Caveats & Limitations](#caveats--limitations) +- [Reading the Source](#reading-the-source) +- [Other Projects Using Bolt](#other-projects-using-bolt) + +## Getting Started + +### Installing + +To start using Bolt, install Go and run `go get`: + +```sh +$ go get github.com/boltdb/bolt/... +``` + +This will retrieve the library and install the `bolt` command line utility into +your `$GOBIN` path. + + +### Opening a database + +The top-level object in Bolt is a `DB`. It is represented as a single file on +your disk and represents a consistent snapshot of your data. + +To open your database, simply use the `bolt.Open()` function: + +```go +package main + +import ( + "log" + + "github.com/boltdb/bolt" +) + +func main() { + // Open the my.db data file in your current directory. + // It will be created if it doesn't exist. + db, err := bolt.Open("my.db", 0600, nil) + if err != nil { + log.Fatal(err) + } + defer db.Close() + + ... +} +``` + +Please note that Bolt obtains a file lock on the data file so multiple processes +cannot open the same database at the same time. Opening an already open Bolt +database will cause it to hang until the other process closes it. To prevent +an indefinite wait you can pass a timeout option to the `Open()` function: + +```go +db, err := bolt.Open("my.db", 0600, &bolt.Options{Timeout: 1 * time.Second}) +``` + + +### Transactions + +Bolt allows only one read-write transaction at a time but allows as many +read-only transactions as you want at a time. Each transaction has a consistent +view of the data as it existed when the transaction started. + +Individual transactions and all objects created from them (e.g. buckets, keys) +are not thread safe. To work with data in multiple goroutines you must start +a transaction for each one or use locking to ensure only one goroutine accesses +a transaction at a time. Creating transaction from the `DB` is thread safe. + +Read-only transactions and read-write transactions should not depend on one +another and generally shouldn't be opened simultaneously in the same goroutine. +This can cause a deadlock as the read-write transaction needs to periodically +re-map the data file but it cannot do so while a read-only transaction is open. + + +#### Read-write transactions + +To start a read-write transaction, you can use the `DB.Update()` function: + +```go +err := db.Update(func(tx *bolt.Tx) error { + ... + return nil +}) +``` + +Inside the closure, you have a consistent view of the database. You commit the +transaction by returning `nil` at the end. You can also rollback the transaction +at any point by returning an error. All database operations are allowed inside +a read-write transaction. + +Always check the return error as it will report any disk failures that can cause +your transaction to not complete. If you return an error within your closure +it will be passed through. + + +#### Read-only transactions + +To start a read-only transaction, you can use the `DB.View()` function: + +```go +err := db.View(func(tx *bolt.Tx) error { + ... + return nil +}) +``` + +You also get a consistent view of the database within this closure, however, +no mutating operations are allowed within a read-only transaction. You can only +retrieve buckets, retrieve values, and copy the database within a read-only +transaction. + + +#### Batch read-write transactions + +Each `DB.Update()` waits for disk to commit the writes. This overhead +can be minimized by combining multiple updates with the `DB.Batch()` +function: + +```go +err := db.Batch(func(tx *bolt.Tx) error { + ... + return nil +}) +``` + +Concurrent Batch calls are opportunistically combined into larger +transactions. Batch is only useful when there are multiple goroutines +calling it. + +The trade-off is that `Batch` can call the given +function multiple times, if parts of the transaction fail. The +function must be idempotent and side effects must take effect only +after a successful return from `DB.Batch()`. + +For example: don't display messages from inside the function, instead +set variables in the enclosing scope: + +```go +var id uint64 +err := db.Batch(func(tx *bolt.Tx) error { + // Find last key in bucket, decode as bigendian uint64, increment + // by one, encode back to []byte, and add new key. + ... + id = newValue + return nil +}) +if err != nil { + return ... +} +fmt.Println("Allocated ID %d", id) +``` + + +#### Managing transactions manually + +The `DB.View()` and `DB.Update()` functions are wrappers around the `DB.Begin()` +function. These helper functions will start the transaction, execute a function, +and then safely close your transaction if an error is returned. This is the +recommended way to use Bolt transactions. + +However, sometimes you may want to manually start and end your transactions. +You can use the `DB.Begin()` function directly but **please** be sure to close +the transaction. + +```go +// Start a writable transaction. +tx, err := db.Begin(true) +if err != nil { + return err +} +defer tx.Rollback() + +// Use the transaction... +_, err := tx.CreateBucket([]byte("MyBucket")) +if err != nil { + return err +} + +// Commit the transaction and check for error. +if err := tx.Commit(); err != nil { + return err +} +``` + +The first argument to `DB.Begin()` is a boolean stating if the transaction +should be writable. + + +### Using buckets + +Buckets are collections of key/value pairs within the database. All keys in a +bucket must be unique. You can create a bucket using the `DB.CreateBucket()` +function: + +```go +db.Update(func(tx *bolt.Tx) error { + b, err := tx.CreateBucket([]byte("MyBucket")) + if err != nil { + return fmt.Errorf("create bucket: %s", err) + } + return nil +}) +``` + +You can also create a bucket only if it doesn't exist by using the +`Tx.CreateBucketIfNotExists()` function. It's a common pattern to call this +function for all your top-level buckets after you open your database so you can +guarantee that they exist for future transactions. + +To delete a bucket, simply call the `Tx.DeleteBucket()` function. + + +### Using key/value pairs + +To save a key/value pair to a bucket, use the `Bucket.Put()` function: + +```go +db.Update(func(tx *bolt.Tx) error { + b := tx.Bucket([]byte("MyBucket")) + err := b.Put([]byte("answer"), []byte("42")) + return err +}) +``` + +This will set the value of the `"answer"` key to `"42"` in the `MyBucket` +bucket. To retrieve this value, we can use the `Bucket.Get()` function: + +```go +db.View(func(tx *bolt.Tx) error { + b := tx.Bucket([]byte("MyBucket")) + v := b.Get([]byte("answer")) + fmt.Printf("The answer is: %s\n", v) + return nil +}) +``` + +The `Get()` function does not return an error because its operation is +guaranteed to work (unless there is some kind of system failure). If the key +exists then it will return its byte slice value. If it doesn't exist then it +will return `nil`. It's important to note that you can have a zero-length value +set to a key which is different than the key not existing. + +Use the `Bucket.Delete()` function to delete a key from the bucket. + +Please note that values returned from `Get()` are only valid while the +transaction is open. If you need to use a value outside of the transaction +then you must use `copy()` to copy it to another byte slice. + + +### Autoincrementing integer for the bucket +By using the `NextSequence()` function, you can let Bolt determine a sequence +which can be used as the unique identifier for your key/value pairs. See the +example below. + +```go +// CreateUser saves u to the store. The new user ID is set on u once the data is persisted. +func (s *Store) CreateUser(u *User) error { + return s.db.Update(func(tx *bolt.Tx) error { + // Retrieve the users bucket. + // This should be created when the DB is first opened. + b := tx.Bucket([]byte("users")) + + // Generate ID for the user. + // This returns an error only if the Tx is closed or not writeable. + // That can't happen in an Update() call so I ignore the error check. + id, _ := b.NextSequence() + u.ID = int(id) + + // Marshal user data into bytes. + buf, err := json.Marshal(u) + if err != nil { + return err + } + + // Persist bytes to users bucket. + return b.Put(itob(u.ID), buf) + }) +} + +// itob returns an 8-byte big endian representation of v. +func itob(v int) []byte { + b := make([]byte, 8) + binary.BigEndian.PutUint64(b, uint64(v)) + return b +} + +type User struct { + ID int + ... +} +``` + +### Iterating over keys + +Bolt stores its keys in byte-sorted order within a bucket. This makes sequential +iteration over these keys extremely fast. To iterate over keys we'll use a +`Cursor`: + +```go +db.View(func(tx *bolt.Tx) error { + // Assume bucket exists and has keys + b := tx.Bucket([]byte("MyBucket")) + + c := b.Cursor() + + for k, v := c.First(); k != nil; k, v = c.Next() { + fmt.Printf("key=%s, value=%s\n", k, v) + } + + return nil +}) +``` + +The cursor allows you to move to a specific point in the list of keys and move +forward or backward through the keys one at a time. + +The following functions are available on the cursor: + +``` +First() Move to the first key. +Last() Move to the last key. +Seek() Move to a specific key. +Next() Move to the next key. +Prev() Move to the previous key. +``` + +Each of those functions has a return signature of `(key []byte, value []byte)`. +When you have iterated to the end of the cursor then `Next()` will return a +`nil` key. You must seek to a position using `First()`, `Last()`, or `Seek()` +before calling `Next()` or `Prev()`. If you do not seek to a position then +these functions will return a `nil` key. + +During iteration, if the key is non-`nil` but the value is `nil`, that means +the key refers to a bucket rather than a value. Use `Bucket.Bucket()` to +access the sub-bucket. + + +#### Prefix scans + +To iterate over a key prefix, you can combine `Seek()` and `bytes.HasPrefix()`: + +```go +db.View(func(tx *bolt.Tx) error { + // Assume bucket exists and has keys + c := tx.Bucket([]byte("MyBucket")).Cursor() + + prefix := []byte("1234") + for k, v := c.Seek(prefix); k != nil && bytes.HasPrefix(k, prefix); k, v = c.Next() { + fmt.Printf("key=%s, value=%s\n", k, v) + } + + return nil +}) +``` + +#### Range scans + +Another common use case is scanning over a range such as a time range. If you +use a sortable time encoding such as RFC3339 then you can query a specific +date range like this: + +```go +db.View(func(tx *bolt.Tx) error { + // Assume our events bucket exists and has RFC3339 encoded time keys. + c := tx.Bucket([]byte("Events")).Cursor() + + // Our time range spans the 90's decade. + min := []byte("1990-01-01T00:00:00Z") + max := []byte("2000-01-01T00:00:00Z") + + // Iterate over the 90's. + for k, v := c.Seek(min); k != nil && bytes.Compare(k, max) <= 0; k, v = c.Next() { + fmt.Printf("%s: %s\n", k, v) + } + + return nil +}) +``` + +Note that, while RFC3339 is sortable, the Golang implementation of RFC3339Nano does not use a fixed number of digits after the decimal point and is therefore not sortable. + + +#### ForEach() + +You can also use the function `ForEach()` if you know you'll be iterating over +all the keys in a bucket: + +```go +db.View(func(tx *bolt.Tx) error { + // Assume bucket exists and has keys + b := tx.Bucket([]byte("MyBucket")) + + b.ForEach(func(k, v []byte) error { + fmt.Printf("key=%s, value=%s\n", k, v) + return nil + }) + return nil +}) +``` + +Please note that keys and values in `ForEach()` are only valid while +the transaction is open. If you need to use a key or value outside of +the transaction, you must use `copy()` to copy it to another byte +slice. + +### Nested buckets + +You can also store a bucket in a key to create nested buckets. The API is the +same as the bucket management API on the `DB` object: + +```go +func (*Bucket) CreateBucket(key []byte) (*Bucket, error) +func (*Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) +func (*Bucket) DeleteBucket(key []byte) error +``` + +Say you had a multi-tenant application where the root level bucket was the account bucket. Inside of this bucket was a sequence of accounts which themselves are buckets. And inside the sequence bucket you could have many buckets pertaining to the Account itself (Users, Notes, etc) isolating the information into logical groupings. + +```go + +// createUser creates a new user in the given account. +func createUser(accountID int, u *User) error { + // Start the transaction. + tx, err := db.Begin(true) + if err != nil { + return err + } + defer tx.Rollback() + + // Retrieve the root bucket for the account. + // Assume this has already been created when the account was set up. + root := tx.Bucket([]byte(strconv.FormatUint(accountID, 10))) + + // Setup the users bucket. + bkt, err := root.CreateBucketIfNotExists([]byte("USERS")) + if err != nil { + return err + } + + // Generate an ID for the new user. + userID, err := bkt.NextSequence() + if err != nil { + return err + } + u.ID = userID + + // Marshal and save the encoded user. + if buf, err := json.Marshal(u); err != nil { + return err + } else if err := bkt.Put([]byte(strconv.FormatUint(u.ID, 10)), buf); err != nil { + return err + } + + // Commit the transaction. + if err := tx.Commit(); err != nil { + return err + } + + return nil +} + +``` + + + + +### Database backups + +Bolt is a single file so it's easy to backup. You can use the `Tx.WriteTo()` +function to write a consistent view of the database to a writer. If you call +this from a read-only transaction, it will perform a hot backup and not block +your other database reads and writes. + +By default, it will use a regular file handle which will utilize the operating +system's page cache. See the [`Tx`](https://godoc.org/github.com/boltdb/bolt#Tx) +documentation for information about optimizing for larger-than-RAM datasets. + +One common use case is to backup over HTTP so you can use tools like `cURL` to +do database backups: + +```go +func BackupHandleFunc(w http.ResponseWriter, req *http.Request) { + err := db.View(func(tx *bolt.Tx) error { + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Disposition", `attachment; filename="my.db"`) + w.Header().Set("Content-Length", strconv.Itoa(int(tx.Size()))) + _, err := tx.WriteTo(w) + return err + }) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } +} +``` + +Then you can backup using this command: + +```sh +$ curl http://localhost/backup > my.db +``` + +Or you can open your browser to `http://localhost/backup` and it will download +automatically. + +If you want to backup to another file you can use the `Tx.CopyFile()` helper +function. + + +### Statistics + +The database keeps a running count of many of the internal operations it +performs so you can better understand what's going on. By grabbing a snapshot +of these stats at two points in time we can see what operations were performed +in that time range. + +For example, we could start a goroutine to log stats every 10 seconds: + +```go +go func() { + // Grab the initial stats. + prev := db.Stats() + + for { + // Wait for 10s. + time.Sleep(10 * time.Second) + + // Grab the current stats and diff them. + stats := db.Stats() + diff := stats.Sub(&prev) + + // Encode stats to JSON and print to STDERR. + json.NewEncoder(os.Stderr).Encode(diff) + + // Save stats for the next loop. + prev = stats + } +}() +``` + +It's also useful to pipe these stats to a service such as statsd for monitoring +or to provide an HTTP endpoint that will perform a fixed-length sample. + + +### Read-Only Mode + +Sometimes it is useful to create a shared, read-only Bolt database. To this, +set the `Options.ReadOnly` flag when opening your database. Read-only mode +uses a shared lock to allow multiple processes to read from the database but +it will block any processes from opening the database in read-write mode. + +```go +db, err := bolt.Open("my.db", 0666, &bolt.Options{ReadOnly: true}) +if err != nil { + log.Fatal(err) +} +``` + +### Mobile Use (iOS/Android) + +Bolt is able to run on mobile devices by leveraging the binding feature of the +[gomobile](https://github.com/golang/mobile) tool. Create a struct that will +contain your database logic and a reference to a `*bolt.DB` with a initializing +constructor that takes in a filepath where the database file will be stored. +Neither Android nor iOS require extra permissions or cleanup from using this method. + +```go +func NewBoltDB(filepath string) *BoltDB { + db, err := bolt.Open(filepath+"/demo.db", 0600, nil) + if err != nil { + log.Fatal(err) + } + + return &BoltDB{db} +} + +type BoltDB struct { + db *bolt.DB + ... +} + +func (b *BoltDB) Path() string { + return b.db.Path() +} + +func (b *BoltDB) Close() { + b.db.Close() +} +``` + +Database logic should be defined as methods on this wrapper struct. + +To initialize this struct from the native language (both platforms now sync +their local storage to the cloud. These snippets disable that functionality for the +database file): + +#### Android + +```java +String path; +if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.LOLLIPOP){ + path = getNoBackupFilesDir().getAbsolutePath(); +} else{ + path = getFilesDir().getAbsolutePath(); +} +Boltmobiledemo.BoltDB boltDB = Boltmobiledemo.NewBoltDB(path) +``` + +#### iOS + +```objc +- (void)demo { + NSString* path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, + NSUserDomainMask, + YES) objectAtIndex:0]; + GoBoltmobiledemoBoltDB * demo = GoBoltmobiledemoNewBoltDB(path); + [self addSkipBackupAttributeToItemAtPath:demo.path]; + //Some DB Logic would go here + [demo close]; +} + +- (BOOL)addSkipBackupAttributeToItemAtPath:(NSString *) filePathString +{ + NSURL* URL= [NSURL fileURLWithPath: filePathString]; + assert([[NSFileManager defaultManager] fileExistsAtPath: [URL path]]); + + NSError *error = nil; + BOOL success = [URL setResourceValue: [NSNumber numberWithBool: YES] + forKey: NSURLIsExcludedFromBackupKey error: &error]; + if(!success){ + NSLog(@"Error excluding %@ from backup %@", [URL lastPathComponent], error); + } + return success; +} + +``` + +## Resources + +For more information on getting started with Bolt, check out the following articles: + +* [Intro to BoltDB: Painless Performant Persistence](http://npf.io/2014/07/intro-to-boltdb-painless-performant-persistence/) by [Nate Finch](https://github.com/natefinch). +* [Bolt -- an embedded key/value database for Go](https://www.progville.com/go/bolt-embedded-db-golang/) by Progville + + +## Comparison with other databases + +### Postgres, MySQL, & other relational databases + +Relational databases structure data into rows and are only accessible through +the use of SQL. This approach provides flexibility in how you store and query +your data but also incurs overhead in parsing and planning SQL statements. Bolt +accesses all data by a byte slice key. This makes Bolt fast to read and write +data by key but provides no built-in support for joining values together. + +Most relational databases (with the exception of SQLite) are standalone servers +that run separately from your application. This gives your systems +flexibility to connect multiple application servers to a single database +server but also adds overhead in serializing and transporting data over the +network. Bolt runs as a library included in your application so all data access +has to go through your application's process. This brings data closer to your +application but limits multi-process access to the data. + + +### LevelDB, RocksDB + +LevelDB and its derivatives (RocksDB, HyperLevelDB) are similar to Bolt in that +they are libraries bundled into the application, however, their underlying +structure is a log-structured merge-tree (LSM tree). An LSM tree optimizes +random writes by using a write ahead log and multi-tiered, sorted files called +SSTables. Bolt uses a B+tree internally and only a single file. Both approaches +have trade-offs. + +If you require a high random write throughput (>10,000 w/sec) or you need to use +spinning disks then LevelDB could be a good choice. If your application is +read-heavy or does a lot of range scans then Bolt could be a good choice. + +One other important consideration is that LevelDB does not have transactions. +It supports batch writing of key/values pairs and it supports read snapshots +but it will not give you the ability to do a compare-and-swap operation safely. +Bolt supports fully serializable ACID transactions. + + +### LMDB + +Bolt was originally a port of LMDB so it is architecturally similar. Both use +a B+tree, have ACID semantics with fully serializable transactions, and support +lock-free MVCC using a single writer and multiple readers. + +The two projects have somewhat diverged. LMDB heavily focuses on raw performance +while Bolt has focused on simplicity and ease of use. For example, LMDB allows +several unsafe actions such as direct writes for the sake of performance. Bolt +opts to disallow actions which can leave the database in a corrupted state. The +only exception to this in Bolt is `DB.NoSync`. + +There are also a few differences in API. LMDB requires a maximum mmap size when +opening an `mdb_env` whereas Bolt will handle incremental mmap resizing +automatically. LMDB overloads the getter and setter functions with multiple +flags whereas Bolt splits these specialized cases into their own functions. + + +## Caveats & Limitations + +It's important to pick the right tool for the job and Bolt is no exception. +Here are a few things to note when evaluating and using Bolt: + +* Bolt is good for read intensive workloads. Sequential write performance is + also fast but random writes can be slow. You can use `DB.Batch()` or add a + write-ahead log to help mitigate this issue. + +* Bolt uses a B+tree internally so there can be a lot of random page access. + SSDs provide a significant performance boost over spinning disks. + +* Try to avoid long running read transactions. Bolt uses copy-on-write so + old pages cannot be reclaimed while an old transaction is using them. + +* Byte slices returned from Bolt are only valid during a transaction. Once the + transaction has been committed or rolled back then the memory they point to + can be reused by a new page or can be unmapped from virtual memory and you'll + see an `unexpected fault address` panic when accessing it. + +* Bolt uses an exclusive write lock on the database file so it cannot be + shared by multiple processes. + +* Be careful when using `Bucket.FillPercent`. Setting a high fill percent for + buckets that have random inserts will cause your database to have very poor + page utilization. + +* Use larger buckets in general. Smaller buckets causes poor page utilization + once they become larger than the page size (typically 4KB). + +* Bulk loading a lot of random writes into a new bucket can be slow as the + page will not split until the transaction is committed. Randomly inserting + more than 100,000 key/value pairs into a single new bucket in a single + transaction is not advised. + +* Bolt uses a memory-mapped file so the underlying operating system handles the + caching of the data. Typically, the OS will cache as much of the file as it + can in memory and will release memory as needed to other processes. This means + that Bolt can show very high memory usage when working with large databases. + However, this is expected and the OS will release memory as needed. Bolt can + handle databases much larger than the available physical RAM, provided its + memory-map fits in the process virtual address space. It may be problematic + on 32-bits systems. + +* The data structures in the Bolt database are memory mapped so the data file + will be endian specific. This means that you cannot copy a Bolt file from a + little endian machine to a big endian machine and have it work. For most + users this is not a concern since most modern CPUs are little endian. + +* Because of the way pages are laid out on disk, Bolt cannot truncate data files + and return free pages back to the disk. Instead, Bolt maintains a free list + of unused pages within its data file. These free pages can be reused by later + transactions. This works well for many use cases as databases generally tend + to grow. However, it's important to note that deleting large chunks of data + will not allow you to reclaim that space on disk. + + For more information on page allocation, [see this comment][page-allocation]. + +[page-allocation]: https://github.com/boltdb/bolt/issues/308#issuecomment-74811638 + + +## Reading the Source + +Bolt is a relatively small code base (<3KLOC) for an embedded, serializable, +transactional key/value database so it can be a good starting point for people +interested in how databases work. + +The best places to start are the main entry points into Bolt: + +- `Open()` - Initializes the reference to the database. It's responsible for + creating the database if it doesn't exist, obtaining an exclusive lock on the + file, reading the meta pages, & memory-mapping the file. + +- `DB.Begin()` - Starts a read-only or read-write transaction depending on the + value of the `writable` argument. This requires briefly obtaining the "meta" + lock to keep track of open transactions. Only one read-write transaction can + exist at a time so the "rwlock" is acquired during the life of a read-write + transaction. + +- `Bucket.Put()` - Writes a key/value pair into a bucket. After validating the + arguments, a cursor is used to traverse the B+tree to the page and position + where they key & value will be written. Once the position is found, the bucket + materializes the underlying page and the page's parent pages into memory as + "nodes". These nodes are where mutations occur during read-write transactions. + These changes get flushed to disk during commit. + +- `Bucket.Get()` - Retrieves a key/value pair from a bucket. This uses a cursor + to move to the page & position of a key/value pair. During a read-only + transaction, the key and value data is returned as a direct reference to the + underlying mmap file so there's no allocation overhead. For read-write + transactions, this data may reference the mmap file or one of the in-memory + node values. + +- `Cursor` - This object is simply for traversing the B+tree of on-disk pages + or in-memory nodes. It can seek to a specific key, move to the first or last + value, or it can move forward or backward. The cursor handles the movement up + and down the B+tree transparently to the end user. + +- `Tx.Commit()` - Converts the in-memory dirty nodes and the list of free pages + into pages to be written to disk. Writing to disk then occurs in two phases. + First, the dirty pages are written to disk and an `fsync()` occurs. Second, a + new meta page with an incremented transaction ID is written and another + `fsync()` occurs. This two phase write ensures that partially written data + pages are ignored in the event of a crash since the meta page pointing to them + is never written. Partially written meta pages are invalidated because they + are written with a checksum. + +If you have additional notes that could be helpful for others, please submit +them via pull request. + + +## Other Projects Using Bolt + +Below is a list of public, open source projects that use Bolt: + +* [BoltDbWeb](https://github.com/evnix/boltdbweb) - A web based GUI for BoltDB files. +* [Operation Go: A Routine Mission](http://gocode.io) - An online programming game for Golang using Bolt for user accounts and a leaderboard. +* [Bazil](https://bazil.org/) - A file system that lets your data reside where it is most convenient for it to reside. +* [DVID](https://github.com/janelia-flyem/dvid) - Added Bolt as optional storage engine and testing it against Basho-tuned leveldb. +* [Skybox Analytics](https://github.com/skybox/skybox) - A standalone funnel analysis tool for web analytics. +* [Scuttlebutt](https://github.com/benbjohnson/scuttlebutt) - Uses Bolt to store and process all Twitter mentions of GitHub projects. +* [Wiki](https://github.com/peterhellberg/wiki) - A tiny wiki using Goji, BoltDB and Blackfriday. +* [ChainStore](https://github.com/pressly/chainstore) - Simple key-value interface to a variety of storage engines organized as a chain of operations. +* [MetricBase](https://github.com/msiebuhr/MetricBase) - Single-binary version of Graphite. +* [Gitchain](https://github.com/gitchain/gitchain) - Decentralized, peer-to-peer Git repositories aka "Git meets Bitcoin". +* [event-shuttle](https://github.com/sclasen/event-shuttle) - A Unix system service to collect and reliably deliver messages to Kafka. +* [ipxed](https://github.com/kelseyhightower/ipxed) - Web interface and api for ipxed. +* [BoltStore](https://github.com/yosssi/boltstore) - Session store using Bolt. +* [photosite/session](https://godoc.org/bitbucket.org/kardianos/photosite/session) - Sessions for a photo viewing site. +* [LedisDB](https://github.com/siddontang/ledisdb) - A high performance NoSQL, using Bolt as optional storage. +* [ipLocator](https://github.com/AndreasBriese/ipLocator) - A fast ip-geo-location-server using bolt with bloom filters. +* [cayley](https://github.com/google/cayley) - Cayley is an open-source graph database using Bolt as optional backend. +* [bleve](http://www.blevesearch.com/) - A pure Go search engine similar to ElasticSearch that uses Bolt as the default storage backend. +* [tentacool](https://github.com/optiflows/tentacool) - REST api server to manage system stuff (IP, DNS, Gateway...) on a linux server. +* [Seaweed File System](https://github.com/chrislusf/seaweedfs) - Highly scalable distributed key~file system with O(1) disk read. +* [InfluxDB](https://influxdata.com) - Scalable datastore for metrics, events, and real-time analytics. +* [Freehold](http://tshannon.bitbucket.org/freehold/) - An open, secure, and lightweight platform for your files and data. +* [Prometheus Annotation Server](https://github.com/oliver006/prom_annotation_server) - Annotation server for PromDash & Prometheus service monitoring system. +* [Consul](https://github.com/hashicorp/consul) - Consul is service discovery and configuration made easy. Distributed, highly available, and datacenter-aware. +* [Kala](https://github.com/ajvb/kala) - Kala is a modern job scheduler optimized to run on a single node. It is persistent, JSON over HTTP API, ISO 8601 duration notation, and dependent jobs. +* [drive](https://github.com/odeke-em/drive) - drive is an unofficial Google Drive command line client for \*NIX operating systems. +* [stow](https://github.com/djherbis/stow) - a persistence manager for objects + backed by boltdb. +* [buckets](https://github.com/joyrexus/buckets) - a bolt wrapper streamlining + simple tx and key scans. +* [mbuckets](https://github.com/abhigupta912/mbuckets) - A Bolt wrapper that allows easy operations on multi level (nested) buckets. +* [Request Baskets](https://github.com/darklynx/request-baskets) - A web service to collect arbitrary HTTP requests and inspect them via REST API or simple web UI, similar to [RequestBin](http://requestb.in/) service +* [Go Report Card](https://goreportcard.com/) - Go code quality report cards as a (free and open source) service. +* [Boltdb Boilerplate](https://github.com/bobintornado/boltdb-boilerplate) - Boilerplate wrapper around bolt aiming to make simple calls one-liners. +* [lru](https://github.com/crowdriff/lru) - Easy to use Bolt-backed Least-Recently-Used (LRU) read-through cache with chainable remote stores. +* [Storm](https://github.com/asdine/storm) - Simple and powerful ORM for BoltDB. +* [GoWebApp](https://github.com/josephspurrier/gowebapp) - A basic MVC web application in Go using BoltDB. +* [SimpleBolt](https://github.com/xyproto/simplebolt) - A simple way to use BoltDB. Deals mainly with strings. +* [Algernon](https://github.com/xyproto/algernon) - A HTTP/2 web server with built-in support for Lua. Uses BoltDB as the default database backend. +* [MuLiFS](https://github.com/dankomiocevic/mulifs) - Music Library Filesystem creates a filesystem to organise your music files. +* [GoShort](https://github.com/pankajkhairnar/goShort) - GoShort is a URL shortener written in Golang and BoltDB for persistent key/value storage and for routing it's using high performent HTTPRouter. +* [torrent](https://github.com/anacrolix/torrent) - Full-featured BitTorrent client package and utilities in Go. BoltDB is a storage backend in development. +* [gopherpit](https://github.com/gopherpit/gopherpit) - A web service to manage Go remote import paths with custom domains +* [bolter](https://github.com/hasit/bolter) - Command-line app for viewing BoltDB file in your terminal. +* [btcwallet](https://github.com/btcsuite/btcwallet) - A bitcoin wallet. +* [dcrwallet](https://github.com/decred/dcrwallet) - A wallet for the Decred cryptocurrency. +* [Ironsmith](https://github.com/timshannon/ironsmith) - A simple, script-driven continuous integration (build - > test -> release) tool, with no external dependencies +* [BoltHold](https://github.com/timshannon/bolthold) - An embeddable NoSQL store for Go types built on BoltDB +* [Ponzu CMS](https://ponzu-cms.org) - Headless CMS + automatic JSON API with auto-HTTPS, HTTP/2 Server Push, and flexible server framework. + +If you are using Bolt in a project please send a pull request to add it to the list. diff --git a/vendor/github.com/boltdb/bolt/appveyor.yml b/vendor/github.com/boltdb/bolt/appveyor.yml new file mode 100644 index 000000000..6e26e941d --- /dev/null +++ b/vendor/github.com/boltdb/bolt/appveyor.yml @@ -0,0 +1,18 @@ +version: "{build}" + +os: Windows Server 2012 R2 + +clone_folder: c:\gopath\src\github.com\boltdb\bolt + +environment: + GOPATH: c:\gopath + +install: + - echo %PATH% + - echo %GOPATH% + - go version + - go env + - go get -v -t ./... + +build_script: + - go test -v ./... diff --git a/vendor/github.com/boltdb/bolt/bolt_386.go b/vendor/github.com/boltdb/bolt/bolt_386.go new file mode 100644 index 000000000..820d533c1 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/bolt_386.go @@ -0,0 +1,10 @@ +package bolt + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0x7FFFFFFF // 2GB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0xFFFFFFF + +// Are unaligned load/stores broken on this arch? +var brokenUnaligned = false diff --git a/vendor/github.com/boltdb/bolt/bolt_amd64.go b/vendor/github.com/boltdb/bolt/bolt_amd64.go new file mode 100644 index 000000000..98fafdb47 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/bolt_amd64.go @@ -0,0 +1,10 @@ +package bolt + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0xFFFFFFFFFFFF // 256TB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0x7FFFFFFF + +// Are unaligned load/stores broken on this arch? +var brokenUnaligned = false diff --git a/vendor/github.com/boltdb/bolt/bolt_arm.go b/vendor/github.com/boltdb/bolt/bolt_arm.go new file mode 100644 index 000000000..7e5cb4b94 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/bolt_arm.go @@ -0,0 +1,28 @@ +package bolt + +import "unsafe" + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0x7FFFFFFF // 2GB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0xFFFFFFF + +// Are unaligned load/stores broken on this arch? +var brokenUnaligned bool + +func init() { + // Simple check to see whether this arch handles unaligned load/stores + // correctly. + + // ARM9 and older devices require load/stores to be from/to aligned + // addresses. If not, the lower 2 bits are cleared and that address is + // read in a jumbled up order. + + // See http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka15414.html + + raw := [6]byte{0xfe, 0xef, 0x11, 0x22, 0x22, 0x11} + val := *(*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&raw)) + 2)) + + brokenUnaligned = val != 0x11222211 +} diff --git a/vendor/github.com/boltdb/bolt/bolt_arm64.go b/vendor/github.com/boltdb/bolt/bolt_arm64.go new file mode 100644 index 000000000..b26d84f91 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/bolt_arm64.go @@ -0,0 +1,12 @@ +// +build arm64 + +package bolt + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0xFFFFFFFFFFFF // 256TB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0x7FFFFFFF + +// Are unaligned load/stores broken on this arch? +var brokenUnaligned = false diff --git a/vendor/github.com/boltdb/bolt/bolt_linux.go b/vendor/github.com/boltdb/bolt/bolt_linux.go new file mode 100644 index 000000000..2b6766614 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/bolt_linux.go @@ -0,0 +1,10 @@ +package bolt + +import ( + "syscall" +) + +// fdatasync flushes written data to a file descriptor. +func fdatasync(db *DB) error { + return syscall.Fdatasync(int(db.file.Fd())) +} diff --git a/vendor/github.com/boltdb/bolt/bolt_openbsd.go b/vendor/github.com/boltdb/bolt/bolt_openbsd.go new file mode 100644 index 000000000..7058c3d73 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/bolt_openbsd.go @@ -0,0 +1,27 @@ +package bolt + +import ( + "syscall" + "unsafe" +) + +const ( + msAsync = 1 << iota // perform asynchronous writes + msSync // perform synchronous writes + msInvalidate // invalidate cached data +) + +func msync(db *DB) error { + _, _, errno := syscall.Syscall(syscall.SYS_MSYNC, uintptr(unsafe.Pointer(db.data)), uintptr(db.datasz), msInvalidate) + if errno != 0 { + return errno + } + return nil +} + +func fdatasync(db *DB) error { + if db.data != nil { + return msync(db) + } + return db.file.Sync() +} diff --git a/vendor/github.com/boltdb/bolt/bolt_ppc.go b/vendor/github.com/boltdb/bolt/bolt_ppc.go new file mode 100644 index 000000000..645ddc3ed --- /dev/null +++ b/vendor/github.com/boltdb/bolt/bolt_ppc.go @@ -0,0 +1,9 @@ +// +build ppc + +package bolt + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0x7FFFFFFF // 2GB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0xFFFFFFF diff --git a/vendor/github.com/boltdb/bolt/bolt_ppc64.go b/vendor/github.com/boltdb/bolt/bolt_ppc64.go new file mode 100644 index 000000000..9331d9771 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/bolt_ppc64.go @@ -0,0 +1,12 @@ +// +build ppc64 + +package bolt + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0xFFFFFFFFFFFF // 256TB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0x7FFFFFFF + +// Are unaligned load/stores broken on this arch? +var brokenUnaligned = false diff --git a/vendor/github.com/boltdb/bolt/bolt_ppc64le.go b/vendor/github.com/boltdb/bolt/bolt_ppc64le.go new file mode 100644 index 000000000..8c143bc5d --- /dev/null +++ b/vendor/github.com/boltdb/bolt/bolt_ppc64le.go @@ -0,0 +1,12 @@ +// +build ppc64le + +package bolt + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0xFFFFFFFFFFFF // 256TB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0x7FFFFFFF + +// Are unaligned load/stores broken on this arch? +var brokenUnaligned = false diff --git a/vendor/github.com/boltdb/bolt/bolt_s390x.go b/vendor/github.com/boltdb/bolt/bolt_s390x.go new file mode 100644 index 000000000..d7c39af92 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/bolt_s390x.go @@ -0,0 +1,12 @@ +// +build s390x + +package bolt + +// maxMapSize represents the largest mmap size supported by Bolt. +const maxMapSize = 0xFFFFFFFFFFFF // 256TB + +// maxAllocSize is the size used when creating array pointers. +const maxAllocSize = 0x7FFFFFFF + +// Are unaligned load/stores broken on this arch? +var brokenUnaligned = false diff --git a/vendor/github.com/boltdb/bolt/bolt_unix.go b/vendor/github.com/boltdb/bolt/bolt_unix.go new file mode 100644 index 000000000..cad62dda1 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/bolt_unix.go @@ -0,0 +1,89 @@ +// +build !windows,!plan9,!solaris + +package bolt + +import ( + "fmt" + "os" + "syscall" + "time" + "unsafe" +) + +// flock acquires an advisory lock on a file descriptor. +func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error { + var t time.Time + for { + // If we're beyond our timeout then return an error. + // This can only occur after we've attempted a flock once. + if t.IsZero() { + t = time.Now() + } else if timeout > 0 && time.Since(t) > timeout { + return ErrTimeout + } + flag := syscall.LOCK_SH + if exclusive { + flag = syscall.LOCK_EX + } + + // Otherwise attempt to obtain an exclusive lock. + err := syscall.Flock(int(db.file.Fd()), flag|syscall.LOCK_NB) + if err == nil { + return nil + } else if err != syscall.EWOULDBLOCK { + return err + } + + // Wait for a bit and try again. + time.Sleep(50 * time.Millisecond) + } +} + +// funlock releases an advisory lock on a file descriptor. +func funlock(db *DB) error { + return syscall.Flock(int(db.file.Fd()), syscall.LOCK_UN) +} + +// mmap memory maps a DB's data file. +func mmap(db *DB, sz int) error { + // Map the data file to memory. + b, err := syscall.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags) + if err != nil { + return err + } + + // Advise the kernel that the mmap is accessed randomly. + if err := madvise(b, syscall.MADV_RANDOM); err != nil { + return fmt.Errorf("madvise: %s", err) + } + + // Save the original byte slice and convert to a byte array pointer. + db.dataref = b + db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0])) + db.datasz = sz + return nil +} + +// munmap unmaps a DB's data file from memory. +func munmap(db *DB) error { + // Ignore the unmap if we have no mapped data. + if db.dataref == nil { + return nil + } + + // Unmap using the original byte slice. + err := syscall.Munmap(db.dataref) + db.dataref = nil + db.data = nil + db.datasz = 0 + return err +} + +// NOTE: This function is copied from stdlib because it is not available on darwin. +func madvise(b []byte, advice int) (err error) { + _, _, e1 := syscall.Syscall(syscall.SYS_MADVISE, uintptr(unsafe.Pointer(&b[0])), uintptr(len(b)), uintptr(advice)) + if e1 != 0 { + err = e1 + } + return +} diff --git a/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go b/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go new file mode 100644 index 000000000..307bf2b3e --- /dev/null +++ b/vendor/github.com/boltdb/bolt/bolt_unix_solaris.go @@ -0,0 +1,90 @@ +package bolt + +import ( + "fmt" + "os" + "syscall" + "time" + "unsafe" + + "golang.org/x/sys/unix" +) + +// flock acquires an advisory lock on a file descriptor. +func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error { + var t time.Time + for { + // If we're beyond our timeout then return an error. + // This can only occur after we've attempted a flock once. + if t.IsZero() { + t = time.Now() + } else if timeout > 0 && time.Since(t) > timeout { + return ErrTimeout + } + var lock syscall.Flock_t + lock.Start = 0 + lock.Len = 0 + lock.Pid = 0 + lock.Whence = 0 + lock.Pid = 0 + if exclusive { + lock.Type = syscall.F_WRLCK + } else { + lock.Type = syscall.F_RDLCK + } + err := syscall.FcntlFlock(db.file.Fd(), syscall.F_SETLK, &lock) + if err == nil { + return nil + } else if err != syscall.EAGAIN { + return err + } + + // Wait for a bit and try again. + time.Sleep(50 * time.Millisecond) + } +} + +// funlock releases an advisory lock on a file descriptor. +func funlock(db *DB) error { + var lock syscall.Flock_t + lock.Start = 0 + lock.Len = 0 + lock.Type = syscall.F_UNLCK + lock.Whence = 0 + return syscall.FcntlFlock(uintptr(db.file.Fd()), syscall.F_SETLK, &lock) +} + +// mmap memory maps a DB's data file. +func mmap(db *DB, sz int) error { + // Map the data file to memory. + b, err := unix.Mmap(int(db.file.Fd()), 0, sz, syscall.PROT_READ, syscall.MAP_SHARED|db.MmapFlags) + if err != nil { + return err + } + + // Advise the kernel that the mmap is accessed randomly. + if err := unix.Madvise(b, syscall.MADV_RANDOM); err != nil { + return fmt.Errorf("madvise: %s", err) + } + + // Save the original byte slice and convert to a byte array pointer. + db.dataref = b + db.data = (*[maxMapSize]byte)(unsafe.Pointer(&b[0])) + db.datasz = sz + return nil +} + +// munmap unmaps a DB's data file from memory. +func munmap(db *DB) error { + // Ignore the unmap if we have no mapped data. + if db.dataref == nil { + return nil + } + + // Unmap using the original byte slice. + err := unix.Munmap(db.dataref) + db.dataref = nil + db.data = nil + db.datasz = 0 + return err +} diff --git a/vendor/github.com/boltdb/bolt/bolt_windows.go b/vendor/github.com/boltdb/bolt/bolt_windows.go new file mode 100644 index 000000000..b00fb0720 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/bolt_windows.go @@ -0,0 +1,144 @@ +package bolt + +import ( + "fmt" + "os" + "syscall" + "time" + "unsafe" +) + +// LockFileEx code derived from golang build filemutex_windows.go @ v1.5.1 +var ( + modkernel32 = syscall.NewLazyDLL("kernel32.dll") + procLockFileEx = modkernel32.NewProc("LockFileEx") + procUnlockFileEx = modkernel32.NewProc("UnlockFileEx") +) + +const ( + lockExt = ".lock" + + // see https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203(v=vs.85).aspx + flagLockExclusive = 2 + flagLockFailImmediately = 1 + + // see https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx + errLockViolation syscall.Errno = 0x21 +) + +func lockFileEx(h syscall.Handle, flags, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) { + r, _, err := procLockFileEx.Call(uintptr(h), uintptr(flags), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol))) + if r == 0 { + return err + } + return nil +} + +func unlockFileEx(h syscall.Handle, reserved, locklow, lockhigh uint32, ol *syscall.Overlapped) (err error) { + r, _, err := procUnlockFileEx.Call(uintptr(h), uintptr(reserved), uintptr(locklow), uintptr(lockhigh), uintptr(unsafe.Pointer(ol)), 0) + if r == 0 { + return err + } + return nil +} + +// fdatasync flushes written data to a file descriptor. +func fdatasync(db *DB) error { + return db.file.Sync() +} + +// flock acquires an advisory lock on a file descriptor. +func flock(db *DB, mode os.FileMode, exclusive bool, timeout time.Duration) error { + // Create a separate lock file on windows because a process + // cannot share an exclusive lock on the same file. This is + // needed during Tx.WriteTo(). + f, err := os.OpenFile(db.path+lockExt, os.O_CREATE, mode) + if err != nil { + return err + } + db.lockfile = f + + var t time.Time + for { + // If we're beyond our timeout then return an error. + // This can only occur after we've attempted a flock once. + if t.IsZero() { + t = time.Now() + } else if timeout > 0 && time.Since(t) > timeout { + return ErrTimeout + } + + var flag uint32 = flagLockFailImmediately + if exclusive { + flag |= flagLockExclusive + } + + err := lockFileEx(syscall.Handle(db.lockfile.Fd()), flag, 0, 1, 0, &syscall.Overlapped{}) + if err == nil { + return nil + } else if err != errLockViolation { + return err + } + + // Wait for a bit and try again. + time.Sleep(50 * time.Millisecond) + } +} + +// funlock releases an advisory lock on a file descriptor. +func funlock(db *DB) error { + err := unlockFileEx(syscall.Handle(db.lockfile.Fd()), 0, 1, 0, &syscall.Overlapped{}) + db.lockfile.Close() + os.Remove(db.path + lockExt) + return err +} + +// mmap memory maps a DB's data file. +// Based on: https://github.com/edsrzf/mmap-go +func mmap(db *DB, sz int) error { + if !db.readOnly { + // Truncate the database to the size of the mmap. + if err := db.file.Truncate(int64(sz)); err != nil { + return fmt.Errorf("truncate: %s", err) + } + } + + // Open a file mapping handle. + sizelo := uint32(sz >> 32) + sizehi := uint32(sz) & 0xffffffff + h, errno := syscall.CreateFileMapping(syscall.Handle(db.file.Fd()), nil, syscall.PAGE_READONLY, sizelo, sizehi, nil) + if h == 0 { + return os.NewSyscallError("CreateFileMapping", errno) + } + + // Create the memory map. + addr, errno := syscall.MapViewOfFile(h, syscall.FILE_MAP_READ, 0, 0, uintptr(sz)) + if addr == 0 { + return os.NewSyscallError("MapViewOfFile", errno) + } + + // Close mapping handle. + if err := syscall.CloseHandle(syscall.Handle(h)); err != nil { + return os.NewSyscallError("CloseHandle", err) + } + + // Convert to a byte array. + db.data = ((*[maxMapSize]byte)(unsafe.Pointer(addr))) + db.datasz = sz + + return nil +} + +// munmap unmaps a pointer from a file. +// Based on: https://github.com/edsrzf/mmap-go +func munmap(db *DB) error { + if db.data == nil { + return nil + } + + addr := (uintptr)(unsafe.Pointer(&db.data[0])) + if err := syscall.UnmapViewOfFile(addr); err != nil { + return os.NewSyscallError("UnmapViewOfFile", err) + } + return nil +} diff --git a/vendor/github.com/boltdb/bolt/boltsync_unix.go b/vendor/github.com/boltdb/bolt/boltsync_unix.go new file mode 100644 index 000000000..f50442523 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/boltsync_unix.go @@ -0,0 +1,8 @@ +// +build !windows,!plan9,!linux,!openbsd + +package bolt + +// fdatasync flushes written data to a file descriptor. +func fdatasync(db *DB) error { + return db.file.Sync() +} diff --git a/vendor/github.com/boltdb/bolt/bucket.go b/vendor/github.com/boltdb/bolt/bucket.go new file mode 100644 index 000000000..0c5bf2746 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/bucket.go @@ -0,0 +1,777 @@ +package bolt + +import ( + "bytes" + "fmt" + "unsafe" +) + +const ( + // MaxKeySize is the maximum length of a key, in bytes. + MaxKeySize = 32768 + + // MaxValueSize is the maximum length of a value, in bytes. + MaxValueSize = (1 << 31) - 2 +) + +const ( + maxUint = ^uint(0) + minUint = 0 + maxInt = int(^uint(0) >> 1) + minInt = -maxInt - 1 +) + +const bucketHeaderSize = int(unsafe.Sizeof(bucket{})) + +const ( + minFillPercent = 0.1 + maxFillPercent = 1.0 +) + +// DefaultFillPercent is the percentage that split pages are filled. +// This value can be changed by setting Bucket.FillPercent. +const DefaultFillPercent = 0.5 + +// Bucket represents a collection of key/value pairs inside the database. +type Bucket struct { + *bucket + tx *Tx // the associated transaction + buckets map[string]*Bucket // subbucket cache + page *page // inline page reference + rootNode *node // materialized node for the root page. + nodes map[pgid]*node // node cache + + // Sets the threshold for filling nodes when they split. By default, + // the bucket will fill to 50% but it can be useful to increase this + // amount if you know that your write workloads are mostly append-only. + // + // This is non-persisted across transactions so it must be set in every Tx. + FillPercent float64 +} + +// bucket represents the on-file representation of a bucket. +// This is stored as the "value" of a bucket key. If the bucket is small enough, +// then its root page can be stored inline in the "value", after the bucket +// header. In the case of inline buckets, the "root" will be 0. +type bucket struct { + root pgid // page id of the bucket's root-level page + sequence uint64 // monotonically incrementing, used by NextSequence() +} + +// newBucket returns a new bucket associated with a transaction. +func newBucket(tx *Tx) Bucket { + var b = Bucket{tx: tx, FillPercent: DefaultFillPercent} + if tx.writable { + b.buckets = make(map[string]*Bucket) + b.nodes = make(map[pgid]*node) + } + return b +} + +// Tx returns the tx of the bucket. +func (b *Bucket) Tx() *Tx { + return b.tx +} + +// Root returns the root of the bucket. +func (b *Bucket) Root() pgid { + return b.root +} + +// Writable returns whether the bucket is writable. +func (b *Bucket) Writable() bool { + return b.tx.writable +} + +// Cursor creates a cursor associated with the bucket. +// The cursor is only valid as long as the transaction is open. +// Do not use a cursor after the transaction is closed. +func (b *Bucket) Cursor() *Cursor { + // Update transaction statistics. + b.tx.stats.CursorCount++ + + // Allocate and return a cursor. + return &Cursor{ + bucket: b, + stack: make([]elemRef, 0), + } +} + +// Bucket retrieves a nested bucket by name. +// Returns nil if the bucket does not exist. +// The bucket instance is only valid for the lifetime of the transaction. +func (b *Bucket) Bucket(name []byte) *Bucket { + if b.buckets != nil { + if child := b.buckets[string(name)]; child != nil { + return child + } + } + + // Move cursor to key. + c := b.Cursor() + k, v, flags := c.seek(name) + + // Return nil if the key doesn't exist or it is not a bucket. + if !bytes.Equal(name, k) || (flags&bucketLeafFlag) == 0 { + return nil + } + + // Otherwise create a bucket and cache it. + var child = b.openBucket(v) + if b.buckets != nil { + b.buckets[string(name)] = child + } + + return child +} + +// Helper method that re-interprets a sub-bucket value +// from a parent into a Bucket +func (b *Bucket) openBucket(value []byte) *Bucket { + var child = newBucket(b.tx) + + // If unaligned load/stores are broken on this arch and value is + // unaligned simply clone to an aligned byte array. + unaligned := brokenUnaligned && uintptr(unsafe.Pointer(&value[0]))&3 != 0 + + if unaligned { + value = cloneBytes(value) + } + + // If this is a writable transaction then we need to copy the bucket entry. + // Read-only transactions can point directly at the mmap entry. + if b.tx.writable && !unaligned { + child.bucket = &bucket{} + *child.bucket = *(*bucket)(unsafe.Pointer(&value[0])) + } else { + child.bucket = (*bucket)(unsafe.Pointer(&value[0])) + } + + // Save a reference to the inline page if the bucket is inline. + if child.root == 0 { + child.page = (*page)(unsafe.Pointer(&value[bucketHeaderSize])) + } + + return &child +} + +// CreateBucket creates a new bucket at the given key and returns the new bucket. +// Returns an error if the key already exists, if the bucket name is blank, or if the bucket name is too long. +// The bucket instance is only valid for the lifetime of the transaction. +func (b *Bucket) CreateBucket(key []byte) (*Bucket, error) { + if b.tx.db == nil { + return nil, ErrTxClosed + } else if !b.tx.writable { + return nil, ErrTxNotWritable + } else if len(key) == 0 { + return nil, ErrBucketNameRequired + } + + // Move cursor to correct position. + c := b.Cursor() + k, _, flags := c.seek(key) + + // Return an error if there is an existing key. + if bytes.Equal(key, k) { + if (flags & bucketLeafFlag) != 0 { + return nil, ErrBucketExists + } + return nil, ErrIncompatibleValue + } + + // Create empty, inline bucket. + var bucket = Bucket{ + bucket: &bucket{}, + rootNode: &node{isLeaf: true}, + FillPercent: DefaultFillPercent, + } + var value = bucket.write() + + // Insert into node. + key = cloneBytes(key) + c.node().put(key, key, value, 0, bucketLeafFlag) + + // Since subbuckets are not allowed on inline buckets, we need to + // dereference the inline page, if it exists. This will cause the bucket + // to be treated as a regular, non-inline bucket for the rest of the tx. + b.page = nil + + return b.Bucket(key), nil +} + +// CreateBucketIfNotExists creates a new bucket if it doesn't already exist and returns a reference to it. +// Returns an error if the bucket name is blank, or if the bucket name is too long. +// The bucket instance is only valid for the lifetime of the transaction. +func (b *Bucket) CreateBucketIfNotExists(key []byte) (*Bucket, error) { + child, err := b.CreateBucket(key) + if err == ErrBucketExists { + return b.Bucket(key), nil + } else if err != nil { + return nil, err + } + return child, nil +} + +// DeleteBucket deletes a bucket at the given key. +// Returns an error if the bucket does not exists, or if the key represents a non-bucket value. +func (b *Bucket) DeleteBucket(key []byte) error { + if b.tx.db == nil { + return ErrTxClosed + } else if !b.Writable() { + return ErrTxNotWritable + } + + // Move cursor to correct position. + c := b.Cursor() + k, _, flags := c.seek(key) + + // Return an error if bucket doesn't exist or is not a bucket. + if !bytes.Equal(key, k) { + return ErrBucketNotFound + } else if (flags & bucketLeafFlag) == 0 { + return ErrIncompatibleValue + } + + // Recursively delete all child buckets. + child := b.Bucket(key) + err := child.ForEach(func(k, v []byte) error { + if v == nil { + if err := child.DeleteBucket(k); err != nil { + return fmt.Errorf("delete bucket: %s", err) + } + } + return nil + }) + if err != nil { + return err + } + + // Remove cached copy. + delete(b.buckets, string(key)) + + // Release all bucket pages to freelist. + child.nodes = nil + child.rootNode = nil + child.free() + + // Delete the node if we have a matching key. + c.node().del(key) + + return nil +} + +// Get retrieves the value for a key in the bucket. +// Returns a nil value if the key does not exist or if the key is a nested bucket. +// The returned value is only valid for the life of the transaction. +func (b *Bucket) Get(key []byte) []byte { + k, v, flags := b.Cursor().seek(key) + + // Return nil if this is a bucket. + if (flags & bucketLeafFlag) != 0 { + return nil + } + + // If our target node isn't the same key as what's passed in then return nil. + if !bytes.Equal(key, k) { + return nil + } + return v +} + +// Put sets the value for a key in the bucket. +// If the key exist then its previous value will be overwritten. +// Supplied value must remain valid for the life of the transaction. +// Returns an error if the bucket was created from a read-only transaction, if the key is blank, if the key is too large, or if the value is too large. +func (b *Bucket) Put(key []byte, value []byte) error { + if b.tx.db == nil { + return ErrTxClosed + } else if !b.Writable() { + return ErrTxNotWritable + } else if len(key) == 0 { + return ErrKeyRequired + } else if len(key) > MaxKeySize { + return ErrKeyTooLarge + } else if int64(len(value)) > MaxValueSize { + return ErrValueTooLarge + } + + // Move cursor to correct position. + c := b.Cursor() + k, _, flags := c.seek(key) + + // Return an error if there is an existing key with a bucket value. + if bytes.Equal(key, k) && (flags&bucketLeafFlag) != 0 { + return ErrIncompatibleValue + } + + // Insert into node. + key = cloneBytes(key) + c.node().put(key, key, value, 0, 0) + + return nil +} + +// Delete removes a key from the bucket. +// If the key does not exist then nothing is done and a nil error is returned. +// Returns an error if the bucket was created from a read-only transaction. +func (b *Bucket) Delete(key []byte) error { + if b.tx.db == nil { + return ErrTxClosed + } else if !b.Writable() { + return ErrTxNotWritable + } + + // Move cursor to correct position. + c := b.Cursor() + _, _, flags := c.seek(key) + + // Return an error if there is already existing bucket value. + if (flags & bucketLeafFlag) != 0 { + return ErrIncompatibleValue + } + + // Delete the node if we have a matching key. + c.node().del(key) + + return nil +} + +// Sequence returns the current integer for the bucket without incrementing it. +func (b *Bucket) Sequence() uint64 { return b.bucket.sequence } + +// SetSequence updates the sequence number for the bucket. +func (b *Bucket) SetSequence(v uint64) error { + if b.tx.db == nil { + return ErrTxClosed + } else if !b.Writable() { + return ErrTxNotWritable + } + + // Materialize the root node if it hasn't been already so that the + // bucket will be saved during commit. + if b.rootNode == nil { + _ = b.node(b.root, nil) + } + + // Increment and return the sequence. + b.bucket.sequence = v + return nil +} + +// NextSequence returns an autoincrementing integer for the bucket. +func (b *Bucket) NextSequence() (uint64, error) { + if b.tx.db == nil { + return 0, ErrTxClosed + } else if !b.Writable() { + return 0, ErrTxNotWritable + } + + // Materialize the root node if it hasn't been already so that the + // bucket will be saved during commit. + if b.rootNode == nil { + _ = b.node(b.root, nil) + } + + // Increment and return the sequence. + b.bucket.sequence++ + return b.bucket.sequence, nil +} + +// ForEach executes a function for each key/value pair in a bucket. +// If the provided function returns an error then the iteration is stopped and +// the error is returned to the caller. The provided function must not modify +// the bucket; this will result in undefined behavior. +func (b *Bucket) ForEach(fn func(k, v []byte) error) error { + if b.tx.db == nil { + return ErrTxClosed + } + c := b.Cursor() + for k, v := c.First(); k != nil; k, v = c.Next() { + if err := fn(k, v); err != nil { + return err + } + } + return nil +} + +// Stat returns stats on a bucket. +func (b *Bucket) Stats() BucketStats { + var s, subStats BucketStats + pageSize := b.tx.db.pageSize + s.BucketN += 1 + if b.root == 0 { + s.InlineBucketN += 1 + } + b.forEachPage(func(p *page, depth int) { + if (p.flags & leafPageFlag) != 0 { + s.KeyN += int(p.count) + + // used totals the used bytes for the page + used := pageHeaderSize + + if p.count != 0 { + // If page has any elements, add all element headers. + used += leafPageElementSize * int(p.count-1) + + // Add all element key, value sizes. + // The computation takes advantage of the fact that the position + // of the last element's key/value equals to the total of the sizes + // of all previous elements' keys and values. + // It also includes the last element's header. + lastElement := p.leafPageElement(p.count - 1) + used += int(lastElement.pos + lastElement.ksize + lastElement.vsize) + } + + if b.root == 0 { + // For inlined bucket just update the inline stats + s.InlineBucketInuse += used + } else { + // For non-inlined bucket update all the leaf stats + s.LeafPageN++ + s.LeafInuse += used + s.LeafOverflowN += int(p.overflow) + + // Collect stats from sub-buckets. + // Do that by iterating over all element headers + // looking for the ones with the bucketLeafFlag. + for i := uint16(0); i < p.count; i++ { + e := p.leafPageElement(i) + if (e.flags & bucketLeafFlag) != 0 { + // For any bucket element, open the element value + // and recursively call Stats on the contained bucket. + subStats.Add(b.openBucket(e.value()).Stats()) + } + } + } + } else if (p.flags & branchPageFlag) != 0 { + s.BranchPageN++ + lastElement := p.branchPageElement(p.count - 1) + + // used totals the used bytes for the page + // Add header and all element headers. + used := pageHeaderSize + (branchPageElementSize * int(p.count-1)) + + // Add size of all keys and values. + // Again, use the fact that last element's position equals to + // the total of key, value sizes of all previous elements. + used += int(lastElement.pos + lastElement.ksize) + s.BranchInuse += used + s.BranchOverflowN += int(p.overflow) + } + + // Keep track of maximum page depth. + if depth+1 > s.Depth { + s.Depth = (depth + 1) + } + }) + + // Alloc stats can be computed from page counts and pageSize. + s.BranchAlloc = (s.BranchPageN + s.BranchOverflowN) * pageSize + s.LeafAlloc = (s.LeafPageN + s.LeafOverflowN) * pageSize + + // Add the max depth of sub-buckets to get total nested depth. + s.Depth += subStats.Depth + // Add the stats for all sub-buckets + s.Add(subStats) + return s +} + +// forEachPage iterates over every page in a bucket, including inline pages. +func (b *Bucket) forEachPage(fn func(*page, int)) { + // If we have an inline page then just use that. + if b.page != nil { + fn(b.page, 0) + return + } + + // Otherwise traverse the page hierarchy. + b.tx.forEachPage(b.root, 0, fn) +} + +// forEachPageNode iterates over every page (or node) in a bucket. +// This also includes inline pages. +func (b *Bucket) forEachPageNode(fn func(*page, *node, int)) { + // If we have an inline page or root node then just use that. + if b.page != nil { + fn(b.page, nil, 0) + return + } + b._forEachPageNode(b.root, 0, fn) +} + +func (b *Bucket) _forEachPageNode(pgid pgid, depth int, fn func(*page, *node, int)) { + var p, n = b.pageNode(pgid) + + // Execute function. + fn(p, n, depth) + + // Recursively loop over children. + if p != nil { + if (p.flags & branchPageFlag) != 0 { + for i := 0; i < int(p.count); i++ { + elem := p.branchPageElement(uint16(i)) + b._forEachPageNode(elem.pgid, depth+1, fn) + } + } + } else { + if !n.isLeaf { + for _, inode := range n.inodes { + b._forEachPageNode(inode.pgid, depth+1, fn) + } + } + } +} + +// spill writes all the nodes for this bucket to dirty pages. +func (b *Bucket) spill() error { + // Spill all child buckets first. + for name, child := range b.buckets { + // If the child bucket is small enough and it has no child buckets then + // write it inline into the parent bucket's page. Otherwise spill it + // like a normal bucket and make the parent value a pointer to the page. + var value []byte + if child.inlineable() { + child.free() + value = child.write() + } else { + if err := child.spill(); err != nil { + return err + } + + // Update the child bucket header in this bucket. + value = make([]byte, unsafe.Sizeof(bucket{})) + var bucket = (*bucket)(unsafe.Pointer(&value[0])) + *bucket = *child.bucket + } + + // Skip writing the bucket if there are no materialized nodes. + if child.rootNode == nil { + continue + } + + // Update parent node. + var c = b.Cursor() + k, _, flags := c.seek([]byte(name)) + if !bytes.Equal([]byte(name), k) { + panic(fmt.Sprintf("misplaced bucket header: %x -> %x", []byte(name), k)) + } + if flags&bucketLeafFlag == 0 { + panic(fmt.Sprintf("unexpected bucket header flag: %x", flags)) + } + c.node().put([]byte(name), []byte(name), value, 0, bucketLeafFlag) + } + + // Ignore if there's not a materialized root node. + if b.rootNode == nil { + return nil + } + + // Spill nodes. + if err := b.rootNode.spill(); err != nil { + return err + } + b.rootNode = b.rootNode.root() + + // Update the root node for this bucket. + if b.rootNode.pgid >= b.tx.meta.pgid { + panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", b.rootNode.pgid, b.tx.meta.pgid)) + } + b.root = b.rootNode.pgid + + return nil +} + +// inlineable returns true if a bucket is small enough to be written inline +// and if it contains no subbuckets. Otherwise returns false. +func (b *Bucket) inlineable() bool { + var n = b.rootNode + + // Bucket must only contain a single leaf node. + if n == nil || !n.isLeaf { + return false + } + + // Bucket is not inlineable if it contains subbuckets or if it goes beyond + // our threshold for inline bucket size. + var size = pageHeaderSize + for _, inode := range n.inodes { + size += leafPageElementSize + len(inode.key) + len(inode.value) + + if inode.flags&bucketLeafFlag != 0 { + return false + } else if size > b.maxInlineBucketSize() { + return false + } + } + + return true +} + +// Returns the maximum total size of a bucket to make it a candidate for inlining. +func (b *Bucket) maxInlineBucketSize() int { + return b.tx.db.pageSize / 4 +} + +// write allocates and writes a bucket to a byte slice. +func (b *Bucket) write() []byte { + // Allocate the appropriate size. + var n = b.rootNode + var value = make([]byte, bucketHeaderSize+n.size()) + + // Write a bucket header. + var bucket = (*bucket)(unsafe.Pointer(&value[0])) + *bucket = *b.bucket + + // Convert byte slice to a fake page and write the root node. + var p = (*page)(unsafe.Pointer(&value[bucketHeaderSize])) + n.write(p) + + return value +} + +// rebalance attempts to balance all nodes. +func (b *Bucket) rebalance() { + for _, n := range b.nodes { + n.rebalance() + } + for _, child := range b.buckets { + child.rebalance() + } +} + +// node creates a node from a page and associates it with a given parent. +func (b *Bucket) node(pgid pgid, parent *node) *node { + _assert(b.nodes != nil, "nodes map expected") + + // Retrieve node if it's already been created. + if n := b.nodes[pgid]; n != nil { + return n + } + + // Otherwise create a node and cache it. + n := &node{bucket: b, parent: parent} + if parent == nil { + b.rootNode = n + } else { + parent.children = append(parent.children, n) + } + + // Use the inline page if this is an inline bucket. + var p = b.page + if p == nil { + p = b.tx.page(pgid) + } + + // Read the page into the node and cache it. + n.read(p) + b.nodes[pgid] = n + + // Update statistics. + b.tx.stats.NodeCount++ + + return n +} + +// free recursively frees all pages in the bucket. +func (b *Bucket) free() { + if b.root == 0 { + return + } + + var tx = b.tx + b.forEachPageNode(func(p *page, n *node, _ int) { + if p != nil { + tx.db.freelist.free(tx.meta.txid, p) + } else { + n.free() + } + }) + b.root = 0 +} + +// dereference removes all references to the old mmap. +func (b *Bucket) dereference() { + if b.rootNode != nil { + b.rootNode.root().dereference() + } + + for _, child := range b.buckets { + child.dereference() + } +} + +// pageNode returns the in-memory node, if it exists. +// Otherwise returns the underlying page. +func (b *Bucket) pageNode(id pgid) (*page, *node) { + // Inline buckets have a fake page embedded in their value so treat them + // differently. We'll return the rootNode (if available) or the fake page. + if b.root == 0 { + if id != 0 { + panic(fmt.Sprintf("inline bucket non-zero page access(2): %d != 0", id)) + } + if b.rootNode != nil { + return nil, b.rootNode + } + return b.page, nil + } + + // Check the node cache for non-inline buckets. + if b.nodes != nil { + if n := b.nodes[id]; n != nil { + return nil, n + } + } + + // Finally lookup the page from the transaction if no node is materialized. + return b.tx.page(id), nil +} + +// BucketStats records statistics about resources used by a bucket. +type BucketStats struct { + // Page count statistics. + BranchPageN int // number of logical branch pages + BranchOverflowN int // number of physical branch overflow pages + LeafPageN int // number of logical leaf pages + LeafOverflowN int // number of physical leaf overflow pages + + // Tree statistics. + KeyN int // number of keys/value pairs + Depth int // number of levels in B+tree + + // Page size utilization. + BranchAlloc int // bytes allocated for physical branch pages + BranchInuse int // bytes actually used for branch data + LeafAlloc int // bytes allocated for physical leaf pages + LeafInuse int // bytes actually used for leaf data + + // Bucket statistics + BucketN int // total number of buckets including the top bucket + InlineBucketN int // total number on inlined buckets + InlineBucketInuse int // bytes used for inlined buckets (also accounted for in LeafInuse) +} + +func (s *BucketStats) Add(other BucketStats) { + s.BranchPageN += other.BranchPageN + s.BranchOverflowN += other.BranchOverflowN + s.LeafPageN += other.LeafPageN + s.LeafOverflowN += other.LeafOverflowN + s.KeyN += other.KeyN + if s.Depth < other.Depth { + s.Depth = other.Depth + } + s.BranchAlloc += other.BranchAlloc + s.BranchInuse += other.BranchInuse + s.LeafAlloc += other.LeafAlloc + s.LeafInuse += other.LeafInuse + + s.BucketN += other.BucketN + s.InlineBucketN += other.InlineBucketN + s.InlineBucketInuse += other.InlineBucketInuse +} + +// cloneBytes returns a copy of a given slice. +func cloneBytes(v []byte) []byte { + var clone = make([]byte, len(v)) + copy(clone, v) + return clone +} diff --git a/vendor/github.com/boltdb/bolt/cursor.go b/vendor/github.com/boltdb/bolt/cursor.go new file mode 100644 index 000000000..1be9f35e3 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/cursor.go @@ -0,0 +1,400 @@ +package bolt + +import ( + "bytes" + "fmt" + "sort" +) + +// Cursor represents an iterator that can traverse over all key/value pairs in a bucket in sorted order. +// Cursors see nested buckets with value == nil. +// Cursors can be obtained from a transaction and are valid as long as the transaction is open. +// +// Keys and values returned from the cursor are only valid for the life of the transaction. +// +// Changing data while traversing with a cursor may cause it to be invalidated +// and return unexpected keys and/or values. You must reposition your cursor +// after mutating data. +type Cursor struct { + bucket *Bucket + stack []elemRef +} + +// Bucket returns the bucket that this cursor was created from. +func (c *Cursor) Bucket() *Bucket { + return c.bucket +} + +// First moves the cursor to the first item in the bucket and returns its key and value. +// If the bucket is empty then a nil key and value are returned. +// The returned key and value are only valid for the life of the transaction. +func (c *Cursor) First() (key []byte, value []byte) { + _assert(c.bucket.tx.db != nil, "tx closed") + c.stack = c.stack[:0] + p, n := c.bucket.pageNode(c.bucket.root) + c.stack = append(c.stack, elemRef{page: p, node: n, index: 0}) + c.first() + + // If we land on an empty page then move to the next value. + // https://github.com/boltdb/bolt/issues/450 + if c.stack[len(c.stack)-1].count() == 0 { + c.next() + } + + k, v, flags := c.keyValue() + if (flags & uint32(bucketLeafFlag)) != 0 { + return k, nil + } + return k, v + +} + +// Last moves the cursor to the last item in the bucket and returns its key and value. +// If the bucket is empty then a nil key and value are returned. +// The returned key and value are only valid for the life of the transaction. +func (c *Cursor) Last() (key []byte, value []byte) { + _assert(c.bucket.tx.db != nil, "tx closed") + c.stack = c.stack[:0] + p, n := c.bucket.pageNode(c.bucket.root) + ref := elemRef{page: p, node: n} + ref.index = ref.count() - 1 + c.stack = append(c.stack, ref) + c.last() + k, v, flags := c.keyValue() + if (flags & uint32(bucketLeafFlag)) != 0 { + return k, nil + } + return k, v +} + +// Next moves the cursor to the next item in the bucket and returns its key and value. +// If the cursor is at the end of the bucket then a nil key and value are returned. +// The returned key and value are only valid for the life of the transaction. +func (c *Cursor) Next() (key []byte, value []byte) { + _assert(c.bucket.tx.db != nil, "tx closed") + k, v, flags := c.next() + if (flags & uint32(bucketLeafFlag)) != 0 { + return k, nil + } + return k, v +} + +// Prev moves the cursor to the previous item in the bucket and returns its key and value. +// If the cursor is at the beginning of the bucket then a nil key and value are returned. +// The returned key and value are only valid for the life of the transaction. +func (c *Cursor) Prev() (key []byte, value []byte) { + _assert(c.bucket.tx.db != nil, "tx closed") + + // Attempt to move back one element until we're successful. + // Move up the stack as we hit the beginning of each page in our stack. + for i := len(c.stack) - 1; i >= 0; i-- { + elem := &c.stack[i] + if elem.index > 0 { + elem.index-- + break + } + c.stack = c.stack[:i] + } + + // If we've hit the end then return nil. + if len(c.stack) == 0 { + return nil, nil + } + + // Move down the stack to find the last element of the last leaf under this branch. + c.last() + k, v, flags := c.keyValue() + if (flags & uint32(bucketLeafFlag)) != 0 { + return k, nil + } + return k, v +} + +// Seek moves the cursor to a given key and returns it. +// If the key does not exist then the next key is used. If no keys +// follow, a nil key is returned. +// The returned key and value are only valid for the life of the transaction. +func (c *Cursor) Seek(seek []byte) (key []byte, value []byte) { + k, v, flags := c.seek(seek) + + // If we ended up after the last element of a page then move to the next one. + if ref := &c.stack[len(c.stack)-1]; ref.index >= ref.count() { + k, v, flags = c.next() + } + + if k == nil { + return nil, nil + } else if (flags & uint32(bucketLeafFlag)) != 0 { + return k, nil + } + return k, v +} + +// Delete removes the current key/value under the cursor from the bucket. +// Delete fails if current key/value is a bucket or if the transaction is not writable. +func (c *Cursor) Delete() error { + if c.bucket.tx.db == nil { + return ErrTxClosed + } else if !c.bucket.Writable() { + return ErrTxNotWritable + } + + key, _, flags := c.keyValue() + // Return an error if current value is a bucket. + if (flags & bucketLeafFlag) != 0 { + return ErrIncompatibleValue + } + c.node().del(key) + + return nil +} + +// seek moves the cursor to a given key and returns it. +// If the key does not exist then the next key is used. +func (c *Cursor) seek(seek []byte) (key []byte, value []byte, flags uint32) { + _assert(c.bucket.tx.db != nil, "tx closed") + + // Start from root page/node and traverse to correct page. + c.stack = c.stack[:0] + c.search(seek, c.bucket.root) + ref := &c.stack[len(c.stack)-1] + + // If the cursor is pointing to the end of page/node then return nil. + if ref.index >= ref.count() { + return nil, nil, 0 + } + + // If this is a bucket then return a nil value. + return c.keyValue() +} + +// first moves the cursor to the first leaf element under the last page in the stack. +func (c *Cursor) first() { + for { + // Exit when we hit a leaf page. + var ref = &c.stack[len(c.stack)-1] + if ref.isLeaf() { + break + } + + // Keep adding pages pointing to the first element to the stack. + var pgid pgid + if ref.node != nil { + pgid = ref.node.inodes[ref.index].pgid + } else { + pgid = ref.page.branchPageElement(uint16(ref.index)).pgid + } + p, n := c.bucket.pageNode(pgid) + c.stack = append(c.stack, elemRef{page: p, node: n, index: 0}) + } +} + +// last moves the cursor to the last leaf element under the last page in the stack. +func (c *Cursor) last() { + for { + // Exit when we hit a leaf page. + ref := &c.stack[len(c.stack)-1] + if ref.isLeaf() { + break + } + + // Keep adding pages pointing to the last element in the stack. + var pgid pgid + if ref.node != nil { + pgid = ref.node.inodes[ref.index].pgid + } else { + pgid = ref.page.branchPageElement(uint16(ref.index)).pgid + } + p, n := c.bucket.pageNode(pgid) + + var nextRef = elemRef{page: p, node: n} + nextRef.index = nextRef.count() - 1 + c.stack = append(c.stack, nextRef) + } +} + +// next moves to the next leaf element and returns the key and value. +// If the cursor is at the last leaf element then it stays there and returns nil. +func (c *Cursor) next() (key []byte, value []byte, flags uint32) { + for { + // Attempt to move over one element until we're successful. + // Move up the stack as we hit the end of each page in our stack. + var i int + for i = len(c.stack) - 1; i >= 0; i-- { + elem := &c.stack[i] + if elem.index < elem.count()-1 { + elem.index++ + break + } + } + + // If we've hit the root page then stop and return. This will leave the + // cursor on the last element of the last page. + if i == -1 { + return nil, nil, 0 + } + + // Otherwise start from where we left off in the stack and find the + // first element of the first leaf page. + c.stack = c.stack[:i+1] + c.first() + + // If this is an empty page then restart and move back up the stack. + // https://github.com/boltdb/bolt/issues/450 + if c.stack[len(c.stack)-1].count() == 0 { + continue + } + + return c.keyValue() + } +} + +// search recursively performs a binary search against a given page/node until it finds a given key. +func (c *Cursor) search(key []byte, pgid pgid) { + p, n := c.bucket.pageNode(pgid) + if p != nil && (p.flags&(branchPageFlag|leafPageFlag)) == 0 { + panic(fmt.Sprintf("invalid page type: %d: %x", p.id, p.flags)) + } + e := elemRef{page: p, node: n} + c.stack = append(c.stack, e) + + // If we're on a leaf page/node then find the specific node. + if e.isLeaf() { + c.nsearch(key) + return + } + + if n != nil { + c.searchNode(key, n) + return + } + c.searchPage(key, p) +} + +func (c *Cursor) searchNode(key []byte, n *node) { + var exact bool + index := sort.Search(len(n.inodes), func(i int) bool { + // TODO(benbjohnson): Optimize this range search. It's a bit hacky right now. + // sort.Search() finds the lowest index where f() != -1 but we need the highest index. + ret := bytes.Compare(n.inodes[i].key, key) + if ret == 0 { + exact = true + } + return ret != -1 + }) + if !exact && index > 0 { + index-- + } + c.stack[len(c.stack)-1].index = index + + // Recursively search to the next page. + c.search(key, n.inodes[index].pgid) +} + +func (c *Cursor) searchPage(key []byte, p *page) { + // Binary search for the correct range. + inodes := p.branchPageElements() + + var exact bool + index := sort.Search(int(p.count), func(i int) bool { + // TODO(benbjohnson): Optimize this range search. It's a bit hacky right now. + // sort.Search() finds the lowest index where f() != -1 but we need the highest index. + ret := bytes.Compare(inodes[i].key(), key) + if ret == 0 { + exact = true + } + return ret != -1 + }) + if !exact && index > 0 { + index-- + } + c.stack[len(c.stack)-1].index = index + + // Recursively search to the next page. + c.search(key, inodes[index].pgid) +} + +// nsearch searches the leaf node on the top of the stack for a key. +func (c *Cursor) nsearch(key []byte) { + e := &c.stack[len(c.stack)-1] + p, n := e.page, e.node + + // If we have a node then search its inodes. + if n != nil { + index := sort.Search(len(n.inodes), func(i int) bool { + return bytes.Compare(n.inodes[i].key, key) != -1 + }) + e.index = index + return + } + + // If we have a page then search its leaf elements. + inodes := p.leafPageElements() + index := sort.Search(int(p.count), func(i int) bool { + return bytes.Compare(inodes[i].key(), key) != -1 + }) + e.index = index +} + +// keyValue returns the key and value of the current leaf element. +func (c *Cursor) keyValue() ([]byte, []byte, uint32) { + ref := &c.stack[len(c.stack)-1] + if ref.count() == 0 || ref.index >= ref.count() { + return nil, nil, 0 + } + + // Retrieve value from node. + if ref.node != nil { + inode := &ref.node.inodes[ref.index] + return inode.key, inode.value, inode.flags + } + + // Or retrieve value from page. + elem := ref.page.leafPageElement(uint16(ref.index)) + return elem.key(), elem.value(), elem.flags +} + +// node returns the node that the cursor is currently positioned on. +func (c *Cursor) node() *node { + _assert(len(c.stack) > 0, "accessing a node with a zero-length cursor stack") + + // If the top of the stack is a leaf node then just return it. + if ref := &c.stack[len(c.stack)-1]; ref.node != nil && ref.isLeaf() { + return ref.node + } + + // Start from root and traverse down the hierarchy. + var n = c.stack[0].node + if n == nil { + n = c.bucket.node(c.stack[0].page.id, nil) + } + for _, ref := range c.stack[:len(c.stack)-1] { + _assert(!n.isLeaf, "expected branch node") + n = n.childAt(int(ref.index)) + } + _assert(n.isLeaf, "expected leaf node") + return n +} + +// elemRef represents a reference to an element on a given page/node. +type elemRef struct { + page *page + node *node + index int +} + +// isLeaf returns whether the ref is pointing at a leaf page/node. +func (r *elemRef) isLeaf() bool { + if r.node != nil { + return r.node.isLeaf + } + return (r.page.flags & leafPageFlag) != 0 +} + +// count returns the number of inodes or page elements. +func (r *elemRef) count() int { + if r.node != nil { + return len(r.node.inodes) + } + return int(r.page.count) +} diff --git a/vendor/github.com/boltdb/bolt/db.go b/vendor/github.com/boltdb/bolt/db.go new file mode 100644 index 000000000..f352ff14f --- /dev/null +++ b/vendor/github.com/boltdb/bolt/db.go @@ -0,0 +1,1039 @@ +package bolt + +import ( + "errors" + "fmt" + "hash/fnv" + "log" + "os" + "runtime" + "runtime/debug" + "strings" + "sync" + "time" + "unsafe" +) + +// The largest step that can be taken when remapping the mmap. +const maxMmapStep = 1 << 30 // 1GB + +// The data file format version. +const version = 2 + +// Represents a marker value to indicate that a file is a Bolt DB. +const magic uint32 = 0xED0CDAED + +// IgnoreNoSync specifies whether the NoSync field of a DB is ignored when +// syncing changes to a file. This is required as some operating systems, +// such as OpenBSD, do not have a unified buffer cache (UBC) and writes +// must be synchronized using the msync(2) syscall. +const IgnoreNoSync = runtime.GOOS == "openbsd" + +// Default values if not set in a DB instance. +const ( + DefaultMaxBatchSize int = 1000 + DefaultMaxBatchDelay = 10 * time.Millisecond + DefaultAllocSize = 16 * 1024 * 1024 +) + +// default page size for db is set to the OS page size. +var defaultPageSize = os.Getpagesize() + +// DB represents a collection of buckets persisted to a file on disk. +// All data access is performed through transactions which can be obtained through the DB. +// All the functions on DB will return a ErrDatabaseNotOpen if accessed before Open() is called. +type DB struct { + // When enabled, the database will perform a Check() after every commit. + // A panic is issued if the database is in an inconsistent state. This + // flag has a large performance impact so it should only be used for + // debugging purposes. + StrictMode bool + + // Setting the NoSync flag will cause the database to skip fsync() + // calls after each commit. This can be useful when bulk loading data + // into a database and you can restart the bulk load in the event of + // a system failure or database corruption. Do not set this flag for + // normal use. + // + // If the package global IgnoreNoSync constant is true, this value is + // ignored. See the comment on that constant for more details. + // + // THIS IS UNSAFE. PLEASE USE WITH CAUTION. + NoSync bool + + // When true, skips the truncate call when growing the database. + // Setting this to true is only safe on non-ext3/ext4 systems. + // Skipping truncation avoids preallocation of hard drive space and + // bypasses a truncate() and fsync() syscall on remapping. + // + // https://github.com/boltdb/bolt/issues/284 + NoGrowSync bool + + // If you want to read the entire database fast, you can set MmapFlag to + // syscall.MAP_POPULATE on Linux 2.6.23+ for sequential read-ahead. + MmapFlags int + + // MaxBatchSize is the maximum size of a batch. Default value is + // copied from DefaultMaxBatchSize in Open. + // + // If <=0, disables batching. + // + // Do not change concurrently with calls to Batch. + MaxBatchSize int + + // MaxBatchDelay is the maximum delay before a batch starts. + // Default value is copied from DefaultMaxBatchDelay in Open. + // + // If <=0, effectively disables batching. + // + // Do not change concurrently with calls to Batch. + MaxBatchDelay time.Duration + + // AllocSize is the amount of space allocated when the database + // needs to create new pages. This is done to amortize the cost + // of truncate() and fsync() when growing the data file. + AllocSize int + + path string + file *os.File + lockfile *os.File // windows only + dataref []byte // mmap'ed readonly, write throws SEGV + data *[maxMapSize]byte + datasz int + filesz int // current on disk file size + meta0 *meta + meta1 *meta + pageSize int + opened bool + rwtx *Tx + txs []*Tx + freelist *freelist + stats Stats + + pagePool sync.Pool + + batchMu sync.Mutex + batch *batch + + rwlock sync.Mutex // Allows only one writer at a time. + metalock sync.Mutex // Protects meta page access. + mmaplock sync.RWMutex // Protects mmap access during remapping. + statlock sync.RWMutex // Protects stats access. + + ops struct { + writeAt func(b []byte, off int64) (n int, err error) + } + + // Read only mode. + // When true, Update() and Begin(true) return ErrDatabaseReadOnly immediately. + readOnly bool +} + +// Path returns the path to currently open database file. +func (db *DB) Path() string { + return db.path +} + +// GoString returns the Go string representation of the database. +func (db *DB) GoString() string { + return fmt.Sprintf("bolt.DB{path:%q}", db.path) +} + +// String returns the string representation of the database. +func (db *DB) String() string { + return fmt.Sprintf("DB<%q>", db.path) +} + +// Open creates and opens a database at the given path. +// If the file does not exist then it will be created automatically. +// Passing in nil options will cause Bolt to open the database with the default options. +func Open(path string, mode os.FileMode, options *Options) (*DB, error) { + var db = &DB{opened: true} + + // Set default options if no options are provided. + if options == nil { + options = DefaultOptions + } + db.NoGrowSync = options.NoGrowSync + db.MmapFlags = options.MmapFlags + + // Set default values for later DB operations. + db.MaxBatchSize = DefaultMaxBatchSize + db.MaxBatchDelay = DefaultMaxBatchDelay + db.AllocSize = DefaultAllocSize + + flag := os.O_RDWR + if options.ReadOnly { + flag = os.O_RDONLY + db.readOnly = true + } + + // Open data file and separate sync handler for metadata writes. + db.path = path + var err error + if db.file, err = os.OpenFile(db.path, flag|os.O_CREATE, mode); err != nil { + _ = db.close() + return nil, err + } + + // Lock file so that other processes using Bolt in read-write mode cannot + // use the database at the same time. This would cause corruption since + // the two processes would write meta pages and free pages separately. + // The database file is locked exclusively (only one process can grab the lock) + // if !options.ReadOnly. + // The database file is locked using the shared lock (more than one process may + // hold a lock at the same time) otherwise (options.ReadOnly is set). + if err := flock(db, mode, !db.readOnly, options.Timeout); err != nil { + _ = db.close() + return nil, err + } + + // Default values for test hooks + db.ops.writeAt = db.file.WriteAt + + // Initialize the database if it doesn't exist. + if info, err := db.file.Stat(); err != nil { + return nil, err + } else if info.Size() == 0 { + // Initialize new files with meta pages. + if err := db.init(); err != nil { + return nil, err + } + } else { + // Read the first meta page to determine the page size. + var buf [0x1000]byte + if _, err := db.file.ReadAt(buf[:], 0); err == nil { + m := db.pageInBuffer(buf[:], 0).meta() + if err := m.validate(); err != nil { + // If we can't read the page size, we can assume it's the same + // as the OS -- since that's how the page size was chosen in the + // first place. + // + // If the first page is invalid and this OS uses a different + // page size than what the database was created with then we + // are out of luck and cannot access the database. + db.pageSize = os.Getpagesize() + } else { + db.pageSize = int(m.pageSize) + } + } + } + + // Initialize page pool. + db.pagePool = sync.Pool{ + New: func() interface{} { + return make([]byte, db.pageSize) + }, + } + + // Memory map the data file. + if err := db.mmap(options.InitialMmapSize); err != nil { + _ = db.close() + return nil, err + } + + // Read in the freelist. + db.freelist = newFreelist() + db.freelist.read(db.page(db.meta().freelist)) + + // Mark the database as opened and return. + return db, nil +} + +// mmap opens the underlying memory-mapped file and initializes the meta references. +// minsz is the minimum size that the new mmap can be. +func (db *DB) mmap(minsz int) error { + db.mmaplock.Lock() + defer db.mmaplock.Unlock() + + info, err := db.file.Stat() + if err != nil { + return fmt.Errorf("mmap stat error: %s", err) + } else if int(info.Size()) < db.pageSize*2 { + return fmt.Errorf("file size too small") + } + + // Ensure the size is at least the minimum size. + var size = int(info.Size()) + if size < minsz { + size = minsz + } + size, err = db.mmapSize(size) + if err != nil { + return err + } + + // Dereference all mmap references before unmapping. + if db.rwtx != nil { + db.rwtx.root.dereference() + } + + // Unmap existing data before continuing. + if err := db.munmap(); err != nil { + return err + } + + // Memory-map the data file as a byte slice. + if err := mmap(db, size); err != nil { + return err + } + + // Save references to the meta pages. + db.meta0 = db.page(0).meta() + db.meta1 = db.page(1).meta() + + // Validate the meta pages. We only return an error if both meta pages fail + // validation, since meta0 failing validation means that it wasn't saved + // properly -- but we can recover using meta1. And vice-versa. + err0 := db.meta0.validate() + err1 := db.meta1.validate() + if err0 != nil && err1 != nil { + return err0 + } + + return nil +} + +// munmap unmaps the data file from memory. +func (db *DB) munmap() error { + if err := munmap(db); err != nil { + return fmt.Errorf("unmap error: " + err.Error()) + } + return nil +} + +// mmapSize determines the appropriate size for the mmap given the current size +// of the database. The minimum size is 32KB and doubles until it reaches 1GB. +// Returns an error if the new mmap size is greater than the max allowed. +func (db *DB) mmapSize(size int) (int, error) { + // Double the size from 32KB until 1GB. + for i := uint(15); i <= 30; i++ { + if size <= 1< maxMapSize { + return 0, fmt.Errorf("mmap too large") + } + + // If larger than 1GB then grow by 1GB at a time. + sz := int64(size) + if remainder := sz % int64(maxMmapStep); remainder > 0 { + sz += int64(maxMmapStep) - remainder + } + + // Ensure that the mmap size is a multiple of the page size. + // This should always be true since we're incrementing in MBs. + pageSize := int64(db.pageSize) + if (sz % pageSize) != 0 { + sz = ((sz / pageSize) + 1) * pageSize + } + + // If we've exceeded the max size then only grow up to the max size. + if sz > maxMapSize { + sz = maxMapSize + } + + return int(sz), nil +} + +// init creates a new database file and initializes its meta pages. +func (db *DB) init() error { + // Set the page size to the OS page size. + db.pageSize = os.Getpagesize() + + // Create two meta pages on a buffer. + buf := make([]byte, db.pageSize*4) + for i := 0; i < 2; i++ { + p := db.pageInBuffer(buf[:], pgid(i)) + p.id = pgid(i) + p.flags = metaPageFlag + + // Initialize the meta page. + m := p.meta() + m.magic = magic + m.version = version + m.pageSize = uint32(db.pageSize) + m.freelist = 2 + m.root = bucket{root: 3} + m.pgid = 4 + m.txid = txid(i) + m.checksum = m.sum64() + } + + // Write an empty freelist at page 3. + p := db.pageInBuffer(buf[:], pgid(2)) + p.id = pgid(2) + p.flags = freelistPageFlag + p.count = 0 + + // Write an empty leaf page at page 4. + p = db.pageInBuffer(buf[:], pgid(3)) + p.id = pgid(3) + p.flags = leafPageFlag + p.count = 0 + + // Write the buffer to our data file. + if _, err := db.ops.writeAt(buf, 0); err != nil { + return err + } + if err := fdatasync(db); err != nil { + return err + } + + return nil +} + +// Close releases all database resources. +// All transactions must be closed before closing the database. +func (db *DB) Close() error { + db.rwlock.Lock() + defer db.rwlock.Unlock() + + db.metalock.Lock() + defer db.metalock.Unlock() + + db.mmaplock.RLock() + defer db.mmaplock.RUnlock() + + return db.close() +} + +func (db *DB) close() error { + if !db.opened { + return nil + } + + db.opened = false + + db.freelist = nil + + // Clear ops. + db.ops.writeAt = nil + + // Close the mmap. + if err := db.munmap(); err != nil { + return err + } + + // Close file handles. + if db.file != nil { + // No need to unlock read-only file. + if !db.readOnly { + // Unlock the file. + if err := funlock(db); err != nil { + log.Printf("bolt.Close(): funlock error: %s", err) + } + } + + // Close the file descriptor. + if err := db.file.Close(); err != nil { + return fmt.Errorf("db file close: %s", err) + } + db.file = nil + } + + db.path = "" + return nil +} + +// Begin starts a new transaction. +// Multiple read-only transactions can be used concurrently but only one +// write transaction can be used at a time. Starting multiple write transactions +// will cause the calls to block and be serialized until the current write +// transaction finishes. +// +// Transactions should not be dependent on one another. Opening a read +// transaction and a write transaction in the same goroutine can cause the +// writer to deadlock because the database periodically needs to re-mmap itself +// as it grows and it cannot do that while a read transaction is open. +// +// If a long running read transaction (for example, a snapshot transaction) is +// needed, you might want to set DB.InitialMmapSize to a large enough value +// to avoid potential blocking of write transaction. +// +// IMPORTANT: You must close read-only transactions after you are finished or +// else the database will not reclaim old pages. +func (db *DB) Begin(writable bool) (*Tx, error) { + if writable { + return db.beginRWTx() + } + return db.beginTx() +} + +func (db *DB) beginTx() (*Tx, error) { + // Lock the meta pages while we initialize the transaction. We obtain + // the meta lock before the mmap lock because that's the order that the + // write transaction will obtain them. + db.metalock.Lock() + + // Obtain a read-only lock on the mmap. When the mmap is remapped it will + // obtain a write lock so all transactions must finish before it can be + // remapped. + db.mmaplock.RLock() + + // Exit if the database is not open yet. + if !db.opened { + db.mmaplock.RUnlock() + db.metalock.Unlock() + return nil, ErrDatabaseNotOpen + } + + // Create a transaction associated with the database. + t := &Tx{} + t.init(db) + + // Keep track of transaction until it closes. + db.txs = append(db.txs, t) + n := len(db.txs) + + // Unlock the meta pages. + db.metalock.Unlock() + + // Update the transaction stats. + db.statlock.Lock() + db.stats.TxN++ + db.stats.OpenTxN = n + db.statlock.Unlock() + + return t, nil +} + +func (db *DB) beginRWTx() (*Tx, error) { + // If the database was opened with Options.ReadOnly, return an error. + if db.readOnly { + return nil, ErrDatabaseReadOnly + } + + // Obtain writer lock. This is released by the transaction when it closes. + // This enforces only one writer transaction at a time. + db.rwlock.Lock() + + // Once we have the writer lock then we can lock the meta pages so that + // we can set up the transaction. + db.metalock.Lock() + defer db.metalock.Unlock() + + // Exit if the database is not open yet. + if !db.opened { + db.rwlock.Unlock() + return nil, ErrDatabaseNotOpen + } + + // Create a transaction associated with the database. + t := &Tx{writable: true} + t.init(db) + db.rwtx = t + + // Free any pages associated with closed read-only transactions. + var minid txid = 0xFFFFFFFFFFFFFFFF + for _, t := range db.txs { + if t.meta.txid < minid { + minid = t.meta.txid + } + } + if minid > 0 { + db.freelist.release(minid - 1) + } + + return t, nil +} + +// removeTx removes a transaction from the database. +func (db *DB) removeTx(tx *Tx) { + // Release the read lock on the mmap. + db.mmaplock.RUnlock() + + // Use the meta lock to restrict access to the DB object. + db.metalock.Lock() + + // Remove the transaction. + for i, t := range db.txs { + if t == tx { + last := len(db.txs) - 1 + db.txs[i] = db.txs[last] + db.txs[last] = nil + db.txs = db.txs[:last] + break + } + } + n := len(db.txs) + + // Unlock the meta pages. + db.metalock.Unlock() + + // Merge statistics. + db.statlock.Lock() + db.stats.OpenTxN = n + db.stats.TxStats.add(&tx.stats) + db.statlock.Unlock() +} + +// Update executes a function within the context of a read-write managed transaction. +// If no error is returned from the function then the transaction is committed. +// If an error is returned then the entire transaction is rolled back. +// Any error that is returned from the function or returned from the commit is +// returned from the Update() method. +// +// Attempting to manually commit or rollback within the function will cause a panic. +func (db *DB) Update(fn func(*Tx) error) error { + t, err := db.Begin(true) + if err != nil { + return err + } + + // Make sure the transaction rolls back in the event of a panic. + defer func() { + if t.db != nil { + t.rollback() + } + }() + + // Mark as a managed tx so that the inner function cannot manually commit. + t.managed = true + + // If an error is returned from the function then rollback and return error. + err = fn(t) + t.managed = false + if err != nil { + _ = t.Rollback() + return err + } + + return t.Commit() +} + +// View executes a function within the context of a managed read-only transaction. +// Any error that is returned from the function is returned from the View() method. +// +// Attempting to manually rollback within the function will cause a panic. +func (db *DB) View(fn func(*Tx) error) error { + t, err := db.Begin(false) + if err != nil { + return err + } + + // Make sure the transaction rolls back in the event of a panic. + defer func() { + if t.db != nil { + t.rollback() + } + }() + + // Mark as a managed tx so that the inner function cannot manually rollback. + t.managed = true + + // If an error is returned from the function then pass it through. + err = fn(t) + t.managed = false + if err != nil { + _ = t.Rollback() + return err + } + + if err := t.Rollback(); err != nil { + return err + } + + return nil +} + +// Batch calls fn as part of a batch. It behaves similar to Update, +// except: +// +// 1. concurrent Batch calls can be combined into a single Bolt +// transaction. +// +// 2. the function passed to Batch may be called multiple times, +// regardless of whether it returns error or not. +// +// This means that Batch function side effects must be idempotent and +// take permanent effect only after a successful return is seen in +// caller. +// +// The maximum batch size and delay can be adjusted with DB.MaxBatchSize +// and DB.MaxBatchDelay, respectively. +// +// Batch is only useful when there are multiple goroutines calling it. +func (db *DB) Batch(fn func(*Tx) error) error { + errCh := make(chan error, 1) + + db.batchMu.Lock() + if (db.batch == nil) || (db.batch != nil && len(db.batch.calls) >= db.MaxBatchSize) { + // There is no existing batch, or the existing batch is full; start a new one. + db.batch = &batch{ + db: db, + } + db.batch.timer = time.AfterFunc(db.MaxBatchDelay, db.batch.trigger) + } + db.batch.calls = append(db.batch.calls, call{fn: fn, err: errCh}) + if len(db.batch.calls) >= db.MaxBatchSize { + // wake up batch, it's ready to run + go db.batch.trigger() + } + db.batchMu.Unlock() + + err := <-errCh + if err == trySolo { + err = db.Update(fn) + } + return err +} + +type call struct { + fn func(*Tx) error + err chan<- error +} + +type batch struct { + db *DB + timer *time.Timer + start sync.Once + calls []call +} + +// trigger runs the batch if it hasn't already been run. +func (b *batch) trigger() { + b.start.Do(b.run) +} + +// run performs the transactions in the batch and communicates results +// back to DB.Batch. +func (b *batch) run() { + b.db.batchMu.Lock() + b.timer.Stop() + // Make sure no new work is added to this batch, but don't break + // other batches. + if b.db.batch == b { + b.db.batch = nil + } + b.db.batchMu.Unlock() + +retry: + for len(b.calls) > 0 { + var failIdx = -1 + err := b.db.Update(func(tx *Tx) error { + for i, c := range b.calls { + if err := safelyCall(c.fn, tx); err != nil { + failIdx = i + return err + } + } + return nil + }) + + if failIdx >= 0 { + // take the failing transaction out of the batch. it's + // safe to shorten b.calls here because db.batch no longer + // points to us, and we hold the mutex anyway. + c := b.calls[failIdx] + b.calls[failIdx], b.calls = b.calls[len(b.calls)-1], b.calls[:len(b.calls)-1] + // tell the submitter re-run it solo, continue with the rest of the batch + c.err <- trySolo + continue retry + } + + // pass success, or bolt internal errors, to all callers + for _, c := range b.calls { + if c.err != nil { + c.err <- err + } + } + break retry + } +} + +// trySolo is a special sentinel error value used for signaling that a +// transaction function should be re-run. It should never be seen by +// callers. +var trySolo = errors.New("batch function returned an error and should be re-run solo") + +type panicked struct { + reason interface{} +} + +func (p panicked) Error() string { + if err, ok := p.reason.(error); ok { + return err.Error() + } + return fmt.Sprintf("panic: %v", p.reason) +} + +func safelyCall(fn func(*Tx) error, tx *Tx) (err error) { + defer func() { + if p := recover(); p != nil { + err = panicked{p} + } + }() + return fn(tx) +} + +// Sync executes fdatasync() against the database file handle. +// +// This is not necessary under normal operation, however, if you use NoSync +// then it allows you to force the database file to sync against the disk. +func (db *DB) Sync() error { return fdatasync(db) } + +// Stats retrieves ongoing performance stats for the database. +// This is only updated when a transaction closes. +func (db *DB) Stats() Stats { + db.statlock.RLock() + defer db.statlock.RUnlock() + return db.stats +} + +// This is for internal access to the raw data bytes from the C cursor, use +// carefully, or not at all. +func (db *DB) Info() *Info { + return &Info{uintptr(unsafe.Pointer(&db.data[0])), db.pageSize} +} + +// page retrieves a page reference from the mmap based on the current page size. +func (db *DB) page(id pgid) *page { + pos := id * pgid(db.pageSize) + return (*page)(unsafe.Pointer(&db.data[pos])) +} + +// pageInBuffer retrieves a page reference from a given byte array based on the current page size. +func (db *DB) pageInBuffer(b []byte, id pgid) *page { + return (*page)(unsafe.Pointer(&b[id*pgid(db.pageSize)])) +} + +// meta retrieves the current meta page reference. +func (db *DB) meta() *meta { + // We have to return the meta with the highest txid which doesn't fail + // validation. Otherwise, we can cause errors when in fact the database is + // in a consistent state. metaA is the one with the higher txid. + metaA := db.meta0 + metaB := db.meta1 + if db.meta1.txid > db.meta0.txid { + metaA = db.meta1 + metaB = db.meta0 + } + + // Use higher meta page if valid. Otherwise fallback to previous, if valid. + if err := metaA.validate(); err == nil { + return metaA + } else if err := metaB.validate(); err == nil { + return metaB + } + + // This should never be reached, because both meta1 and meta0 were validated + // on mmap() and we do fsync() on every write. + panic("bolt.DB.meta(): invalid meta pages") +} + +// allocate returns a contiguous block of memory starting at a given page. +func (db *DB) allocate(count int) (*page, error) { + // Allocate a temporary buffer for the page. + var buf []byte + if count == 1 { + buf = db.pagePool.Get().([]byte) + } else { + buf = make([]byte, count*db.pageSize) + } + p := (*page)(unsafe.Pointer(&buf[0])) + p.overflow = uint32(count - 1) + + // Use pages from the freelist if they are available. + if p.id = db.freelist.allocate(count); p.id != 0 { + return p, nil + } + + // Resize mmap() if we're at the end. + p.id = db.rwtx.meta.pgid + var minsz = int((p.id+pgid(count))+1) * db.pageSize + if minsz >= db.datasz { + if err := db.mmap(minsz); err != nil { + return nil, fmt.Errorf("mmap allocate error: %s", err) + } + } + + // Move the page id high water mark. + db.rwtx.meta.pgid += pgid(count) + + return p, nil +} + +// grow grows the size of the database to the given sz. +func (db *DB) grow(sz int) error { + // Ignore if the new size is less than available file size. + if sz <= db.filesz { + return nil + } + + // If the data is smaller than the alloc size then only allocate what's needed. + // Once it goes over the allocation size then allocate in chunks. + if db.datasz < db.AllocSize { + sz = db.datasz + } else { + sz += db.AllocSize + } + + // Truncate and fsync to ensure file size metadata is flushed. + // https://github.com/boltdb/bolt/issues/284 + if !db.NoGrowSync && !db.readOnly { + if runtime.GOOS != "windows" { + if err := db.file.Truncate(int64(sz)); err != nil { + return fmt.Errorf("file resize error: %s", err) + } + } + if err := db.file.Sync(); err != nil { + return fmt.Errorf("file sync error: %s", err) + } + } + + db.filesz = sz + return nil +} + +func (db *DB) IsReadOnly() bool { + return db.readOnly +} + +// Options represents the options that can be set when opening a database. +type Options struct { + // Timeout is the amount of time to wait to obtain a file lock. + // When set to zero it will wait indefinitely. This option is only + // available on Darwin and Linux. + Timeout time.Duration + + // Sets the DB.NoGrowSync flag before memory mapping the file. + NoGrowSync bool + + // Open database in read-only mode. Uses flock(..., LOCK_SH |LOCK_NB) to + // grab a shared lock (UNIX). + ReadOnly bool + + // Sets the DB.MmapFlags flag before memory mapping the file. + MmapFlags int + + // InitialMmapSize is the initial mmap size of the database + // in bytes. Read transactions won't block write transaction + // if the InitialMmapSize is large enough to hold database mmap + // size. (See DB.Begin for more information) + // + // If <=0, the initial map size is 0. + // If initialMmapSize is smaller than the previous database size, + // it takes no effect. + InitialMmapSize int +} + +// DefaultOptions represent the options used if nil options are passed into Open(). +// No timeout is used which will cause Bolt to wait indefinitely for a lock. +var DefaultOptions = &Options{ + Timeout: 0, + NoGrowSync: false, +} + +// Stats represents statistics about the database. +type Stats struct { + // Freelist stats + FreePageN int // total number of free pages on the freelist + PendingPageN int // total number of pending pages on the freelist + FreeAlloc int // total bytes allocated in free pages + FreelistInuse int // total bytes used by the freelist + + // Transaction stats + TxN int // total number of started read transactions + OpenTxN int // number of currently open read transactions + + TxStats TxStats // global, ongoing stats. +} + +// Sub calculates and returns the difference between two sets of database stats. +// This is useful when obtaining stats at two different points and time and +// you need the performance counters that occurred within that time span. +func (s *Stats) Sub(other *Stats) Stats { + if other == nil { + return *s + } + var diff Stats + diff.FreePageN = s.FreePageN + diff.PendingPageN = s.PendingPageN + diff.FreeAlloc = s.FreeAlloc + diff.FreelistInuse = s.FreelistInuse + diff.TxN = s.TxN - other.TxN + diff.TxStats = s.TxStats.Sub(&other.TxStats) + return diff +} + +func (s *Stats) add(other *Stats) { + s.TxStats.add(&other.TxStats) +} + +type Info struct { + Data uintptr + PageSize int +} + +type meta struct { + magic uint32 + version uint32 + pageSize uint32 + flags uint32 + root bucket + freelist pgid + pgid pgid + txid txid + checksum uint64 +} + +// validate checks the marker bytes and version of the meta page to ensure it matches this binary. +func (m *meta) validate() error { + if m.magic != magic { + return ErrInvalid + } else if m.version != version { + return ErrVersionMismatch + } else if m.checksum != 0 && m.checksum != m.sum64() { + return ErrChecksum + } + return nil +} + +// copy copies one meta object to another. +func (m *meta) copy(dest *meta) { + *dest = *m +} + +// write writes the meta onto a page. +func (m *meta) write(p *page) { + if m.root.root >= m.pgid { + panic(fmt.Sprintf("root bucket pgid (%d) above high water mark (%d)", m.root.root, m.pgid)) + } else if m.freelist >= m.pgid { + panic(fmt.Sprintf("freelist pgid (%d) above high water mark (%d)", m.freelist, m.pgid)) + } + + // Page id is either going to be 0 or 1 which we can determine by the transaction ID. + p.id = pgid(m.txid % 2) + p.flags |= metaPageFlag + + // Calculate the checksum. + m.checksum = m.sum64() + + m.copy(p.meta()) +} + +// generates the checksum for the meta. +func (m *meta) sum64() uint64 { + var h = fnv.New64a() + _, _ = h.Write((*[unsafe.Offsetof(meta{}.checksum)]byte)(unsafe.Pointer(m))[:]) + return h.Sum64() +} + +// _assert will panic with a given formatted message if the given condition is false. +func _assert(condition bool, msg string, v ...interface{}) { + if !condition { + panic(fmt.Sprintf("assertion failed: "+msg, v...)) + } +} + +func warn(v ...interface{}) { fmt.Fprintln(os.Stderr, v...) } +func warnf(msg string, v ...interface{}) { fmt.Fprintf(os.Stderr, msg+"\n", v...) } + +func printstack() { + stack := strings.Join(strings.Split(string(debug.Stack()), "\n")[2:], "\n") + fmt.Fprintln(os.Stderr, stack) +} diff --git a/vendor/github.com/boltdb/bolt/doc.go b/vendor/github.com/boltdb/bolt/doc.go new file mode 100644 index 000000000..cc937845d --- /dev/null +++ b/vendor/github.com/boltdb/bolt/doc.go @@ -0,0 +1,44 @@ +/* +Package bolt implements a low-level key/value store in pure Go. It supports +fully serializable transactions, ACID semantics, and lock-free MVCC with +multiple readers and a single writer. Bolt can be used for projects that +want a simple data store without the need to add large dependencies such as +Postgres or MySQL. + +Bolt is a single-level, zero-copy, B+tree data store. This means that Bolt is +optimized for fast read access and does not require recovery in the event of a +system crash. Transactions which have not finished committing will simply be +rolled back in the event of a crash. + +The design of Bolt is based on Howard Chu's LMDB database project. + +Bolt currently works on Windows, Mac OS X, and Linux. + + +Basics + +There are only a few types in Bolt: DB, Bucket, Tx, and Cursor. The DB is +a collection of buckets and is represented by a single file on disk. A bucket is +a collection of unique keys that are associated with values. + +Transactions provide either read-only or read-write access to the database. +Read-only transactions can retrieve key/value pairs and can use Cursors to +iterate over the dataset sequentially. Read-write transactions can create and +delete buckets and can insert and remove keys. Only one read-write transaction +is allowed at a time. + + +Caveats + +The database uses a read-only, memory-mapped data file to ensure that +applications cannot corrupt the database, however, this means that keys and +values returned from Bolt cannot be changed. Writing to a read-only byte slice +will cause Go to panic. + +Keys and values retrieved from the database are only valid for the life of +the transaction. When used outside the transaction, these byte slices can +point to different data or can point to invalid memory which will cause a panic. + + +*/ +package bolt diff --git a/vendor/github.com/boltdb/bolt/errors.go b/vendor/github.com/boltdb/bolt/errors.go new file mode 100644 index 000000000..a3620a3eb --- /dev/null +++ b/vendor/github.com/boltdb/bolt/errors.go @@ -0,0 +1,71 @@ +package bolt + +import "errors" + +// These errors can be returned when opening or calling methods on a DB. +var ( + // ErrDatabaseNotOpen is returned when a DB instance is accessed before it + // is opened or after it is closed. + ErrDatabaseNotOpen = errors.New("database not open") + + // ErrDatabaseOpen is returned when opening a database that is + // already open. + ErrDatabaseOpen = errors.New("database already open") + + // ErrInvalid is returned when both meta pages on a database are invalid. + // This typically occurs when a file is not a bolt database. + ErrInvalid = errors.New("invalid database") + + // ErrVersionMismatch is returned when the data file was created with a + // different version of Bolt. + ErrVersionMismatch = errors.New("version mismatch") + + // ErrChecksum is returned when either meta page checksum does not match. + ErrChecksum = errors.New("checksum error") + + // ErrTimeout is returned when a database cannot obtain an exclusive lock + // on the data file after the timeout passed to Open(). + ErrTimeout = errors.New("timeout") +) + +// These errors can occur when beginning or committing a Tx. +var ( + // ErrTxNotWritable is returned when performing a write operation on a + // read-only transaction. + ErrTxNotWritable = errors.New("tx not writable") + + // ErrTxClosed is returned when committing or rolling back a transaction + // that has already been committed or rolled back. + ErrTxClosed = errors.New("tx closed") + + // ErrDatabaseReadOnly is returned when a mutating transaction is started on a + // read-only database. + ErrDatabaseReadOnly = errors.New("database is in read-only mode") +) + +// These errors can occur when putting or deleting a value or a bucket. +var ( + // ErrBucketNotFound is returned when trying to access a bucket that has + // not been created yet. + ErrBucketNotFound = errors.New("bucket not found") + + // ErrBucketExists is returned when creating a bucket that already exists. + ErrBucketExists = errors.New("bucket already exists") + + // ErrBucketNameRequired is returned when creating a bucket with a blank name. + ErrBucketNameRequired = errors.New("bucket name required") + + // ErrKeyRequired is returned when inserting a zero-length key. + ErrKeyRequired = errors.New("key required") + + // ErrKeyTooLarge is returned when inserting a key that is larger than MaxKeySize. + ErrKeyTooLarge = errors.New("key too large") + + // ErrValueTooLarge is returned when inserting a value that is larger than MaxValueSize. + ErrValueTooLarge = errors.New("value too large") + + // ErrIncompatibleValue is returned when trying create or delete a bucket + // on an existing non-bucket key or when trying to create or delete a + // non-bucket key on an existing bucket key. + ErrIncompatibleValue = errors.New("incompatible value") +) diff --git a/vendor/github.com/boltdb/bolt/freelist.go b/vendor/github.com/boltdb/bolt/freelist.go new file mode 100644 index 000000000..aba48f58c --- /dev/null +++ b/vendor/github.com/boltdb/bolt/freelist.go @@ -0,0 +1,252 @@ +package bolt + +import ( + "fmt" + "sort" + "unsafe" +) + +// freelist represents a list of all pages that are available for allocation. +// It also tracks pages that have been freed but are still in use by open transactions. +type freelist struct { + ids []pgid // all free and available free page ids. + pending map[txid][]pgid // mapping of soon-to-be free page ids by tx. + cache map[pgid]bool // fast lookup of all free and pending page ids. +} + +// newFreelist returns an empty, initialized freelist. +func newFreelist() *freelist { + return &freelist{ + pending: make(map[txid][]pgid), + cache: make(map[pgid]bool), + } +} + +// size returns the size of the page after serialization. +func (f *freelist) size() int { + n := f.count() + if n >= 0xFFFF { + // The first element will be used to store the count. See freelist.write. + n++ + } + return pageHeaderSize + (int(unsafe.Sizeof(pgid(0))) * n) +} + +// count returns count of pages on the freelist +func (f *freelist) count() int { + return f.free_count() + f.pending_count() +} + +// free_count returns count of free pages +func (f *freelist) free_count() int { + return len(f.ids) +} + +// pending_count returns count of pending pages +func (f *freelist) pending_count() int { + var count int + for _, list := range f.pending { + count += len(list) + } + return count +} + +// copyall copies into dst a list of all free ids and all pending ids in one sorted list. +// f.count returns the minimum length required for dst. +func (f *freelist) copyall(dst []pgid) { + m := make(pgids, 0, f.pending_count()) + for _, list := range f.pending { + m = append(m, list...) + } + sort.Sort(m) + mergepgids(dst, f.ids, m) +} + +// allocate returns the starting page id of a contiguous list of pages of a given size. +// If a contiguous block cannot be found then 0 is returned. +func (f *freelist) allocate(n int) pgid { + if len(f.ids) == 0 { + return 0 + } + + var initial, previd pgid + for i, id := range f.ids { + if id <= 1 { + panic(fmt.Sprintf("invalid page allocation: %d", id)) + } + + // Reset initial page if this is not contiguous. + if previd == 0 || id-previd != 1 { + initial = id + } + + // If we found a contiguous block then remove it and return it. + if (id-initial)+1 == pgid(n) { + // If we're allocating off the beginning then take the fast path + // and just adjust the existing slice. This will use extra memory + // temporarily but the append() in free() will realloc the slice + // as is necessary. + if (i + 1) == n { + f.ids = f.ids[i+1:] + } else { + copy(f.ids[i-n+1:], f.ids[i+1:]) + f.ids = f.ids[:len(f.ids)-n] + } + + // Remove from the free cache. + for i := pgid(0); i < pgid(n); i++ { + delete(f.cache, initial+i) + } + + return initial + } + + previd = id + } + return 0 +} + +// free releases a page and its overflow for a given transaction id. +// If the page is already free then a panic will occur. +func (f *freelist) free(txid txid, p *page) { + if p.id <= 1 { + panic(fmt.Sprintf("cannot free page 0 or 1: %d", p.id)) + } + + // Free page and all its overflow pages. + var ids = f.pending[txid] + for id := p.id; id <= p.id+pgid(p.overflow); id++ { + // Verify that page is not already free. + if f.cache[id] { + panic(fmt.Sprintf("page %d already freed", id)) + } + + // Add to the freelist and cache. + ids = append(ids, id) + f.cache[id] = true + } + f.pending[txid] = ids +} + +// release moves all page ids for a transaction id (or older) to the freelist. +func (f *freelist) release(txid txid) { + m := make(pgids, 0) + for tid, ids := range f.pending { + if tid <= txid { + // Move transaction's pending pages to the available freelist. + // Don't remove from the cache since the page is still free. + m = append(m, ids...) + delete(f.pending, tid) + } + } + sort.Sort(m) + f.ids = pgids(f.ids).merge(m) +} + +// rollback removes the pages from a given pending tx. +func (f *freelist) rollback(txid txid) { + // Remove page ids from cache. + for _, id := range f.pending[txid] { + delete(f.cache, id) + } + + // Remove pages from pending list. + delete(f.pending, txid) +} + +// freed returns whether a given page is in the free list. +func (f *freelist) freed(pgid pgid) bool { + return f.cache[pgid] +} + +// read initializes the freelist from a freelist page. +func (f *freelist) read(p *page) { + // If the page.count is at the max uint16 value (64k) then it's considered + // an overflow and the size of the freelist is stored as the first element. + idx, count := 0, int(p.count) + if count == 0xFFFF { + idx = 1 + count = int(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0]) + } + + // Copy the list of page ids from the freelist. + if count == 0 { + f.ids = nil + } else { + ids := ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[idx:count] + f.ids = make([]pgid, len(ids)) + copy(f.ids, ids) + + // Make sure they're sorted. + sort.Sort(pgids(f.ids)) + } + + // Rebuild the page cache. + f.reindex() +} + +// write writes the page ids onto a freelist page. All free and pending ids are +// saved to disk since in the event of a program crash, all pending ids will +// become free. +func (f *freelist) write(p *page) error { + // Combine the old free pgids and pgids waiting on an open transaction. + + // Update the header flag. + p.flags |= freelistPageFlag + + // The page.count can only hold up to 64k elements so if we overflow that + // number then we handle it by putting the size in the first element. + lenids := f.count() + if lenids == 0 { + p.count = uint16(lenids) + } else if lenids < 0xFFFF { + p.count = uint16(lenids) + f.copyall(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[:]) + } else { + p.count = 0xFFFF + ((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[0] = pgid(lenids) + f.copyall(((*[maxAllocSize]pgid)(unsafe.Pointer(&p.ptr)))[1:]) + } + + return nil +} + +// reload reads the freelist from a page and filters out pending items. +func (f *freelist) reload(p *page) { + f.read(p) + + // Build a cache of only pending pages. + pcache := make(map[pgid]bool) + for _, pendingIDs := range f.pending { + for _, pendingID := range pendingIDs { + pcache[pendingID] = true + } + } + + // Check each page in the freelist and build a new available freelist + // with any pages not in the pending lists. + var a []pgid + for _, id := range f.ids { + if !pcache[id] { + a = append(a, id) + } + } + f.ids = a + + // Once the available list is rebuilt then rebuild the free cache so that + // it includes the available and pending free pages. + f.reindex() +} + +// reindex rebuilds the free cache based on available and pending free lists. +func (f *freelist) reindex() { + f.cache = make(map[pgid]bool, len(f.ids)) + for _, id := range f.ids { + f.cache[id] = true + } + for _, pendingIDs := range f.pending { + for _, pendingID := range pendingIDs { + f.cache[pendingID] = true + } + } +} diff --git a/vendor/github.com/boltdb/bolt/node.go b/vendor/github.com/boltdb/bolt/node.go new file mode 100644 index 000000000..159318b22 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/node.go @@ -0,0 +1,604 @@ +package bolt + +import ( + "bytes" + "fmt" + "sort" + "unsafe" +) + +// node represents an in-memory, deserialized page. +type node struct { + bucket *Bucket + isLeaf bool + unbalanced bool + spilled bool + key []byte + pgid pgid + parent *node + children nodes + inodes inodes +} + +// root returns the top-level node this node is attached to. +func (n *node) root() *node { + if n.parent == nil { + return n + } + return n.parent.root() +} + +// minKeys returns the minimum number of inodes this node should have. +func (n *node) minKeys() int { + if n.isLeaf { + return 1 + } + return 2 +} + +// size returns the size of the node after serialization. +func (n *node) size() int { + sz, elsz := pageHeaderSize, n.pageElementSize() + for i := 0; i < len(n.inodes); i++ { + item := &n.inodes[i] + sz += elsz + len(item.key) + len(item.value) + } + return sz +} + +// sizeLessThan returns true if the node is less than a given size. +// This is an optimization to avoid calculating a large node when we only need +// to know if it fits inside a certain page size. +func (n *node) sizeLessThan(v int) bool { + sz, elsz := pageHeaderSize, n.pageElementSize() + for i := 0; i < len(n.inodes); i++ { + item := &n.inodes[i] + sz += elsz + len(item.key) + len(item.value) + if sz >= v { + return false + } + } + return true +} + +// pageElementSize returns the size of each page element based on the type of node. +func (n *node) pageElementSize() int { + if n.isLeaf { + return leafPageElementSize + } + return branchPageElementSize +} + +// childAt returns the child node at a given index. +func (n *node) childAt(index int) *node { + if n.isLeaf { + panic(fmt.Sprintf("invalid childAt(%d) on a leaf node", index)) + } + return n.bucket.node(n.inodes[index].pgid, n) +} + +// childIndex returns the index of a given child node. +func (n *node) childIndex(child *node) int { + index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, child.key) != -1 }) + return index +} + +// numChildren returns the number of children. +func (n *node) numChildren() int { + return len(n.inodes) +} + +// nextSibling returns the next node with the same parent. +func (n *node) nextSibling() *node { + if n.parent == nil { + return nil + } + index := n.parent.childIndex(n) + if index >= n.parent.numChildren()-1 { + return nil + } + return n.parent.childAt(index + 1) +} + +// prevSibling returns the previous node with the same parent. +func (n *node) prevSibling() *node { + if n.parent == nil { + return nil + } + index := n.parent.childIndex(n) + if index == 0 { + return nil + } + return n.parent.childAt(index - 1) +} + +// put inserts a key/value. +func (n *node) put(oldKey, newKey, value []byte, pgid pgid, flags uint32) { + if pgid >= n.bucket.tx.meta.pgid { + panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", pgid, n.bucket.tx.meta.pgid)) + } else if len(oldKey) <= 0 { + panic("put: zero-length old key") + } else if len(newKey) <= 0 { + panic("put: zero-length new key") + } + + // Find insertion index. + index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, oldKey) != -1 }) + + // Add capacity and shift nodes if we don't have an exact match and need to insert. + exact := (len(n.inodes) > 0 && index < len(n.inodes) && bytes.Equal(n.inodes[index].key, oldKey)) + if !exact { + n.inodes = append(n.inodes, inode{}) + copy(n.inodes[index+1:], n.inodes[index:]) + } + + inode := &n.inodes[index] + inode.flags = flags + inode.key = newKey + inode.value = value + inode.pgid = pgid + _assert(len(inode.key) > 0, "put: zero-length inode key") +} + +// del removes a key from the node. +func (n *node) del(key []byte) { + // Find index of key. + index := sort.Search(len(n.inodes), func(i int) bool { return bytes.Compare(n.inodes[i].key, key) != -1 }) + + // Exit if the key isn't found. + if index >= len(n.inodes) || !bytes.Equal(n.inodes[index].key, key) { + return + } + + // Delete inode from the node. + n.inodes = append(n.inodes[:index], n.inodes[index+1:]...) + + // Mark the node as needing rebalancing. + n.unbalanced = true +} + +// read initializes the node from a page. +func (n *node) read(p *page) { + n.pgid = p.id + n.isLeaf = ((p.flags & leafPageFlag) != 0) + n.inodes = make(inodes, int(p.count)) + + for i := 0; i < int(p.count); i++ { + inode := &n.inodes[i] + if n.isLeaf { + elem := p.leafPageElement(uint16(i)) + inode.flags = elem.flags + inode.key = elem.key() + inode.value = elem.value() + } else { + elem := p.branchPageElement(uint16(i)) + inode.pgid = elem.pgid + inode.key = elem.key() + } + _assert(len(inode.key) > 0, "read: zero-length inode key") + } + + // Save first key so we can find the node in the parent when we spill. + if len(n.inodes) > 0 { + n.key = n.inodes[0].key + _assert(len(n.key) > 0, "read: zero-length node key") + } else { + n.key = nil + } +} + +// write writes the items onto one or more pages. +func (n *node) write(p *page) { + // Initialize page. + if n.isLeaf { + p.flags |= leafPageFlag + } else { + p.flags |= branchPageFlag + } + + if len(n.inodes) >= 0xFFFF { + panic(fmt.Sprintf("inode overflow: %d (pgid=%d)", len(n.inodes), p.id)) + } + p.count = uint16(len(n.inodes)) + + // Stop here if there are no items to write. + if p.count == 0 { + return + } + + // Loop over each item and write it to the page. + b := (*[maxAllocSize]byte)(unsafe.Pointer(&p.ptr))[n.pageElementSize()*len(n.inodes):] + for i, item := range n.inodes { + _assert(len(item.key) > 0, "write: zero-length inode key") + + // Write the page element. + if n.isLeaf { + elem := p.leafPageElement(uint16(i)) + elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem))) + elem.flags = item.flags + elem.ksize = uint32(len(item.key)) + elem.vsize = uint32(len(item.value)) + } else { + elem := p.branchPageElement(uint16(i)) + elem.pos = uint32(uintptr(unsafe.Pointer(&b[0])) - uintptr(unsafe.Pointer(elem))) + elem.ksize = uint32(len(item.key)) + elem.pgid = item.pgid + _assert(elem.pgid != p.id, "write: circular dependency occurred") + } + + // If the length of key+value is larger than the max allocation size + // then we need to reallocate the byte array pointer. + // + // See: https://github.com/boltdb/bolt/pull/335 + klen, vlen := len(item.key), len(item.value) + if len(b) < klen+vlen { + b = (*[maxAllocSize]byte)(unsafe.Pointer(&b[0]))[:] + } + + // Write data for the element to the end of the page. + copy(b[0:], item.key) + b = b[klen:] + copy(b[0:], item.value) + b = b[vlen:] + } + + // DEBUG ONLY: n.dump() +} + +// split breaks up a node into multiple smaller nodes, if appropriate. +// This should only be called from the spill() function. +func (n *node) split(pageSize int) []*node { + var nodes []*node + + node := n + for { + // Split node into two. + a, b := node.splitTwo(pageSize) + nodes = append(nodes, a) + + // If we can't split then exit the loop. + if b == nil { + break + } + + // Set node to b so it gets split on the next iteration. + node = b + } + + return nodes +} + +// splitTwo breaks up a node into two smaller nodes, if appropriate. +// This should only be called from the split() function. +func (n *node) splitTwo(pageSize int) (*node, *node) { + // Ignore the split if the page doesn't have at least enough nodes for + // two pages or if the nodes can fit in a single page. + if len(n.inodes) <= (minKeysPerPage*2) || n.sizeLessThan(pageSize) { + return n, nil + } + + // Determine the threshold before starting a new node. + var fillPercent = n.bucket.FillPercent + if fillPercent < minFillPercent { + fillPercent = minFillPercent + } else if fillPercent > maxFillPercent { + fillPercent = maxFillPercent + } + threshold := int(float64(pageSize) * fillPercent) + + // Determine split position and sizes of the two pages. + splitIndex, _ := n.splitIndex(threshold) + + // Split node into two separate nodes. + // If there's no parent then we'll need to create one. + if n.parent == nil { + n.parent = &node{bucket: n.bucket, children: []*node{n}} + } + + // Create a new node and add it to the parent. + next := &node{bucket: n.bucket, isLeaf: n.isLeaf, parent: n.parent} + n.parent.children = append(n.parent.children, next) + + // Split inodes across two nodes. + next.inodes = n.inodes[splitIndex:] + n.inodes = n.inodes[:splitIndex] + + // Update the statistics. + n.bucket.tx.stats.Split++ + + return n, next +} + +// splitIndex finds the position where a page will fill a given threshold. +// It returns the index as well as the size of the first page. +// This is only be called from split(). +func (n *node) splitIndex(threshold int) (index, sz int) { + sz = pageHeaderSize + + // Loop until we only have the minimum number of keys required for the second page. + for i := 0; i < len(n.inodes)-minKeysPerPage; i++ { + index = i + inode := n.inodes[i] + elsize := n.pageElementSize() + len(inode.key) + len(inode.value) + + // If we have at least the minimum number of keys and adding another + // node would put us over the threshold then exit and return. + if i >= minKeysPerPage && sz+elsize > threshold { + break + } + + // Add the element size to the total size. + sz += elsize + } + + return +} + +// spill writes the nodes to dirty pages and splits nodes as it goes. +// Returns an error if dirty pages cannot be allocated. +func (n *node) spill() error { + var tx = n.bucket.tx + if n.spilled { + return nil + } + + // Spill child nodes first. Child nodes can materialize sibling nodes in + // the case of split-merge so we cannot use a range loop. We have to check + // the children size on every loop iteration. + sort.Sort(n.children) + for i := 0; i < len(n.children); i++ { + if err := n.children[i].spill(); err != nil { + return err + } + } + + // We no longer need the child list because it's only used for spill tracking. + n.children = nil + + // Split nodes into appropriate sizes. The first node will always be n. + var nodes = n.split(tx.db.pageSize) + for _, node := range nodes { + // Add node's page to the freelist if it's not new. + if node.pgid > 0 { + tx.db.freelist.free(tx.meta.txid, tx.page(node.pgid)) + node.pgid = 0 + } + + // Allocate contiguous space for the node. + p, err := tx.allocate((node.size() / tx.db.pageSize) + 1) + if err != nil { + return err + } + + // Write the node. + if p.id >= tx.meta.pgid { + panic(fmt.Sprintf("pgid (%d) above high water mark (%d)", p.id, tx.meta.pgid)) + } + node.pgid = p.id + node.write(p) + node.spilled = true + + // Insert into parent inodes. + if node.parent != nil { + var key = node.key + if key == nil { + key = node.inodes[0].key + } + + node.parent.put(key, node.inodes[0].key, nil, node.pgid, 0) + node.key = node.inodes[0].key + _assert(len(node.key) > 0, "spill: zero-length node key") + } + + // Update the statistics. + tx.stats.Spill++ + } + + // If the root node split and created a new root then we need to spill that + // as well. We'll clear out the children to make sure it doesn't try to respill. + if n.parent != nil && n.parent.pgid == 0 { + n.children = nil + return n.parent.spill() + } + + return nil +} + +// rebalance attempts to combine the node with sibling nodes if the node fill +// size is below a threshold or if there are not enough keys. +func (n *node) rebalance() { + if !n.unbalanced { + return + } + n.unbalanced = false + + // Update statistics. + n.bucket.tx.stats.Rebalance++ + + // Ignore if node is above threshold (25%) and has enough keys. + var threshold = n.bucket.tx.db.pageSize / 4 + if n.size() > threshold && len(n.inodes) > n.minKeys() { + return + } + + // Root node has special handling. + if n.parent == nil { + // If root node is a branch and only has one node then collapse it. + if !n.isLeaf && len(n.inodes) == 1 { + // Move root's child up. + child := n.bucket.node(n.inodes[0].pgid, n) + n.isLeaf = child.isLeaf + n.inodes = child.inodes[:] + n.children = child.children + + // Reparent all child nodes being moved. + for _, inode := range n.inodes { + if child, ok := n.bucket.nodes[inode.pgid]; ok { + child.parent = n + } + } + + // Remove old child. + child.parent = nil + delete(n.bucket.nodes, child.pgid) + child.free() + } + + return + } + + // If node has no keys then just remove it. + if n.numChildren() == 0 { + n.parent.del(n.key) + n.parent.removeChild(n) + delete(n.bucket.nodes, n.pgid) + n.free() + n.parent.rebalance() + return + } + + _assert(n.parent.numChildren() > 1, "parent must have at least 2 children") + + // Destination node is right sibling if idx == 0, otherwise left sibling. + var target *node + var useNextSibling = (n.parent.childIndex(n) == 0) + if useNextSibling { + target = n.nextSibling() + } else { + target = n.prevSibling() + } + + // If both this node and the target node are too small then merge them. + if useNextSibling { + // Reparent all child nodes being moved. + for _, inode := range target.inodes { + if child, ok := n.bucket.nodes[inode.pgid]; ok { + child.parent.removeChild(child) + child.parent = n + child.parent.children = append(child.parent.children, child) + } + } + + // Copy over inodes from target and remove target. + n.inodes = append(n.inodes, target.inodes...) + n.parent.del(target.key) + n.parent.removeChild(target) + delete(n.bucket.nodes, target.pgid) + target.free() + } else { + // Reparent all child nodes being moved. + for _, inode := range n.inodes { + if child, ok := n.bucket.nodes[inode.pgid]; ok { + child.parent.removeChild(child) + child.parent = target + child.parent.children = append(child.parent.children, child) + } + } + + // Copy over inodes to target and remove node. + target.inodes = append(target.inodes, n.inodes...) + n.parent.del(n.key) + n.parent.removeChild(n) + delete(n.bucket.nodes, n.pgid) + n.free() + } + + // Either this node or the target node was deleted from the parent so rebalance it. + n.parent.rebalance() +} + +// removes a node from the list of in-memory children. +// This does not affect the inodes. +func (n *node) removeChild(target *node) { + for i, child := range n.children { + if child == target { + n.children = append(n.children[:i], n.children[i+1:]...) + return + } + } +} + +// dereference causes the node to copy all its inode key/value references to heap memory. +// This is required when the mmap is reallocated so inodes are not pointing to stale data. +func (n *node) dereference() { + if n.key != nil { + key := make([]byte, len(n.key)) + copy(key, n.key) + n.key = key + _assert(n.pgid == 0 || len(n.key) > 0, "dereference: zero-length node key on existing node") + } + + for i := range n.inodes { + inode := &n.inodes[i] + + key := make([]byte, len(inode.key)) + copy(key, inode.key) + inode.key = key + _assert(len(inode.key) > 0, "dereference: zero-length inode key") + + value := make([]byte, len(inode.value)) + copy(value, inode.value) + inode.value = value + } + + // Recursively dereference children. + for _, child := range n.children { + child.dereference() + } + + // Update statistics. + n.bucket.tx.stats.NodeDeref++ +} + +// free adds the node's underlying page to the freelist. +func (n *node) free() { + if n.pgid != 0 { + n.bucket.tx.db.freelist.free(n.bucket.tx.meta.txid, n.bucket.tx.page(n.pgid)) + n.pgid = 0 + } +} + +// dump writes the contents of the node to STDERR for debugging purposes. +/* +func (n *node) dump() { + // Write node header. + var typ = "branch" + if n.isLeaf { + typ = "leaf" + } + warnf("[NODE %d {type=%s count=%d}]", n.pgid, typ, len(n.inodes)) + + // Write out abbreviated version of each item. + for _, item := range n.inodes { + if n.isLeaf { + if item.flags&bucketLeafFlag != 0 { + bucket := (*bucket)(unsafe.Pointer(&item.value[0])) + warnf("+L %08x -> (bucket root=%d)", trunc(item.key, 4), bucket.root) + } else { + warnf("+L %08x -> %08x", trunc(item.key, 4), trunc(item.value, 4)) + } + } else { + warnf("+B %08x -> pgid=%d", trunc(item.key, 4), item.pgid) + } + } + warn("") +} +*/ + +type nodes []*node + +func (s nodes) Len() int { return len(s) } +func (s nodes) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s nodes) Less(i, j int) bool { return bytes.Compare(s[i].inodes[0].key, s[j].inodes[0].key) == -1 } + +// inode represents an internal node inside of a node. +// It can be used to point to elements in a page or point +// to an element which hasn't been added to a page yet. +type inode struct { + flags uint32 + pgid pgid + key []byte + value []byte +} + +type inodes []inode diff --git a/vendor/github.com/boltdb/bolt/page.go b/vendor/github.com/boltdb/bolt/page.go new file mode 100644 index 000000000..cde403ae8 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/page.go @@ -0,0 +1,197 @@ +package bolt + +import ( + "fmt" + "os" + "sort" + "unsafe" +) + +const pageHeaderSize = int(unsafe.Offsetof(((*page)(nil)).ptr)) + +const minKeysPerPage = 2 + +const branchPageElementSize = int(unsafe.Sizeof(branchPageElement{})) +const leafPageElementSize = int(unsafe.Sizeof(leafPageElement{})) + +const ( + branchPageFlag = 0x01 + leafPageFlag = 0x02 + metaPageFlag = 0x04 + freelistPageFlag = 0x10 +) + +const ( + bucketLeafFlag = 0x01 +) + +type pgid uint64 + +type page struct { + id pgid + flags uint16 + count uint16 + overflow uint32 + ptr uintptr +} + +// typ returns a human readable page type string used for debugging. +func (p *page) typ() string { + if (p.flags & branchPageFlag) != 0 { + return "branch" + } else if (p.flags & leafPageFlag) != 0 { + return "leaf" + } else if (p.flags & metaPageFlag) != 0 { + return "meta" + } else if (p.flags & freelistPageFlag) != 0 { + return "freelist" + } + return fmt.Sprintf("unknown<%02x>", p.flags) +} + +// meta returns a pointer to the metadata section of the page. +func (p *page) meta() *meta { + return (*meta)(unsafe.Pointer(&p.ptr)) +} + +// leafPageElement retrieves the leaf node by index +func (p *page) leafPageElement(index uint16) *leafPageElement { + n := &((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[index] + return n +} + +// leafPageElements retrieves a list of leaf nodes. +func (p *page) leafPageElements() []leafPageElement { + if p.count == 0 { + return nil + } + return ((*[0x7FFFFFF]leafPageElement)(unsafe.Pointer(&p.ptr)))[:] +} + +// branchPageElement retrieves the branch node by index +func (p *page) branchPageElement(index uint16) *branchPageElement { + return &((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[index] +} + +// branchPageElements retrieves a list of branch nodes. +func (p *page) branchPageElements() []branchPageElement { + if p.count == 0 { + return nil + } + return ((*[0x7FFFFFF]branchPageElement)(unsafe.Pointer(&p.ptr)))[:] +} + +// dump writes n bytes of the page to STDERR as hex output. +func (p *page) hexdump(n int) { + buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:n] + fmt.Fprintf(os.Stderr, "%x\n", buf) +} + +type pages []*page + +func (s pages) Len() int { return len(s) } +func (s pages) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s pages) Less(i, j int) bool { return s[i].id < s[j].id } + +// branchPageElement represents a node on a branch page. +type branchPageElement struct { + pos uint32 + ksize uint32 + pgid pgid +} + +// key returns a byte slice of the node key. +func (n *branchPageElement) key() []byte { + buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) + return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos]))[:n.ksize] +} + +// leafPageElement represents a node on a leaf page. +type leafPageElement struct { + flags uint32 + pos uint32 + ksize uint32 + vsize uint32 +} + +// key returns a byte slice of the node key. +func (n *leafPageElement) key() []byte { + buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) + return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos]))[:n.ksize:n.ksize] +} + +// value returns a byte slice of the node value. +func (n *leafPageElement) value() []byte { + buf := (*[maxAllocSize]byte)(unsafe.Pointer(n)) + return (*[maxAllocSize]byte)(unsafe.Pointer(&buf[n.pos+n.ksize]))[:n.vsize:n.vsize] +} + +// PageInfo represents human readable information about a page. +type PageInfo struct { + ID int + Type string + Count int + OverflowCount int +} + +type pgids []pgid + +func (s pgids) Len() int { return len(s) } +func (s pgids) Swap(i, j int) { s[i], s[j] = s[j], s[i] } +func (s pgids) Less(i, j int) bool { return s[i] < s[j] } + +// merge returns the sorted union of a and b. +func (a pgids) merge(b pgids) pgids { + // Return the opposite slice if one is nil. + if len(a) == 0 { + return b + } + if len(b) == 0 { + return a + } + merged := make(pgids, len(a)+len(b)) + mergepgids(merged, a, b) + return merged +} + +// mergepgids copies the sorted union of a and b into dst. +// If dst is too small, it panics. +func mergepgids(dst, a, b pgids) { + if len(dst) < len(a)+len(b) { + panic(fmt.Errorf("mergepgids bad len %d < %d + %d", len(dst), len(a), len(b))) + } + // Copy in the opposite slice if one is nil. + if len(a) == 0 { + copy(dst, b) + return + } + if len(b) == 0 { + copy(dst, a) + return + } + + // Merged will hold all elements from both lists. + merged := dst[:0] + + // Assign lead to the slice with a lower starting value, follow to the higher value. + lead, follow := a, b + if b[0] < a[0] { + lead, follow = b, a + } + + // Continue while there are elements in the lead. + for len(lead) > 0 { + // Merge largest prefix of lead that is ahead of follow[0]. + n := sort.Search(len(lead), func(i int) bool { return lead[i] > follow[0] }) + merged = append(merged, lead[:n]...) + if n >= len(lead) { + break + } + + // Swap lead and follow. + lead, follow = follow, lead[n:] + } + + // Append what's left in follow. + _ = append(merged, follow...) +} diff --git a/vendor/github.com/boltdb/bolt/tx.go b/vendor/github.com/boltdb/bolt/tx.go new file mode 100644 index 000000000..6700308a2 --- /dev/null +++ b/vendor/github.com/boltdb/bolt/tx.go @@ -0,0 +1,684 @@ +package bolt + +import ( + "fmt" + "io" + "os" + "sort" + "strings" + "time" + "unsafe" +) + +// txid represents the internal transaction identifier. +type txid uint64 + +// Tx represents a read-only or read/write transaction on the database. +// Read-only transactions can be used for retrieving values for keys and creating cursors. +// Read/write transactions can create and remove buckets and create and remove keys. +// +// IMPORTANT: You must commit or rollback transactions when you are done with +// them. Pages can not be reclaimed by the writer until no more transactions +// are using them. A long running read transaction can cause the database to +// quickly grow. +type Tx struct { + writable bool + managed bool + db *DB + meta *meta + root Bucket + pages map[pgid]*page + stats TxStats + commitHandlers []func() + + // WriteFlag specifies the flag for write-related methods like WriteTo(). + // Tx opens the database file with the specified flag to copy the data. + // + // By default, the flag is unset, which works well for mostly in-memory + // workloads. For databases that are much larger than available RAM, + // set the flag to syscall.O_DIRECT to avoid trashing the page cache. + WriteFlag int +} + +// init initializes the transaction. +func (tx *Tx) init(db *DB) { + tx.db = db + tx.pages = nil + + // Copy the meta page since it can be changed by the writer. + tx.meta = &meta{} + db.meta().copy(tx.meta) + + // Copy over the root bucket. + tx.root = newBucket(tx) + tx.root.bucket = &bucket{} + *tx.root.bucket = tx.meta.root + + // Increment the transaction id and add a page cache for writable transactions. + if tx.writable { + tx.pages = make(map[pgid]*page) + tx.meta.txid += txid(1) + } +} + +// ID returns the transaction id. +func (tx *Tx) ID() int { + return int(tx.meta.txid) +} + +// DB returns a reference to the database that created the transaction. +func (tx *Tx) DB() *DB { + return tx.db +} + +// Size returns current database size in bytes as seen by this transaction. +func (tx *Tx) Size() int64 { + return int64(tx.meta.pgid) * int64(tx.db.pageSize) +} + +// Writable returns whether the transaction can perform write operations. +func (tx *Tx) Writable() bool { + return tx.writable +} + +// Cursor creates a cursor associated with the root bucket. +// All items in the cursor will return a nil value because all root bucket keys point to buckets. +// The cursor is only valid as long as the transaction is open. +// Do not use a cursor after the transaction is closed. +func (tx *Tx) Cursor() *Cursor { + return tx.root.Cursor() +} + +// Stats retrieves a copy of the current transaction statistics. +func (tx *Tx) Stats() TxStats { + return tx.stats +} + +// Bucket retrieves a bucket by name. +// Returns nil if the bucket does not exist. +// The bucket instance is only valid for the lifetime of the transaction. +func (tx *Tx) Bucket(name []byte) *Bucket { + return tx.root.Bucket(name) +} + +// CreateBucket creates a new bucket. +// Returns an error if the bucket already exists, if the bucket name is blank, or if the bucket name is too long. +// The bucket instance is only valid for the lifetime of the transaction. +func (tx *Tx) CreateBucket(name []byte) (*Bucket, error) { + return tx.root.CreateBucket(name) +} + +// CreateBucketIfNotExists creates a new bucket if it doesn't already exist. +// Returns an error if the bucket name is blank, or if the bucket name is too long. +// The bucket instance is only valid for the lifetime of the transaction. +func (tx *Tx) CreateBucketIfNotExists(name []byte) (*Bucket, error) { + return tx.root.CreateBucketIfNotExists(name) +} + +// DeleteBucket deletes a bucket. +// Returns an error if the bucket cannot be found or if the key represents a non-bucket value. +func (tx *Tx) DeleteBucket(name []byte) error { + return tx.root.DeleteBucket(name) +} + +// ForEach executes a function for each bucket in the root. +// If the provided function returns an error then the iteration is stopped and +// the error is returned to the caller. +func (tx *Tx) ForEach(fn func(name []byte, b *Bucket) error) error { + return tx.root.ForEach(func(k, v []byte) error { + if err := fn(k, tx.root.Bucket(k)); err != nil { + return err + } + return nil + }) +} + +// OnCommit adds a handler function to be executed after the transaction successfully commits. +func (tx *Tx) OnCommit(fn func()) { + tx.commitHandlers = append(tx.commitHandlers, fn) +} + +// Commit writes all changes to disk and updates the meta page. +// Returns an error if a disk write error occurs, or if Commit is +// called on a read-only transaction. +func (tx *Tx) Commit() error { + _assert(!tx.managed, "managed tx commit not allowed") + if tx.db == nil { + return ErrTxClosed + } else if !tx.writable { + return ErrTxNotWritable + } + + // TODO(benbjohnson): Use vectorized I/O to write out dirty pages. + + // Rebalance nodes which have had deletions. + var startTime = time.Now() + tx.root.rebalance() + if tx.stats.Rebalance > 0 { + tx.stats.RebalanceTime += time.Since(startTime) + } + + // spill data onto dirty pages. + startTime = time.Now() + if err := tx.root.spill(); err != nil { + tx.rollback() + return err + } + tx.stats.SpillTime += time.Since(startTime) + + // Free the old root bucket. + tx.meta.root.root = tx.root.root + + opgid := tx.meta.pgid + + // Free the freelist and allocate new pages for it. This will overestimate + // the size of the freelist but not underestimate the size (which would be bad). + tx.db.freelist.free(tx.meta.txid, tx.db.page(tx.meta.freelist)) + p, err := tx.allocate((tx.db.freelist.size() / tx.db.pageSize) + 1) + if err != nil { + tx.rollback() + return err + } + if err := tx.db.freelist.write(p); err != nil { + tx.rollback() + return err + } + tx.meta.freelist = p.id + + // If the high water mark has moved up then attempt to grow the database. + if tx.meta.pgid > opgid { + if err := tx.db.grow(int(tx.meta.pgid+1) * tx.db.pageSize); err != nil { + tx.rollback() + return err + } + } + + // Write dirty pages to disk. + startTime = time.Now() + if err := tx.write(); err != nil { + tx.rollback() + return err + } + + // If strict mode is enabled then perform a consistency check. + // Only the first consistency error is reported in the panic. + if tx.db.StrictMode { + ch := tx.Check() + var errs []string + for { + err, ok := <-ch + if !ok { + break + } + errs = append(errs, err.Error()) + } + if len(errs) > 0 { + panic("check fail: " + strings.Join(errs, "\n")) + } + } + + // Write meta to disk. + if err := tx.writeMeta(); err != nil { + tx.rollback() + return err + } + tx.stats.WriteTime += time.Since(startTime) + + // Finalize the transaction. + tx.close() + + // Execute commit handlers now that the locks have been removed. + for _, fn := range tx.commitHandlers { + fn() + } + + return nil +} + +// Rollback closes the transaction and ignores all previous updates. Read-only +// transactions must be rolled back and not committed. +func (tx *Tx) Rollback() error { + _assert(!tx.managed, "managed tx rollback not allowed") + if tx.db == nil { + return ErrTxClosed + } + tx.rollback() + return nil +} + +func (tx *Tx) rollback() { + if tx.db == nil { + return + } + if tx.writable { + tx.db.freelist.rollback(tx.meta.txid) + tx.db.freelist.reload(tx.db.page(tx.db.meta().freelist)) + } + tx.close() +} + +func (tx *Tx) close() { + if tx.db == nil { + return + } + if tx.writable { + // Grab freelist stats. + var freelistFreeN = tx.db.freelist.free_count() + var freelistPendingN = tx.db.freelist.pending_count() + var freelistAlloc = tx.db.freelist.size() + + // Remove transaction ref & writer lock. + tx.db.rwtx = nil + tx.db.rwlock.Unlock() + + // Merge statistics. + tx.db.statlock.Lock() + tx.db.stats.FreePageN = freelistFreeN + tx.db.stats.PendingPageN = freelistPendingN + tx.db.stats.FreeAlloc = (freelistFreeN + freelistPendingN) * tx.db.pageSize + tx.db.stats.FreelistInuse = freelistAlloc + tx.db.stats.TxStats.add(&tx.stats) + tx.db.statlock.Unlock() + } else { + tx.db.removeTx(tx) + } + + // Clear all references. + tx.db = nil + tx.meta = nil + tx.root = Bucket{tx: tx} + tx.pages = nil +} + +// Copy writes the entire database to a writer. +// This function exists for backwards compatibility. Use WriteTo() instead. +func (tx *Tx) Copy(w io.Writer) error { + _, err := tx.WriteTo(w) + return err +} + +// WriteTo writes the entire database to a writer. +// If err == nil then exactly tx.Size() bytes will be written into the writer. +func (tx *Tx) WriteTo(w io.Writer) (n int64, err error) { + // Attempt to open reader with WriteFlag + f, err := os.OpenFile(tx.db.path, os.O_RDONLY|tx.WriteFlag, 0) + if err != nil { + return 0, err + } + defer func() { _ = f.Close() }() + + // Generate a meta page. We use the same page data for both meta pages. + buf := make([]byte, tx.db.pageSize) + page := (*page)(unsafe.Pointer(&buf[0])) + page.flags = metaPageFlag + *page.meta() = *tx.meta + + // Write meta 0. + page.id = 0 + page.meta().checksum = page.meta().sum64() + nn, err := w.Write(buf) + n += int64(nn) + if err != nil { + return n, fmt.Errorf("meta 0 copy: %s", err) + } + + // Write meta 1 with a lower transaction id. + page.id = 1 + page.meta().txid -= 1 + page.meta().checksum = page.meta().sum64() + nn, err = w.Write(buf) + n += int64(nn) + if err != nil { + return n, fmt.Errorf("meta 1 copy: %s", err) + } + + // Move past the meta pages in the file. + if _, err := f.Seek(int64(tx.db.pageSize*2), os.SEEK_SET); err != nil { + return n, fmt.Errorf("seek: %s", err) + } + + // Copy data pages. + wn, err := io.CopyN(w, f, tx.Size()-int64(tx.db.pageSize*2)) + n += wn + if err != nil { + return n, err + } + + return n, f.Close() +} + +// CopyFile copies the entire database to file at the given path. +// A reader transaction is maintained during the copy so it is safe to continue +// using the database while a copy is in progress. +func (tx *Tx) CopyFile(path string, mode os.FileMode) error { + f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode) + if err != nil { + return err + } + + err = tx.Copy(f) + if err != nil { + _ = f.Close() + return err + } + return f.Close() +} + +// Check performs several consistency checks on the database for this transaction. +// An error is returned if any inconsistency is found. +// +// It can be safely run concurrently on a writable transaction. However, this +// incurs a high cost for large databases and databases with a lot of subbuckets +// because of caching. This overhead can be removed if running on a read-only +// transaction, however, it is not safe to execute other writer transactions at +// the same time. +func (tx *Tx) Check() <-chan error { + ch := make(chan error) + go tx.check(ch) + return ch +} + +func (tx *Tx) check(ch chan error) { + // Check if any pages are double freed. + freed := make(map[pgid]bool) + all := make([]pgid, tx.db.freelist.count()) + tx.db.freelist.copyall(all) + for _, id := range all { + if freed[id] { + ch <- fmt.Errorf("page %d: already freed", id) + } + freed[id] = true + } + + // Track every reachable page. + reachable := make(map[pgid]*page) + reachable[0] = tx.page(0) // meta0 + reachable[1] = tx.page(1) // meta1 + for i := uint32(0); i <= tx.page(tx.meta.freelist).overflow; i++ { + reachable[tx.meta.freelist+pgid(i)] = tx.page(tx.meta.freelist) + } + + // Recursively check buckets. + tx.checkBucket(&tx.root, reachable, freed, ch) + + // Ensure all pages below high water mark are either reachable or freed. + for i := pgid(0); i < tx.meta.pgid; i++ { + _, isReachable := reachable[i] + if !isReachable && !freed[i] { + ch <- fmt.Errorf("page %d: unreachable unfreed", int(i)) + } + } + + // Close the channel to signal completion. + close(ch) +} + +func (tx *Tx) checkBucket(b *Bucket, reachable map[pgid]*page, freed map[pgid]bool, ch chan error) { + // Ignore inline buckets. + if b.root == 0 { + return + } + + // Check every page used by this bucket. + b.tx.forEachPage(b.root, 0, func(p *page, _ int) { + if p.id > tx.meta.pgid { + ch <- fmt.Errorf("page %d: out of bounds: %d", int(p.id), int(b.tx.meta.pgid)) + } + + // Ensure each page is only referenced once. + for i := pgid(0); i <= pgid(p.overflow); i++ { + var id = p.id + i + if _, ok := reachable[id]; ok { + ch <- fmt.Errorf("page %d: multiple references", int(id)) + } + reachable[id] = p + } + + // We should only encounter un-freed leaf and branch pages. + if freed[p.id] { + ch <- fmt.Errorf("page %d: reachable freed", int(p.id)) + } else if (p.flags&branchPageFlag) == 0 && (p.flags&leafPageFlag) == 0 { + ch <- fmt.Errorf("page %d: invalid type: %s", int(p.id), p.typ()) + } + }) + + // Check each bucket within this bucket. + _ = b.ForEach(func(k, v []byte) error { + if child := b.Bucket(k); child != nil { + tx.checkBucket(child, reachable, freed, ch) + } + return nil + }) +} + +// allocate returns a contiguous block of memory starting at a given page. +func (tx *Tx) allocate(count int) (*page, error) { + p, err := tx.db.allocate(count) + if err != nil { + return nil, err + } + + // Save to our page cache. + tx.pages[p.id] = p + + // Update statistics. + tx.stats.PageCount++ + tx.stats.PageAlloc += count * tx.db.pageSize + + return p, nil +} + +// write writes any dirty pages to disk. +func (tx *Tx) write() error { + // Sort pages by id. + pages := make(pages, 0, len(tx.pages)) + for _, p := range tx.pages { + pages = append(pages, p) + } + // Clear out page cache early. + tx.pages = make(map[pgid]*page) + sort.Sort(pages) + + // Write pages to disk in order. + for _, p := range pages { + size := (int(p.overflow) + 1) * tx.db.pageSize + offset := int64(p.id) * int64(tx.db.pageSize) + + // Write out page in "max allocation" sized chunks. + ptr := (*[maxAllocSize]byte)(unsafe.Pointer(p)) + for { + // Limit our write to our max allocation size. + sz := size + if sz > maxAllocSize-1 { + sz = maxAllocSize - 1 + } + + // Write chunk to disk. + buf := ptr[:sz] + if _, err := tx.db.ops.writeAt(buf, offset); err != nil { + return err + } + + // Update statistics. + tx.stats.Write++ + + // Exit inner for loop if we've written all the chunks. + size -= sz + if size == 0 { + break + } + + // Otherwise move offset forward and move pointer to next chunk. + offset += int64(sz) + ptr = (*[maxAllocSize]byte)(unsafe.Pointer(&ptr[sz])) + } + } + + // Ignore file sync if flag is set on DB. + if !tx.db.NoSync || IgnoreNoSync { + if err := fdatasync(tx.db); err != nil { + return err + } + } + + // Put small pages back to page pool. + for _, p := range pages { + // Ignore page sizes over 1 page. + // These are allocated using make() instead of the page pool. + if int(p.overflow) != 0 { + continue + } + + buf := (*[maxAllocSize]byte)(unsafe.Pointer(p))[:tx.db.pageSize] + + // See https://go.googlesource.com/go/+/f03c9202c43e0abb130669852082117ca50aa9b1 + for i := range buf { + buf[i] = 0 + } + tx.db.pagePool.Put(buf) + } + + return nil +} + +// writeMeta writes the meta to the disk. +func (tx *Tx) writeMeta() error { + // Create a temporary buffer for the meta page. + buf := make([]byte, tx.db.pageSize) + p := tx.db.pageInBuffer(buf, 0) + tx.meta.write(p) + + // Write the meta page to file. + if _, err := tx.db.ops.writeAt(buf, int64(p.id)*int64(tx.db.pageSize)); err != nil { + return err + } + if !tx.db.NoSync || IgnoreNoSync { + if err := fdatasync(tx.db); err != nil { + return err + } + } + + // Update statistics. + tx.stats.Write++ + + return nil +} + +// page returns a reference to the page with a given id. +// If page has been written to then a temporary buffered page is returned. +func (tx *Tx) page(id pgid) *page { + // Check the dirty pages first. + if tx.pages != nil { + if p, ok := tx.pages[id]; ok { + return p + } + } + + // Otherwise return directly from the mmap. + return tx.db.page(id) +} + +// forEachPage iterates over every page within a given page and executes a function. +func (tx *Tx) forEachPage(pgid pgid, depth int, fn func(*page, int)) { + p := tx.page(pgid) + + // Execute function. + fn(p, depth) + + // Recursively loop over children. + if (p.flags & branchPageFlag) != 0 { + for i := 0; i < int(p.count); i++ { + elem := p.branchPageElement(uint16(i)) + tx.forEachPage(elem.pgid, depth+1, fn) + } + } +} + +// Page returns page information for a given page number. +// This is only safe for concurrent use when used by a writable transaction. +func (tx *Tx) Page(id int) (*PageInfo, error) { + if tx.db == nil { + return nil, ErrTxClosed + } else if pgid(id) >= tx.meta.pgid { + return nil, nil + } + + // Build the page info. + p := tx.db.page(pgid(id)) + info := &PageInfo{ + ID: id, + Count: int(p.count), + OverflowCount: int(p.overflow), + } + + // Determine the type (or if it's free). + if tx.db.freelist.freed(pgid(id)) { + info.Type = "free" + } else { + info.Type = p.typ() + } + + return info, nil +} + +// TxStats represents statistics about the actions performed by the transaction. +type TxStats struct { + // Page statistics. + PageCount int // number of page allocations + PageAlloc int // total bytes allocated + + // Cursor statistics. + CursorCount int // number of cursors created + + // Node statistics + NodeCount int // number of node allocations + NodeDeref int // number of node dereferences + + // Rebalance statistics. + Rebalance int // number of node rebalances + RebalanceTime time.Duration // total time spent rebalancing + + // Split/Spill statistics. + Split int // number of nodes split + Spill int // number of nodes spilled + SpillTime time.Duration // total time spent spilling + + // Write statistics. + Write int // number of writes performed + WriteTime time.Duration // total time spent writing to disk +} + +func (s *TxStats) add(other *TxStats) { + s.PageCount += other.PageCount + s.PageAlloc += other.PageAlloc + s.CursorCount += other.CursorCount + s.NodeCount += other.NodeCount + s.NodeDeref += other.NodeDeref + s.Rebalance += other.Rebalance + s.RebalanceTime += other.RebalanceTime + s.Split += other.Split + s.Spill += other.Spill + s.SpillTime += other.SpillTime + s.Write += other.Write + s.WriteTime += other.WriteTime +} + +// Sub calculates and returns the difference between two sets of transaction stats. +// This is useful when obtaining stats at two different points and time and +// you need the performance counters that occurred within that time span. +func (s *TxStats) Sub(other *TxStats) TxStats { + var diff TxStats + diff.PageCount = s.PageCount - other.PageCount + diff.PageAlloc = s.PageAlloc - other.PageAlloc + diff.CursorCount = s.CursorCount - other.CursorCount + diff.NodeCount = s.NodeCount - other.NodeCount + diff.NodeDeref = s.NodeDeref - other.NodeDeref + diff.Rebalance = s.Rebalance - other.Rebalance + diff.RebalanceTime = s.RebalanceTime - other.RebalanceTime + diff.Split = s.Split - other.Split + diff.Spill = s.Spill - other.Spill + diff.SpillTime = s.SpillTime - other.SpillTime + diff.Write = s.Write - other.Write + diff.WriteTime = s.WriteTime - other.WriteTime + return diff +} diff --git a/vendor/github.com/davecgh/go-spew/spew/bypass.go b/vendor/github.com/davecgh/go-spew/spew/bypass.go index 70ddeaad3..792994785 100644 --- a/vendor/github.com/davecgh/go-spew/spew/bypass.go +++ b/vendor/github.com/davecgh/go-spew/spew/bypass.go @@ -18,7 +18,6 @@ // tag is deprecated and thus should not be used. // Go versions prior to 1.4 are disabled because they use a different layout // for interfaces which make the implementation of unsafeReflectValue more complex. -//go:build !js && !appengine && !safe && !disableunsafe && go1.4 // +build !js,!appengine,!safe,!disableunsafe,go1.4 package spew diff --git a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go index 5e2d890d6..205c28d68 100644 --- a/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go +++ b/vendor/github.com/davecgh/go-spew/spew/bypasssafe.go @@ -16,7 +16,6 @@ // when the code is running on Google App Engine, compiled by GopherJS, or // "-tags safe" is added to the go build command line. The "disableunsafe" // tag is deprecated and thus should not be used. -//go:build js || appengine || safe || disableunsafe || !go1.4 // +build js appengine safe disableunsafe !go1.4 package spew diff --git a/vendor/github.com/gen2brain/dlgs/color_darwin.go b/vendor/github.com/gen2brain/dlgs/color_darwin.go index 0ed8c14bd..d77c4cfd4 100644 --- a/vendor/github.com/gen2brain/dlgs/color_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/color_darwin.go @@ -1,4 +1,3 @@ -//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/color_js.go b/vendor/github.com/gen2brain/dlgs/color_js.go index 0602429b3..514ecb0d1 100644 --- a/vendor/github.com/gen2brain/dlgs/color_js.go +++ b/vendor/github.com/gen2brain/dlgs/color_js.go @@ -1,4 +1,3 @@ -//go:build js // +build js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/color_linux.go b/vendor/github.com/gen2brain/dlgs/color_linux.go index 5bc26b39b..3eed6d709 100644 --- a/vendor/github.com/gen2brain/dlgs/color_linux.go +++ b/vendor/github.com/gen2brain/dlgs/color_linux.go @@ -1,4 +1,3 @@ -//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/color_unsupported.go b/vendor/github.com/gen2brain/dlgs/color_unsupported.go index b3498110e..213cb4c26 100644 --- a/vendor/github.com/gen2brain/dlgs/color_unsupported.go +++ b/vendor/github.com/gen2brain/dlgs/color_unsupported.go @@ -1,4 +1,3 @@ -//go:build !linux && !windows && !darwin && !js // +build !linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/color_windows.go b/vendor/github.com/gen2brain/dlgs/color_windows.go index 9e12cf5ba..773b0e434 100644 --- a/vendor/github.com/gen2brain/dlgs/color_windows.go +++ b/vendor/github.com/gen2brain/dlgs/color_windows.go @@ -1,4 +1,3 @@ -//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/date_darwin.go b/vendor/github.com/gen2brain/dlgs/date_darwin.go index 79d7cd27e..995f08a4f 100644 --- a/vendor/github.com/gen2brain/dlgs/date_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/date_darwin.go @@ -1,4 +1,3 @@ -//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/date_js.go b/vendor/github.com/gen2brain/dlgs/date_js.go index 44590fcbb..c04e8aa62 100644 --- a/vendor/github.com/gen2brain/dlgs/date_js.go +++ b/vendor/github.com/gen2brain/dlgs/date_js.go @@ -1,4 +1,3 @@ -//go:build js // +build js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/date_linux.go b/vendor/github.com/gen2brain/dlgs/date_linux.go index ac7dcb329..e01fcd51b 100644 --- a/vendor/github.com/gen2brain/dlgs/date_linux.go +++ b/vendor/github.com/gen2brain/dlgs/date_linux.go @@ -1,4 +1,3 @@ -//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/date_unsupported.go b/vendor/github.com/gen2brain/dlgs/date_unsupported.go index d1743cd60..dedce2a46 100644 --- a/vendor/github.com/gen2brain/dlgs/date_unsupported.go +++ b/vendor/github.com/gen2brain/dlgs/date_unsupported.go @@ -1,4 +1,3 @@ -//go:build !linux && !windows && !darwin && !js // +build !linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/date_windows.go b/vendor/github.com/gen2brain/dlgs/date_windows.go index 4e15ed042..933269557 100644 --- a/vendor/github.com/gen2brain/dlgs/date_windows.go +++ b/vendor/github.com/gen2brain/dlgs/date_windows.go @@ -1,4 +1,3 @@ -//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/dlgs_darwin.go b/vendor/github.com/gen2brain/dlgs/dlgs_darwin.go index 3c4359cc7..d94a194bd 100644 --- a/vendor/github.com/gen2brain/dlgs/dlgs_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/dlgs_darwin.go @@ -1,4 +1,3 @@ -//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/dlgs_linux.go b/vendor/github.com/gen2brain/dlgs/dlgs_linux.go index 9d7ddc4e5..afb6d6f3a 100644 --- a/vendor/github.com/gen2brain/dlgs/dlgs_linux.go +++ b/vendor/github.com/gen2brain/dlgs/dlgs_linux.go @@ -1,4 +1,3 @@ -//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/dlgs_windows.go b/vendor/github.com/gen2brain/dlgs/dlgs_windows.go index ba8034757..e1feb3701 100644 --- a/vendor/github.com/gen2brain/dlgs/dlgs_windows.go +++ b/vendor/github.com/gen2brain/dlgs/dlgs_windows.go @@ -1,4 +1,3 @@ -//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/entry_darwin.go b/vendor/github.com/gen2brain/dlgs/entry_darwin.go index c10dcfae1..19aa7613f 100644 --- a/vendor/github.com/gen2brain/dlgs/entry_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/entry_darwin.go @@ -1,4 +1,3 @@ -//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/entry_js.go b/vendor/github.com/gen2brain/dlgs/entry_js.go index eb786ec41..c4b96f825 100644 --- a/vendor/github.com/gen2brain/dlgs/entry_js.go +++ b/vendor/github.com/gen2brain/dlgs/entry_js.go @@ -1,4 +1,3 @@ -//go:build js // +build js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/entry_linux.go b/vendor/github.com/gen2brain/dlgs/entry_linux.go index 500460e64..aabfbba54 100644 --- a/vendor/github.com/gen2brain/dlgs/entry_linux.go +++ b/vendor/github.com/gen2brain/dlgs/entry_linux.go @@ -1,4 +1,3 @@ -//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/entry_unsupported.go b/vendor/github.com/gen2brain/dlgs/entry_unsupported.go index c8117aebe..25c53aa33 100644 --- a/vendor/github.com/gen2brain/dlgs/entry_unsupported.go +++ b/vendor/github.com/gen2brain/dlgs/entry_unsupported.go @@ -1,4 +1,3 @@ -//go:build !linux && !windows && !darwin && !js // +build !linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/entry_windows.go b/vendor/github.com/gen2brain/dlgs/entry_windows.go index a78cc82af..9c8b22dd6 100644 --- a/vendor/github.com/gen2brain/dlgs/entry_windows.go +++ b/vendor/github.com/gen2brain/dlgs/entry_windows.go @@ -1,4 +1,3 @@ -//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/file_darwin.go b/vendor/github.com/gen2brain/dlgs/file_darwin.go index 01d18f9ba..d07677ba4 100644 --- a/vendor/github.com/gen2brain/dlgs/file_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/file_darwin.go @@ -1,4 +1,3 @@ -//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/file_js.go b/vendor/github.com/gen2brain/dlgs/file_js.go index 3c39b894f..d311ce04f 100644 --- a/vendor/github.com/gen2brain/dlgs/file_js.go +++ b/vendor/github.com/gen2brain/dlgs/file_js.go @@ -1,9 +1,10 @@ -//go:build js // +build js package dlgs +import ( //"github.com/gopherjs/gopherjs/js" +) // File displays a file dialog, returning the selected file/directory and a bool for success. func File(title, filter string, directory bool) (string, bool, error) { diff --git a/vendor/github.com/gen2brain/dlgs/file_linux.go b/vendor/github.com/gen2brain/dlgs/file_linux.go index f39a77d53..c2472de98 100644 --- a/vendor/github.com/gen2brain/dlgs/file_linux.go +++ b/vendor/github.com/gen2brain/dlgs/file_linux.go @@ -1,4 +1,3 @@ -//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs @@ -10,8 +9,8 @@ import ( ) // File displays a file dialog, returning the selected file or directory, a bool for success, and an -// error if it was unable to display the dialog. Filter is a string that determines -// which extensions should be displayed for the dialog. Separate multiple file +// error if it was unable to display the dialog. Filter is a string that determines +// which extensions should be displayed for the dialog. Separate multiple file // extensions by spaces and use "*.extension" format for cross-platform compatibility, e.g. "*.png *.jpg". // A blank string for the filter will display all file types. func File(title, filter string, directory bool) (string, bool, error) { @@ -47,9 +46,9 @@ func File(title, filter string, directory bool) (string, bool, error) { return out, ret, err } -// FileMulti displays a file dialog that allows for selecting multiple files. It returns the selected -// files, a bool for success, and an error if it was unable to display the dialog. Filter is a string -// that determines which files should be available for selection in the dialog. Separate multiple file +// FileMulti displays a file dialog that allows for selecting multiple files. It returns the selected +// files, a bool for success, and an error if it was unable to display the dialog. Filter is a string +// that determines which files should be available for selection in the dialog. Separate multiple file // extensions by spaces and use "*.extension" format for cross-platform compatibility, e.g. "*.png *.jpg". // A blank string for the filter will display all file types. func FileMulti(title, filter string) ([]string, bool, error) { diff --git a/vendor/github.com/gen2brain/dlgs/file_unsupported.go b/vendor/github.com/gen2brain/dlgs/file_unsupported.go index 699ffc0cf..7c8784053 100644 --- a/vendor/github.com/gen2brain/dlgs/file_unsupported.go +++ b/vendor/github.com/gen2brain/dlgs/file_unsupported.go @@ -1,4 +1,3 @@ -//go:build !linux && !windows && !darwin && !js // +build !linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/file_windows.go b/vendor/github.com/gen2brain/dlgs/file_windows.go index f36d83cbc..30d8c3fbf 100644 --- a/vendor/github.com/gen2brain/dlgs/file_windows.go +++ b/vendor/github.com/gen2brain/dlgs/file_windows.go @@ -1,4 +1,3 @@ -//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/list_darwin.go b/vendor/github.com/gen2brain/dlgs/list_darwin.go index a7f102852..433a84225 100644 --- a/vendor/github.com/gen2brain/dlgs/list_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/list_darwin.go @@ -1,4 +1,3 @@ -//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/list_js.go b/vendor/github.com/gen2brain/dlgs/list_js.go index a6ff7e4ba..905c03684 100644 --- a/vendor/github.com/gen2brain/dlgs/list_js.go +++ b/vendor/github.com/gen2brain/dlgs/list_js.go @@ -1,9 +1,10 @@ -//go:build js // +build js package dlgs +import ( //"github.com/gopherjs/gopherjs/js" +) // List displays a list dialog, returning the selected value and a bool for success. func List(title, text string, items []string) (string, bool, error) { diff --git a/vendor/github.com/gen2brain/dlgs/list_linux.go b/vendor/github.com/gen2brain/dlgs/list_linux.go index 037ebb677..38dc8a5d4 100644 --- a/vendor/github.com/gen2brain/dlgs/list_linux.go +++ b/vendor/github.com/gen2brain/dlgs/list_linux.go @@ -1,4 +1,3 @@ -//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/list_unsupported.go b/vendor/github.com/gen2brain/dlgs/list_unsupported.go index afe5a2bac..026a25890 100644 --- a/vendor/github.com/gen2brain/dlgs/list_unsupported.go +++ b/vendor/github.com/gen2brain/dlgs/list_unsupported.go @@ -1,4 +1,3 @@ -//go:build !linux && !windows && !darwin && !js // +build !linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/list_windows.go b/vendor/github.com/gen2brain/dlgs/list_windows.go index 173780f15..55ae56e0c 100644 --- a/vendor/github.com/gen2brain/dlgs/list_windows.go +++ b/vendor/github.com/gen2brain/dlgs/list_windows.go @@ -1,4 +1,3 @@ -//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/message_darwin.go b/vendor/github.com/gen2brain/dlgs/message_darwin.go index 32e098ab6..dbfa29a0d 100644 --- a/vendor/github.com/gen2brain/dlgs/message_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/message_darwin.go @@ -1,4 +1,3 @@ -//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/message_js.go b/vendor/github.com/gen2brain/dlgs/message_js.go index 7842f76cd..1c3e665ff 100644 --- a/vendor/github.com/gen2brain/dlgs/message_js.go +++ b/vendor/github.com/gen2brain/dlgs/message_js.go @@ -1,4 +1,3 @@ -//go:build js // +build js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/message_linux.go b/vendor/github.com/gen2brain/dlgs/message_linux.go index d6cbd534c..55c9a9844 100644 --- a/vendor/github.com/gen2brain/dlgs/message_linux.go +++ b/vendor/github.com/gen2brain/dlgs/message_linux.go @@ -1,4 +1,3 @@ -//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/message_unsupported.go b/vendor/github.com/gen2brain/dlgs/message_unsupported.go index fadbb2467..0ba7cc276 100644 --- a/vendor/github.com/gen2brain/dlgs/message_unsupported.go +++ b/vendor/github.com/gen2brain/dlgs/message_unsupported.go @@ -1,4 +1,3 @@ -//go:build !linux && !windows && !darwin && !js // +build !linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/message_windows.go b/vendor/github.com/gen2brain/dlgs/message_windows.go index e167ec283..497eeb39e 100644 --- a/vendor/github.com/gen2brain/dlgs/message_windows.go +++ b/vendor/github.com/gen2brain/dlgs/message_windows.go @@ -1,4 +1,3 @@ -//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/password_darwin.go b/vendor/github.com/gen2brain/dlgs/password_darwin.go index 9d9839512..e2db710ef 100644 --- a/vendor/github.com/gen2brain/dlgs/password_darwin.go +++ b/vendor/github.com/gen2brain/dlgs/password_darwin.go @@ -1,4 +1,3 @@ -//go:build darwin && !linux && !windows && !js // +build darwin,!linux,!windows,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/password_js.go b/vendor/github.com/gen2brain/dlgs/password_js.go index 73ebd4556..968fae5c2 100644 --- a/vendor/github.com/gen2brain/dlgs/password_js.go +++ b/vendor/github.com/gen2brain/dlgs/password_js.go @@ -1,4 +1,3 @@ -//go:build js // +build js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/password_linux.go b/vendor/github.com/gen2brain/dlgs/password_linux.go index 6ede485da..c755c0bb5 100644 --- a/vendor/github.com/gen2brain/dlgs/password_linux.go +++ b/vendor/github.com/gen2brain/dlgs/password_linux.go @@ -1,4 +1,3 @@ -//go:build linux && !windows && !darwin && !js // +build linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/password_unsupported.go b/vendor/github.com/gen2brain/dlgs/password_unsupported.go index 74dc216cc..607a2076d 100644 --- a/vendor/github.com/gen2brain/dlgs/password_unsupported.go +++ b/vendor/github.com/gen2brain/dlgs/password_unsupported.go @@ -1,4 +1,3 @@ -//go:build !linux && !windows && !darwin && !js // +build !linux,!windows,!darwin,!js package dlgs diff --git a/vendor/github.com/gen2brain/dlgs/password_windows.go b/vendor/github.com/gen2brain/dlgs/password_windows.go index b4a13643e..ef1cf6beb 100644 --- a/vendor/github.com/gen2brain/dlgs/password_windows.go +++ b/vendor/github.com/gen2brain/dlgs/password_windows.go @@ -1,4 +1,3 @@ -//go:build windows && !linux && !darwin && !js // +build windows,!linux,!darwin,!js package dlgs diff --git a/vendor/github.com/go-ole/go-ole/com.go b/vendor/github.com/go-ole/go-ole/com.go index dca260e1c..cabbac012 100644 --- a/vendor/github.com/go-ole/go-ole/com.go +++ b/vendor/github.com/go-ole/go-ole/com.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/com_func.go b/vendor/github.com/go-ole/go-ole/com_func.go index 7b9fa67f3..cef539d9d 100644 --- a/vendor/github.com/go-ole/go-ole/com_func.go +++ b/vendor/github.com/go-ole/go-ole/com_func.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/error_func.go b/vendor/github.com/go-ole/go-ole/error_func.go index 6478b3390..8a2ffaa27 100644 --- a/vendor/github.com/go-ole/go-ole/error_func.go +++ b/vendor/github.com/go-ole/go-ole/error_func.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/error_windows.go b/vendor/github.com/go-ole/go-ole/error_windows.go index 8da277c05..d0e8e6859 100644 --- a/vendor/github.com/go-ole/go-ole/error_windows.go +++ b/vendor/github.com/go-ole/go-ole/error_windows.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iconnectionpoint_func.go b/vendor/github.com/go-ole/go-ole/iconnectionpoint_func.go index 999720a0d..5414dc3cd 100644 --- a/vendor/github.com/go-ole/go-ole/iconnectionpoint_func.go +++ b/vendor/github.com/go-ole/go-ole/iconnectionpoint_func.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iconnectionpoint_windows.go b/vendor/github.com/go-ole/go-ole/iconnectionpoint_windows.go index c7325ad0b..32bc18324 100644 --- a/vendor/github.com/go-ole/go-ole/iconnectionpoint_windows.go +++ b/vendor/github.com/go-ole/go-ole/iconnectionpoint_windows.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_func.go b/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_func.go index 26e264d1b..5dfa42aae 100644 --- a/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_func.go +++ b/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_func.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_windows.go b/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_windows.go index 8b090f49e..ad30d79ef 100644 --- a/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_windows.go +++ b/vendor/github.com/go-ole/go-ole/iconnectionpointcontainer_windows.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/idispatch_func.go b/vendor/github.com/go-ole/go-ole/idispatch_func.go index 5315505ae..b8fbbe319 100644 --- a/vendor/github.com/go-ole/go-ole/idispatch_func.go +++ b/vendor/github.com/go-ole/go-ole/idispatch_func.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/ienumvariant_func.go b/vendor/github.com/go-ole/go-ole/ienumvariant_func.go index f332e439b..c14848199 100644 --- a/vendor/github.com/go-ole/go-ole/ienumvariant_func.go +++ b/vendor/github.com/go-ole/go-ole/ienumvariant_func.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/ienumvariant_windows.go b/vendor/github.com/go-ole/go-ole/ienumvariant_windows.go index 72e5f31d6..4781f3b8b 100644 --- a/vendor/github.com/go-ole/go-ole/ienumvariant_windows.go +++ b/vendor/github.com/go-ole/go-ole/ienumvariant_windows.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iinspectable_func.go b/vendor/github.com/go-ole/go-ole/iinspectable_func.go index cf0fba0dc..348829bf0 100644 --- a/vendor/github.com/go-ole/go-ole/iinspectable_func.go +++ b/vendor/github.com/go-ole/go-ole/iinspectable_func.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iinspectable_windows.go b/vendor/github.com/go-ole/go-ole/iinspectable_windows.go index 9a686d256..4519a4aa4 100644 --- a/vendor/github.com/go-ole/go-ole/iinspectable_windows.go +++ b/vendor/github.com/go-ole/go-ole/iinspectable_windows.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iprovideclassinfo_func.go b/vendor/github.com/go-ole/go-ole/iprovideclassinfo_func.go index 90109f557..7e3cb63ea 100644 --- a/vendor/github.com/go-ole/go-ole/iprovideclassinfo_func.go +++ b/vendor/github.com/go-ole/go-ole/iprovideclassinfo_func.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iprovideclassinfo_windows.go b/vendor/github.com/go-ole/go-ole/iprovideclassinfo_windows.go index c758acd9b..2ad016394 100644 --- a/vendor/github.com/go-ole/go-ole/iprovideclassinfo_windows.go +++ b/vendor/github.com/go-ole/go-ole/iprovideclassinfo_windows.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/itypeinfo_func.go b/vendor/github.com/go-ole/go-ole/itypeinfo_func.go index 31c0677c6..8364a659b 100644 --- a/vendor/github.com/go-ole/go-ole/itypeinfo_func.go +++ b/vendor/github.com/go-ole/go-ole/itypeinfo_func.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/itypeinfo_windows.go b/vendor/github.com/go-ole/go-ole/itypeinfo_windows.go index 2abab8214..54782b3da 100644 --- a/vendor/github.com/go-ole/go-ole/itypeinfo_windows.go +++ b/vendor/github.com/go-ole/go-ole/itypeinfo_windows.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iunknown_func.go b/vendor/github.com/go-ole/go-ole/iunknown_func.go index 247fccb3c..d0a62cfd7 100644 --- a/vendor/github.com/go-ole/go-ole/iunknown_func.go +++ b/vendor/github.com/go-ole/go-ole/iunknown_func.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/iunknown_windows.go b/vendor/github.com/go-ole/go-ole/iunknown_windows.go index faf9c4c7f..ede5bb8c1 100644 --- a/vendor/github.com/go-ole/go-ole/iunknown_windows.go +++ b/vendor/github.com/go-ole/go-ole/iunknown_windows.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/oleutil/connection.go b/vendor/github.com/go-ole/go-ole/oleutil/connection.go index 4c52d55ef..60df73cda 100644 --- a/vendor/github.com/go-ole/go-ole/oleutil/connection.go +++ b/vendor/github.com/go-ole/go-ole/oleutil/connection.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package oleutil diff --git a/vendor/github.com/go-ole/go-ole/oleutil/connection_func.go b/vendor/github.com/go-ole/go-ole/oleutil/connection_func.go index b00ac4a92..8818fb827 100644 --- a/vendor/github.com/go-ole/go-ole/oleutil/connection_func.go +++ b/vendor/github.com/go-ole/go-ole/oleutil/connection_func.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package oleutil diff --git a/vendor/github.com/go-ole/go-ole/oleutil/connection_windows.go b/vendor/github.com/go-ole/go-ole/oleutil/connection_windows.go index 19fa27e51..ab9c0d8dc 100644 --- a/vendor/github.com/go-ole/go-ole/oleutil/connection_windows.go +++ b/vendor/github.com/go-ole/go-ole/oleutil/connection_windows.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package oleutil diff --git a/vendor/github.com/go-ole/go-ole/oleutil/go-get.go b/vendor/github.com/go-ole/go-ole/oleutil/go-get.go index 40bd9ff61..58347628f 100644 --- a/vendor/github.com/go-ole/go-ole/oleutil/go-get.go +++ b/vendor/github.com/go-ole/go-ole/oleutil/go-get.go @@ -1,7 +1,6 @@ // This file is here so go get succeeds as without it errors with: // no buildable Go source files in ... // -//go:build !windows // +build !windows package oleutil diff --git a/vendor/github.com/go-ole/go-ole/safearray_func.go b/vendor/github.com/go-ole/go-ole/safearray_func.go index afb1d02d5..0dee670ce 100644 --- a/vendor/github.com/go-ole/go-ole/safearray_func.go +++ b/vendor/github.com/go-ole/go-ole/safearray_func.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/go-ole/go-ole/safearray_windows.go b/vendor/github.com/go-ole/go-ole/safearray_windows.go index 0a322f5da..0c1b3a10f 100644 --- a/vendor/github.com/go-ole/go-ole/safearray_windows.go +++ b/vendor/github.com/go-ole/go-ole/safearray_windows.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/safearrayconversion.go b/vendor/github.com/go-ole/go-ole/safearrayconversion.go index dde3e17e0..da737293d 100644 --- a/vendor/github.com/go-ole/go-ole/safearrayconversion.go +++ b/vendor/github.com/go-ole/go-ole/safearrayconversion.go @@ -84,7 +84,7 @@ func (sac *SafeArrayConversion) ToValueArray() (values []interface{}) { safeArrayGetElement(sac.Array, i, unsafe.Pointer(&v)) values[i] = v case VT_BSTR: - v, _ := safeArrayGetElementString(sac.Array, i) + v , _ := safeArrayGetElementString(sac.Array, i) values[i] = v case VT_VARIANT: var v VARIANT diff --git a/vendor/github.com/go-ole/go-ole/safearrayslices.go b/vendor/github.com/go-ole/go-ole/safearrayslices.go index 063dbbfec..a9fa885f1 100644 --- a/vendor/github.com/go-ole/go-ole/safearrayslices.go +++ b/vendor/github.com/go-ole/go-ole/safearrayslices.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/variables.go b/vendor/github.com/go-ole/go-ole/variables.go index 056f844d9..a6add1b00 100644 --- a/vendor/github.com/go-ole/go-ole/variables.go +++ b/vendor/github.com/go-ole/go-ole/variables.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_386.go b/vendor/github.com/go-ole/go-ole/variant_386.go index 2e3d3aa4a..e73736bf3 100644 --- a/vendor/github.com/go-ole/go-ole/variant_386.go +++ b/vendor/github.com/go-ole/go-ole/variant_386.go @@ -1,4 +1,3 @@ -//go:build 386 // +build 386 package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_amd64.go b/vendor/github.com/go-ole/go-ole/variant_amd64.go index b48c3ce6f..dccdde132 100644 --- a/vendor/github.com/go-ole/go-ole/variant_amd64.go +++ b/vendor/github.com/go-ole/go-ole/variant_amd64.go @@ -1,4 +1,3 @@ -//go:build amd64 // +build amd64 package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_arm.go b/vendor/github.com/go-ole/go-ole/variant_arm.go index 5c8d492d6..d47245444 100644 --- a/vendor/github.com/go-ole/go-ole/variant_arm.go +++ b/vendor/github.com/go-ole/go-ole/variant_arm.go @@ -1,4 +1,3 @@ -//go:build arm // +build arm package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_date_386.go b/vendor/github.com/go-ole/go-ole/variant_date_386.go index 8c3d3085f..1b970f63f 100644 --- a/vendor/github.com/go-ole/go-ole/variant_date_386.go +++ b/vendor/github.com/go-ole/go-ole/variant_date_386.go @@ -1,4 +1,3 @@ -//go:build windows && 386 // +build windows,386 package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_date_amd64.go b/vendor/github.com/go-ole/go-ole/variant_date_amd64.go index 8554d38d9..6952f1f0d 100644 --- a/vendor/github.com/go-ole/go-ole/variant_date_amd64.go +++ b/vendor/github.com/go-ole/go-ole/variant_date_amd64.go @@ -1,4 +1,3 @@ -//go:build windows && amd64 // +build windows,amd64 package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_date_arm.go b/vendor/github.com/go-ole/go-ole/variant_date_arm.go index 7afe38b89..09ec7b5cf 100644 --- a/vendor/github.com/go-ole/go-ole/variant_date_arm.go +++ b/vendor/github.com/go-ole/go-ole/variant_date_arm.go @@ -1,4 +1,3 @@ -//go:build windows && arm // +build windows,arm package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_ppc64le.go b/vendor/github.com/go-ole/go-ole/variant_ppc64le.go index 4ce060d8f..326427a7d 100644 --- a/vendor/github.com/go-ole/go-ole/variant_ppc64le.go +++ b/vendor/github.com/go-ole/go-ole/variant_ppc64le.go @@ -1,4 +1,3 @@ -//go:build ppc64le // +build ppc64le package ole diff --git a/vendor/github.com/go-ole/go-ole/variant_s390x.go b/vendor/github.com/go-ole/go-ole/variant_s390x.go index f83731098..9874ca66b 100644 --- a/vendor/github.com/go-ole/go-ole/variant_s390x.go +++ b/vendor/github.com/go-ole/go-ole/variant_s390x.go @@ -1,4 +1,3 @@ -//go:build s390x // +build s390x package ole diff --git a/vendor/github.com/go-ole/go-ole/winrt.go b/vendor/github.com/go-ole/go-ole/winrt.go index f503d685f..4e9eca732 100644 --- a/vendor/github.com/go-ole/go-ole/winrt.go +++ b/vendor/github.com/go-ole/go-ole/winrt.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package ole diff --git a/vendor/github.com/go-ole/go-ole/winrt_doc.go b/vendor/github.com/go-ole/go-ole/winrt_doc.go index a392928d2..52e6d74c9 100644 --- a/vendor/github.com/go-ole/go-ole/winrt_doc.go +++ b/vendor/github.com/go-ole/go-ole/winrt_doc.go @@ -1,4 +1,3 @@ -//go:build !windows // +build !windows package ole diff --git a/vendor/github.com/godbus/dbus/v5/conn_other.go b/vendor/github.com/godbus/dbus/v5/conn_other.go index 8d4e6bc41..90289ca85 100644 --- a/vendor/github.com/godbus/dbus/v5/conn_other.go +++ b/vendor/github.com/godbus/dbus/v5/conn_other.go @@ -1,4 +1,3 @@ -//go:build !darwin // +build !darwin package dbus diff --git a/vendor/github.com/godbus/dbus/v5/conn_unix.go b/vendor/github.com/godbus/dbus/v5/conn_unix.go index 1a0daa656..58aee7d2a 100644 --- a/vendor/github.com/godbus/dbus/v5/conn_unix.go +++ b/vendor/github.com/godbus/dbus/v5/conn_unix.go @@ -1,5 +1,4 @@ -//go:build !windows && !solaris && !darwin -// +build !windows,!solaris,!darwin +//+build !windows,!solaris,!darwin package dbus diff --git a/vendor/github.com/godbus/dbus/v5/conn_windows.go b/vendor/github.com/godbus/dbus/v5/conn_windows.go index 0515dd003..4291e4519 100644 --- a/vendor/github.com/godbus/dbus/v5/conn_windows.go +++ b/vendor/github.com/godbus/dbus/v5/conn_windows.go @@ -1,5 +1,4 @@ -//go:build windows -// +build windows +//+build windows package dbus diff --git a/vendor/github.com/godbus/dbus/v5/sequential_handler.go b/vendor/github.com/godbus/dbus/v5/sequential_handler.go index 886b5eb16..ef2fcdba1 100644 --- a/vendor/github.com/godbus/dbus/v5/sequential_handler.go +++ b/vendor/github.com/godbus/dbus/v5/sequential_handler.go @@ -93,7 +93,7 @@ func (scd *sequentialSignalChannelData) bufferSignals() { var queue []*Signal for { if len(queue) == 0 { - signal, ok := <-scd.in + signal, ok := <- scd.in if !ok { return } diff --git a/vendor/github.com/godbus/dbus/v5/transport_nonce_tcp.go b/vendor/github.com/godbus/dbus/v5/transport_nonce_tcp.go index a61a82084..697739efa 100644 --- a/vendor/github.com/godbus/dbus/v5/transport_nonce_tcp.go +++ b/vendor/github.com/godbus/dbus/v5/transport_nonce_tcp.go @@ -1,5 +1,4 @@ -//go:build !windows -// +build !windows +//+build !windows package dbus diff --git a/vendor/github.com/godbus/dbus/v5/transport_unix.go b/vendor/github.com/godbus/dbus/v5/transport_unix.go index ffccff0c3..0a8c712eb 100644 --- a/vendor/github.com/godbus/dbus/v5/transport_unix.go +++ b/vendor/github.com/godbus/dbus/v5/transport_unix.go @@ -1,5 +1,4 @@ -//go:build !windows && !solaris -// +build !windows,!solaris +//+build !windows,!solaris package dbus diff --git a/vendor/github.com/google/uuid/node_js.go b/vendor/github.com/google/uuid/node_js.go index f745d7017..b2a0bc871 100644 --- a/vendor/github.com/google/uuid/node_js.go +++ b/vendor/github.com/google/uuid/node_js.go @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build js // +build js package uuid diff --git a/vendor/github.com/google/uuid/node_net.go b/vendor/github.com/google/uuid/node_net.go index e91358f7d..0cbbcddbd 100644 --- a/vendor/github.com/google/uuid/node_net.go +++ b/vendor/github.com/google/uuid/node_net.go @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build !js // +build !js package uuid diff --git a/vendor/github.com/gorilla/securecookie/fuzz.go b/vendor/github.com/gorilla/securecookie/fuzz.go index b8658e0ae..e4d0534e4 100644 --- a/vendor/github.com/gorilla/securecookie/fuzz.go +++ b/vendor/github.com/gorilla/securecookie/fuzz.go @@ -1,4 +1,3 @@ -//go:build gofuzz // +build gofuzz package securecookie diff --git a/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go b/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go deleted file mode 100644 index c78a98fdc..000000000 --- a/vendor/github.com/inconshreveable/mousetrap/trap_windows_1.4.go +++ /dev/null @@ -1,46 +0,0 @@ -//go:build windows && go1.4 -// +build windows,go1.4 - -package mousetrap - -import ( - "os" - "syscall" - "unsafe" -) - -func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) { - snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0) - if err != nil { - return nil, err - } - defer syscall.CloseHandle(snapshot) - var procEntry syscall.ProcessEntry32 - procEntry.Size = uint32(unsafe.Sizeof(procEntry)) - if err = syscall.Process32First(snapshot, &procEntry); err != nil { - return nil, err - } - for { - if procEntry.ProcessID == uint32(pid) { - return &procEntry, nil - } - err = syscall.Process32Next(snapshot, &procEntry) - if err != nil { - return nil, err - } - } -} - -// StartedByExplorer returns true if the program was invoked by the user double-clicking -// on the executable from explorer.exe -// -// It is conservative and returns false if any of the internal calls fail. -// It does not guarantee that the program was run from a terminal. It only can tell you -// whether it was launched from explorer.exe -func StartedByExplorer() bool { - pe, err := getProcessEntry(os.Getppid()) - if err != nil { - return false - } - return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:]) -} diff --git a/vendor/github.com/james-barrow/golang-ipc/README.md b/vendor/github.com/james-barrow/golang-ipc/README.md index fd93e5fd2..793751d46 100644 --- a/vendor/github.com/james-barrow/golang-ipc/README.md +++ b/vendor/github.com/james-barrow/golang-ipc/README.md @@ -13,9 +13,7 @@ As well as using this library just for go processes it was also designed to work #### NodeJs -I currently use this library to comunicate between a ElectronJS GUI and a go program. - -Below is a link to the nodeJS client library: +I currently use this library to comunicate between a ElectronJs GUI and a go program. https://github.com/james-barrow/node-ipc-client @@ -29,97 +27,59 @@ Create a server with the default configuation and start listening for the client ```go - s, err := ipc.StartServer("", nil) + sc, err := ipc.StartServer("", nil) if err != nil { log.Println(err) return } ``` + Create a client and connect to the server: ```go - c, err := ipc.StartClient("", nil) + cc, err := ipc.StartClient("", nil) if err != nil { log.Println(err) return } ``` - -### Read messages - -Read each message sent: - -```go - - for { - - // message, err := s.Read() server - message, err := c.Read() // client - - if err == nil { - // handle error - } - - // do something with the received messages - } - -``` - -All received messages are formated into the type Message - -```go - -type Message struct { - Err error // details of any error - MsgType int // 0 = reserved , -1 is an internal message (disconnection or error etc), all messages recieved will be > 0 - Data []byte // message data received - Status string // the status of the connection -} - -``` - -### Write a message - - -```go - - //err := s.Write(1, []byte("", config) + ``` ### Unix Socket Permissions Under most configurations, a socket created by a user will by default not be writable by another user, making it impossible for the client and server to communicate if being run by separate users. - The permission mask can be dropped during socket creation by passing a custom configuration to the server start function. **This will make the socket writable for any user.** + The permission mask can be dropped during socket creation by passing custom configuration to the server start function. **This will make the socket writable by any user.** ```go - UnmaskPermissions: true + + config := &ipc.ServerConfig{UnmaskPermissions: true} + sc, err := ipc.StartServer("", config) + ``` Note: Tested on Linux, not tested on Mac, not implemented on Windows. - ## Testing + ### Testing The package has been tested on Mac, Windows and Linux and has extensive test coverage. -## Licence +### Licence MIT diff --git a/vendor/github.com/james-barrow/golang-ipc/client_all.go b/vendor/github.com/james-barrow/golang-ipc/client_all.go index 0a89de78e..d76c14735 100644 --- a/vendor/github.com/james-barrow/golang-ipc/client_all.go +++ b/vendor/github.com/james-barrow/golang-ipc/client_all.go @@ -4,13 +4,15 @@ import ( "bufio" "errors" "io" - "log" "strings" "time" ) // StartClient - start the ipc client. +// // ipcName = is the name of the unix socket or named pipe that the client will try and connect to. +// timeout = number of seconds before the socket/pipe times out trying to connect/re-cconnect - if -1 or 0 it never times out. +// retryTimer = number of seconds before the client tries to connect again. func StartClient(ipcName string, config *ClientConfig) (*Client, error) { err := checkIpcName(ipcName) @@ -22,14 +24,14 @@ func StartClient(ipcName string, config *ClientConfig) (*Client, error) { cc := &Client{ Name: ipcName, status: NotConnected, - received: make(chan *Message), + recieved: make(chan *Message), toWrite: make(chan *Message), } if config == nil { cc.timeout = 0 - cc.retryTimer = time.Duration(20) + cc.retryTimer = time.Duration(1) cc.encryptionReq = true } else { @@ -56,32 +58,34 @@ func StartClient(ipcName string, config *ClientConfig) (*Client, error) { go startClient(cc) return cc, nil + } -func startClient(c *Client) { +func startClient(cc *Client) { - c.status = Connecting - c.received <- &Message{Status: c.status.String(), MsgType: -1} + cc.status = Connecting + cc.recieved <- &Message{Status: cc.status.String(), MsgType: -1} - err := c.dial() + err := cc.dial() if err != nil { - c.received <- &Message{Err: err, MsgType: -1} + cc.recieved <- &Message{err: err, MsgType: -2} return } - c.status = Connected - c.received <- &Message{Status: c.status.String(), MsgType: -1} + cc.status = Connected + cc.recieved <- &Message{Status: cc.status.String(), MsgType: -1} + + go cc.read() + go cc.write() - go c.read() - go c.write() } -func (c *Client) read() { +func (cc *Client) read() { bLen := make([]byte, 4) for { - res := c.readData(bLen) + res := cc.readData(bLen) if !res { break } @@ -90,13 +94,13 @@ func (c *Client) read() { msgRecvd := make([]byte, mLen) - res = c.readData(msgRecvd) + res = cc.readData(msgRecvd) if !res { break } - if c.encryption { - msgFinal, err := decrypt(*c.enc.cipher, msgRecvd) + if cc.encryption { + msgFinal, err := decrypt(*cc.enc.cipher, msgRecvd) if err != nil { break } @@ -104,7 +108,7 @@ func (c *Client) read() { if bytesToInt(msgFinal[:4]) == 0 { // type 0 = control message } else { - c.received <- &Message{Data: msgFinal[4:], MsgType: bytesToInt(msgFinal[:4])} + cc.recieved <- &Message{Data: msgFinal[4:], MsgType: bytesToInt(msgFinal[:4])} } } else { @@ -112,29 +116,30 @@ func (c *Client) read() { if bytesToInt(msgRecvd[:4]) == 0 { // type 0 = control message } else { - c.received <- &Message{Data: msgRecvd[4:], MsgType: bytesToInt(msgRecvd[:4])} + cc.recieved <- &Message{Data: msgRecvd[4:], MsgType: bytesToInt(msgRecvd[:4])} } } } } -func (c *Client) readData(buff []byte) bool { +func (cc *Client) readData(buff []byte) bool { - _, err := io.ReadFull(c.conn, buff) + _, err := io.ReadFull(cc.conn, buff) + //_, err := cc.conn.Read(buff) if err != nil { if strings.Contains(err.Error(), "EOF") { // the connection has been closed by the client. - c.conn.Close() + cc.conn.Close() - if c.status != Closing || c.status == Closed { - go c.reconnect() + if cc.status != Closing || cc.status == Closed { + go cc.reconnect() } return false } - if c.status == Closing { - c.status = Closed - c.received <- &Message{Status: c.status.String(), MsgType: -1} - c.received <- &Message{Err: errors.New("client has closed the connection"), MsgType: -2} + if cc.status == Closing { + cc.status = Closed + cc.recieved <- &Message{Status: cc.status.String(), MsgType: -1} + cc.recieved <- &Message{err: errors.New("Client has closed the connection"), MsgType: -2} return false } @@ -150,44 +155,44 @@ func (c *Client) readData(buff []byte) bool { func (c *Client) reconnect() { c.status = ReConnecting - c.received <- &Message{Status: c.status.String(), MsgType: -1} + c.recieved <- &Message{Status: c.status.String(), MsgType: -1} err := c.dial() // connect to the pipe if err != nil { - if err.Error() == "timed out trying to connect" { + if err.Error() == "Timed out trying to connect" { c.status = Timeout - c.received <- &Message{Status: c.status.String(), MsgType: -1} - c.received <- &Message{Err: errors.New("timed out trying to re-connect"), MsgType: -1} + c.recieved <- &Message{Status: c.status.String(), MsgType: -1} + c.recieved <- &Message{err: errors.New("timed out trying to re-connect"), MsgType: -2} } return } c.status = Connected - c.received <- &Message{Status: c.status.String(), MsgType: -1} + c.recieved <- &Message{Status: c.status.String(), MsgType: -1} go c.read() } -// Read - blocking function that receices messages -// if MsgType is a negative number its an internal message +// Read - blocking function that waits until an non multipart message is recieved +// returns the message type, data and any error. func (c *Client) Read() (*Message, error) { - m, ok := (<-c.received) + m, ok := (<-c.recieved) if !ok { - return nil, errors.New("the received channel has been closed") + return nil, errors.New("the recieve channel has been closed") } - if m.Err != nil { - close(c.received) + if m.err != nil { + close(c.recieved) close(c.toWrite) - return nil, m.Err + return nil, m.err } return m, nil } -// Write - writes a message to the ipc connection. +// Write - writes a non multipart message to the ipc connection. // msgType - denotes the type of data being sent. 0 is a reserved type for internal messages and errors. func (c *Client) Write(msgType int, message []byte) error { @@ -215,7 +220,7 @@ func (c *Client) write() { m, ok := <-c.toWrite - if !ok { + if !ok{ break } @@ -227,8 +232,7 @@ func (c *Client) write() { toSend = append(toSend, m.Data...) toSendEnc, err := encrypt(*c.enc.cipher, toSend) if err != nil { - log.Println("error encrypting data", err) - continue + //return err } toSend = toSendEnc } else { @@ -242,8 +246,7 @@ func (c *Client) write() { err := writer.Flush() if err != nil { - log.Println("error flushing data", err) - continue + //return err } } diff --git a/vendor/github.com/james-barrow/golang-ipc/connect_other.go b/vendor/github.com/james-barrow/golang-ipc/connect_other.go index cf2473f42..eff12a9dd 100644 --- a/vendor/github.com/james-barrow/golang-ipc/connect_other.go +++ b/vendor/github.com/james-barrow/golang-ipc/connect_other.go @@ -1,4 +1,3 @@ -//go:build linux || darwin // +build linux darwin package ipc @@ -13,23 +12,23 @@ import ( ) // Server create a unix socket and start listening connections - for unix and linux -func (s *Server) run() error { +func (sc *Server) run() error { base := "/tmp/" sock := ".sock" - if err := os.RemoveAll(base + s.name + sock); err != nil { + if err := os.RemoveAll(base + sc.name + sock); err != nil { return err } var oldUmask int - if s.unMask { + if sc.unMask { oldUmask = syscall.Umask(0) } - listen, err := net.Listen("unix", base+s.name+sock) + listen, err := net.Listen("unix", base+sc.name+sock) - if s.unMask { + if sc.unMask { syscall.Umask(oldUmask) } @@ -37,18 +36,25 @@ func (s *Server) run() error { return err } - s.listen = listen + sc.listen = listen - go s.acceptLoop() + sc.status = Listening + sc.recieved <- &Message{Status: sc.status.String(), MsgType: -1} + sc.connChannel = make(chan bool) - s.status = Listening + go sc.acceptLoop() + + err = sc.connectionTimer() + if err != nil { + return err + } return nil } // Client connect to the unix socket created by the server - for unix and linux -func (c *Client) dial() error { +func (cc *Client) dial() error { base := "/tmp/" sock := ".sock" @@ -56,16 +62,14 @@ func (c *Client) dial() error { startTime := time.Now() for { - - if c.timeout != 0 { - - if time.Since(startTime).Seconds() > c.timeout { - c.status = Closed + if cc.timeout != 0 { + if time.Now().Sub(startTime).Seconds() > cc.timeout { + cc.status = Closed return errors.New("timed out trying to connect") } } - conn, err := net.Dial("unix", base+c.Name+sock) + conn, err := net.Dial("unix", base+cc.Name+sock) if err != nil { if strings.Contains(err.Error(), "connect: no such file or directory") { @@ -73,14 +77,14 @@ func (c *Client) dial() error { } else if strings.Contains(err.Error(), "connect: connection refused") { } else { - c.received <- &Message{Err: err, MsgType: -1} + cc.recieved <- &Message{err: err, MsgType: -2} } } else { - c.conn = conn + cc.conn = conn - err = c.handshake() + err = cc.handshake() if err != nil { return err } @@ -88,7 +92,7 @@ func (c *Client) dial() error { return nil } - time.Sleep(c.retryTimer * time.Second) + time.Sleep(cc.retryTimer * time.Second) } diff --git a/vendor/github.com/james-barrow/golang-ipc/connect_windows.go b/vendor/github.com/james-barrow/golang-ipc/connect_windows.go index f206b5dad..41c7e4888 100644 --- a/vendor/github.com/james-barrow/golang-ipc/connect_windows.go +++ b/vendor/github.com/james-barrow/golang-ipc/connect_windows.go @@ -11,27 +11,28 @@ import ( // Server function // Create the named pipe (if it doesn't already exist) and start listening for a client to connect. // when a client connects and connection is accepted the read function is called on a go routine. -func (s *Server) run() error { +func (sc *Server) run() error { var pipeBase = `\\.\pipe\` - var config *winio.PipeConfig - - if s.unMask { - config = &winio.PipeConfig{SecurityDescriptor: "D:P(A;;GA;;;AU)"} - } - - listen, err := winio.ListenPipe(pipeBase+s.name, config) + listen, err := winio.ListenPipe(pipeBase+sc.name, nil) if err != nil { return err } - s.listen = listen + sc.listen = listen + + sc.status = Listening - s.status = Listening + sc.connChannel = make(chan bool) - go s.acceptLoop() + go sc.acceptLoop() + + err2 := sc.connectionTimer() + if err2 != nil { + return err2 + } return nil @@ -39,23 +40,23 @@ func (s *Server) run() error { // Client function // dial - attempts to connect to a named pipe created by the server -func (c *Client) dial() error { +func (cc *Client) dial() error { var pipeBase = `\\.\pipe\` startTime := time.Now() for { - if c.timeout != 0 { - if time.Since(startTime).Seconds() > c.timeout { - c.status = Closed - return errors.New("timed out trying to connect") + if cc.timeout != 0 { + if time.Now().Sub(startTime).Seconds() > cc.timeout { + cc.status = Closed + return errors.New("Timed out trying to connect") } } - pn, err := winio.DialPipe(pipeBase+c.Name, nil) + pn, err := winio.DialPipe(pipeBase+cc.Name, nil) if err != nil { - if strings.Contains(err.Error(), "the system cannot find the file specified.") == true { + if strings.Contains(err.Error(), "The system cannot find the file specified.") == true { } else { return err @@ -63,16 +64,16 @@ func (c *Client) dial() error { } else { - c.conn = pn + cc.conn = pn - err = c.handshake() + err = cc.handshake() if err != nil { return err } return nil } - time.Sleep(c.retryTimer * time.Second) + time.Sleep(cc.retryTimer * time.Second) } } diff --git a/vendor/github.com/james-barrow/golang-ipc/encryption.go b/vendor/github.com/james-barrow/golang-ipc/encryption.go index 73af1b3c7..705b50b85 100644 --- a/vendor/github.com/james-barrow/golang-ipc/encryption.go +++ b/vendor/github.com/james-barrow/golang-ipc/encryption.go @@ -27,7 +27,7 @@ func (sc *Server) keyExchange() ([32]byte, error) { return shared, err } - // received clients public key + // recieve clients public key pubRecvd, err := recvPublic(sc.conn) if err != nil { return shared, err @@ -50,7 +50,7 @@ func (cc *Client) keyExchange() ([32]byte, error) { return shared, err } - // received servers public key + // recieve servers public key pubRecvd, err := recvPublic(cc.conn) if err != nil { return shared, err @@ -103,20 +103,20 @@ func sendPublic(conn net.Conn, pub *ecdsa.PublicKey) error { func recvPublic(conn net.Conn) (*ecdsa.PublicKey, error) { - buff := make([]byte, 98) + buff := make([]byte, 300) i, err := conn.Read(buff) if err != nil { - return nil, errors.New("didn't received public key") + return nil, errors.New("didn't recieve public key") } if i != 97 { - return nil, errors.New("public key received isn't valid length") + return nil, errors.New("public key recieved isn't valid length") } recvdPub := bytesToPublicKey(buff[:i]) if !recvdPub.IsOnCurve(recvdPub.X, recvdPub.Y) { - return nil, errors.New("didn't received valid public key") + return nil, errors.New("didn't recieve valid public key") } return recvdPub, nil @@ -145,6 +145,7 @@ func bytesToPublicKey(recvdPub []byte) *ecdsa.PublicKey { func createCipher(shared [32]byte) (*cipher.AEAD, error) { b, err := aes.NewCipher(shared[:]) + if err != nil { return nil, err } @@ -161,9 +162,11 @@ func encrypt(g cipher.AEAD, data []byte) ([]byte, error) { nonce := make([]byte, g.NonceSize()) - _, err := io.ReadFull(rand.Reader, nonce) + if _, err := io.ReadFull(rand.Reader, nonce); err != nil { + return nil, err + } - return g.Seal(nonce, nonce, data, nil), err + return g.Seal(nonce, nonce, data, nil), nil } diff --git a/vendor/github.com/james-barrow/golang-ipc/handshake.go b/vendor/github.com/james-barrow/golang-ipc/handshake.go index 3ac65e5c7..f4f9ec629 100644 --- a/vendor/github.com/james-barrow/golang-ipc/handshake.go +++ b/vendor/github.com/james-barrow/golang-ipc/handshake.go @@ -52,7 +52,7 @@ func (sc *Server) one() error { recv := make([]byte, 1) _, err = sc.conn.Read(recv) if err != nil { - return errors.New("failed to received handshake reply") + return errors.New("failed to recieve handshake reply") } switch result := recv[0]; result { @@ -124,14 +124,14 @@ func (sc *Server) msgLength() error { _, err = sc.conn.Read(reply) if err != nil { - return errors.New("did not received message length reply") + return errors.New("did not recieve message length reply") } return nil } -// 1st message received by the client +// 1st message recieved by the client func (cc *Client) handshake() error { err := cc.one() @@ -160,7 +160,7 @@ func (cc *Client) one() error { recv := make([]byte, 2) _, err := cc.conn.Read(recv) if err != nil { - return errors.New("failed to received handshake message") + return errors.New("failed to recieve handshake message") } if recv[0] != version { @@ -212,7 +212,7 @@ func (cc *Client) msgLength() error { _, err := cc.conn.Read(buff) if err != nil { - return errors.New("failed to received max message length 1") + return errors.New("failed to recieve max message length 1") } var msgLen uint32 @@ -222,13 +222,13 @@ func (cc *Client) msgLength() error { _, err = cc.conn.Read(buff) if err != nil { - return errors.New("failed to received max message length 2") + return errors.New("failed to recieve max message length 2") } var buff2 []byte if cc.encryption { buff2, err = decrypt(*cc.enc.cipher, buff) if err != nil { - return errors.New("failed to received max message length 3") + return errors.New("failed to recieve max message length 3") } } else { diff --git a/vendor/github.com/james-barrow/golang-ipc/server_all.go b/vendor/github.com/james-barrow/golang-ipc/server_all.go index 4f7a61b54..3690690cd 100644 --- a/vendor/github.com/james-barrow/golang-ipc/server_all.go +++ b/vendor/github.com/james-barrow/golang-ipc/server_all.go @@ -4,13 +4,13 @@ import ( "bufio" "errors" "io" - "log" "time" ) // StartServer - starts the ipc server. // -// ipcName - is the name of the unix socket or named pipe that will be created, the client needs to use the same name +// ipcName = is the name of the unix socket or named pipe that will be created. +// timeout = number of seconds before the socket/pipe times out waiting for a connection/re-cconnection - if -1 or 0 it never times out. func StartServer(ipcName string, config *ServerConfig) (*Server, error) { err := checkIpcName(ipcName) @@ -18,71 +18,84 @@ func StartServer(ipcName string, config *ServerConfig) (*Server, error) { return nil, err } - s := &Server{ + sc := &Server{ name: ipcName, status: NotConnected, - received: make(chan *Message), + recieved: make(chan *Message), toWrite: make(chan *Message), } if config == nil { - s.timeout = 0 - s.maxMsgSize = maxMsgSize - s.encryption = true - s.unMask = false + sc.timeout = 0 + sc.maxMsgSize = maxMsgSize + sc.encryption = true + sc.unMask = false } else { + if config.Timeout < 0 { + sc.timeout = 0 + } else { + sc.timeout = config.Timeout + } + if config.MaxMsgSize < 1024 { - s.maxMsgSize = maxMsgSize + sc.maxMsgSize = maxMsgSize } else { - s.maxMsgSize = config.MaxMsgSize + sc.maxMsgSize = config.MaxMsgSize } if !config.Encryption { - s.encryption = false + sc.encryption = false } else { - s.encryption = true + sc.encryption = true } if config.UnmaskPermissions { - s.unMask = true + sc.unMask = true } else { - s.unMask = false + sc.unMask = false } } - err = s.run() + go startServer(sc) - return s, err + return sc, err } -func (s *Server) acceptLoop() { +func startServer(sc *Server) { + + err := sc.run() + if err != nil { + sc.recieved <- &Message{err: err, MsgType: -2} + } +} +func (sc *Server) acceptLoop() { for { - conn, err := s.listen.Accept() + conn, err := sc.listen.Accept() if err != nil { break } - if s.status == Listening || s.status == Disconnected { + if sc.status == Listening || sc.status == ReConnecting { - s.conn = conn + sc.conn = conn - err2 := s.handshake() + err2 := sc.handshake() if err2 != nil { - s.received <- &Message{Err: err2, MsgType: -1} - s.status = Error - s.listen.Close() - s.conn.Close() + sc.recieved <- &Message{err: err2, MsgType: -2} + sc.status = Error + sc.listen.Close() + sc.conn.Close() } else { + go sc.read() + go sc.write() - go s.read() - go s.write() - - s.status = Connected - s.received <- &Message{Status: s.status.String(), MsgType: -1} + sc.status = Connected + sc.recieved <- &Message{Status: sc.status.String(), MsgType: -1} + sc.connChannel <- true } } @@ -91,16 +104,46 @@ func (s *Server) acceptLoop() { } -func (s *Server) read() { +func (sc *Server) connectionTimer() error { + + if sc.timeout != 0 { + + timeout := make(chan bool) + + go func() { + time.Sleep(sc.timeout * time.Second) + timeout <- true + }() + + select { + + case <-sc.connChannel: + return nil + case <-timeout: + sc.listen.Close() + return errors.New("timed out waiting for client to connect") + } + } + + //select { + + //case <-sc.connChannel: + // return nil + //} + + <-sc.connChannel + return nil + +} + +func (sc *Server) read() { bLen := make([]byte, 4) for { - res := s.readData(bLen) + res := sc.readData(bLen) if !res { - s.conn.Close() - break } @@ -108,111 +151,124 @@ func (s *Server) read() { msgRecvd := make([]byte, mLen) - res = s.readData(msgRecvd) + res = sc.readData(msgRecvd) if !res { - s.conn.Close() - break } - if s.encryption { - msgFinal, err := decrypt(*s.enc.cipher, msgRecvd) + if sc.encryption { + msgFinal, err := decrypt(*sc.enc.cipher, msgRecvd) if err != nil { - s.received <- &Message{Err: err, MsgType: -1} + sc.recieved <- &Message{err: err, MsgType: -2} continue } if bytesToInt(msgFinal[:4]) == 0 { // type 0 = control message } else { - s.received <- &Message{Data: msgFinal[4:], MsgType: bytesToInt(msgFinal[:4])} + sc.recieved <- &Message{Data: msgFinal[4:], MsgType: bytesToInt(msgFinal[:4])} } } else { if bytesToInt(msgRecvd[:4]) == 0 { // type 0 = control message } else { - s.received <- &Message{Data: msgRecvd[4:], MsgType: bytesToInt(msgRecvd[:4])} + sc.recieved <- &Message{Data: msgRecvd[4:], MsgType: bytesToInt(msgRecvd[:4])} } } } - } -func (s *Server) readData(buff []byte) bool { +func (sc *Server) readData(buff []byte) bool { - _, err := io.ReadFull(s.conn, buff) + _, err := io.ReadFull(sc.conn, buff) + //_, err := sc.conn.Read(buff) if err != nil { - if s.status == Closing { + if sc.status == Closing { - s.status = Closed - s.received <- &Message{Status: s.status.String(), MsgType: -1} - s.received <- &Message{Err: errors.New("server has closed the connection"), MsgType: -1} + sc.status = Closed + sc.recieved <- &Message{Status: sc.status.String(), MsgType: -1} + sc.recieved <- &Message{err: errors.New("Server has closed the connection"), MsgType: -2} return false } - if err == io.EOF { - - s.status = Disconnected - s.received <- &Message{Status: s.status.String(), MsgType: -1} - return false - } + go sc.reConnect() + return false } return true + } -// Read - blocking function, reads each message recieved -// if MsgType is a negative number its an internal message -func (s *Server) Read() (*Message, error) { +func (sc *Server) reConnect() { + + sc.status = ReConnecting + sc.recieved <- &Message{Status: sc.status.String(), MsgType: -1} + + err := sc.connectionTimer() + if err != nil { + sc.status = Timeout + sc.recieved <- &Message{Status: sc.status.String(), MsgType: -1} + + sc.recieved <- &Message{err: err, MsgType: -2} + + } - m, ok := (<-s.received) +} + +// Read - blocking function that waits until an non multipart message is recieved + +func (sc *Server) Read() (*Message, error) { + + m, ok := (<-sc.recieved) if !ok { - return nil, errors.New("the received channel has been closed") + return nil, errors.New("the recieve channel has been closed") } - if m.Err != nil { - //close(s.received) - //close(s.toWrite) - return nil, m.Err + if m.err != nil { + close(sc.recieved) + close(sc.toWrite) + return nil, m.err } return m, nil + } -// Write - writes a message to the ipc connection +// Write - writes a non multipart message to the ipc connection. // msgType - denotes the type of data being sent. 0 is a reserved type for internal messages and errors. -func (s *Server) Write(msgType int, message []byte) error { +func (sc *Server) Write(msgType int, message []byte) error { if msgType == 0 { - return errors.New("message type 0 is reserved") + return errors.New("Message type 0 is reserved") } mlen := len(message) - if mlen > s.maxMsgSize { - return errors.New("message exceeds maximum message length") + if mlen > sc.maxMsgSize { + return errors.New("Message exceeds maximum message length") } - if s.status == Connected { + if sc.status == Connected { - s.toWrite <- &Message{MsgType: msgType, Data: message} + sc.toWrite <- &Message{MsgType: msgType, Data: message} } else { - return errors.New(s.status.String()) + return errors.New(sc.status.String()) } return nil + } -func (s *Server) write() { +func (sc *Server) write() { for { - m, ok := <-s.toWrite + m, ok := <-sc.toWrite if !ok { break @@ -220,16 +276,14 @@ func (s *Server) write() { toSend := intToBytes(m.MsgType) - writer := bufio.NewWriter(s.conn) + writer := bufio.NewWriter(sc.conn) - if s.encryption { + if sc.encryption { toSend = append(toSend, m.Data...) - toSendEnc, err := encrypt(*s.enc.cipher, toSend) + toSendEnc, err := encrypt(*sc.enc.cipher, toSend) if err != nil { - log.Println("error encrypting data", err) - continue + //return err } - toSend = toSendEnc } else { @@ -242,44 +296,42 @@ func (s *Server) write() { err := writer.Flush() if err != nil { - log.Println("error flushing data", err) - continue + //return err } time.Sleep(2 * time.Millisecond) } -} +} // getStatus - get the current status of the connection -func (s *Server) getStatus() Status { +func (sc *Server) getStatus() Status { - return s.status + return sc.status } - // StatusCode - returns the current connection status -func (s *Server) StatusCode() Status { - return s.status +func (sc *Server) StatusCode() Status { + return sc.status } // Status - returns the current connection status as a string -func (s *Server) Status() string { +func (sc *Server) Status() string { - return s.status.String() + return sc.status.String() } // Close - closes the connection -func (s *Server) Close() { +func (sc *Server) Close() { - s.status = Closing + sc.status = Closing - if s.listen != nil { - s.listen.Close() + if sc.listen != nil { + sc.listen.Close() } - if s.conn != nil { - s.conn.Close() + if sc.conn != nil { + sc.conn.Close() } } diff --git a/vendor/github.com/james-barrow/golang-ipc/shared.go b/vendor/github.com/james-barrow/golang-ipc/shared.go index 56811028f..f91033026 100644 --- a/vendor/github.com/james-barrow/golang-ipc/shared.go +++ b/vendor/github.com/james-barrow/golang-ipc/shared.go @@ -2,7 +2,7 @@ package ipc import "errors" -// returns the status of the connection as a string +// returns the status of the connection as a string func (status *Status) String() string { switch *status { @@ -17,15 +17,13 @@ func (status *Status) String() string { case Closing: return "Closing" case ReConnecting: - return "Reconnecting" + return "Re-connecting" case Timeout: return "Timeout" case Closed: return "Closed" case Error: return "Error" - case Disconnected: - return "Disconnected" default: return "Status not found" } @@ -39,4 +37,5 @@ func checkIpcName(ipcName string) error { } return nil + } diff --git a/vendor/github.com/james-barrow/golang-ipc/types.go b/vendor/github.com/james-barrow/golang-ipc/types.go index 572651f4f..563353338 100644 --- a/vendor/github.com/james-barrow/golang-ipc/types.go +++ b/vendor/github.com/james-barrow/golang-ipc/types.go @@ -8,17 +8,18 @@ import ( // Server - holds the details of the server connection & config. type Server struct { - name string - listen net.Listener - conn net.Conn - status Status - received chan (*Message) - toWrite chan (*Message) - timeout time.Duration - encryption bool - maxMsgSize int - enc *encryption - unMask bool + name string + listen net.Listener + conn net.Conn + status Status + recieved chan (*Message) + connChannel chan bool + toWrite chan (*Message) + timeout time.Duration + encryption bool + maxMsgSize int + enc *encryption + unMask bool } // Client - holds the details of the client connection and config. @@ -28,7 +29,7 @@ type Client struct { status Status timeout float64 // retryTimer time.Duration // number of seconds before trying to connect again - received chan (*Message) + recieved chan (*Message) toWrite chan (*Message) encryption bool encryptionReq bool @@ -36,12 +37,12 @@ type Client struct { enc *encryption } -// Message - contains the received message +// Message - contains the recieved message type Message struct { - Err error // details of any error - MsgType int // 0 = reserved , -1 is an internal message (disconnection or error etc), all messages recieved will be > 0 - Data []byte // message data received - Status string // the status of the connection + err error // details of any error + MsgType int // type of message sent - 0 is reserved + Data []byte // message data recieved + Status string } // Status - Status of the connection @@ -52,27 +53,26 @@ const ( // NotConnected - 0 NotConnected Status = iota // Listening - 1 - Listening + Listening Status = iota // Connecting - 2 - Connecting + Connecting Status = iota // Connected - 3 - Connected + Connected Status = iota // ReConnecting - 4 - ReConnecting + ReConnecting Status = iota // Closed - 5 - Closed + Closed Status = iota // Closing - 6 - Closing + Closing Status = iota // Error - 7 - Error + Error Status = iota // Timeout - 8 - Timeout - // Disconnected - 9 - Disconnected + Timeout Status = iota ) // ServerConfig - used to pass configuation overrides to ServerStart() type ServerConfig struct { + Timeout time.Duration MaxMsgSize int Encryption bool UnmaskPermissions bool diff --git a/vendor/github.com/json-iterator/go/any.go b/vendor/github.com/json-iterator/go/any.go index 4b7e1cf5c..f6b8aeab0 100644 --- a/vendor/github.com/json-iterator/go/any.go +++ b/vendor/github.com/json-iterator/go/any.go @@ -3,12 +3,11 @@ package jsoniter import ( "errors" "fmt" + "github.com/modern-go/reflect2" "io" "reflect" "strconv" "unsafe" - - "github.com/modern-go/reflect2" ) // Any generic object representation. diff --git a/vendor/github.com/json-iterator/go/iter_skip_sloppy.go b/vendor/github.com/json-iterator/go/iter_skip_sloppy.go index 3d993f277..9303de41e 100644 --- a/vendor/github.com/json-iterator/go/iter_skip_sloppy.go +++ b/vendor/github.com/json-iterator/go/iter_skip_sloppy.go @@ -1,5 +1,4 @@ -//go:build jsoniter_sloppy -// +build jsoniter_sloppy +//+build jsoniter_sloppy package jsoniter diff --git a/vendor/github.com/json-iterator/go/iter_skip_strict.go b/vendor/github.com/json-iterator/go/iter_skip_strict.go index f1ad6591b..6cf66d043 100644 --- a/vendor/github.com/json-iterator/go/iter_skip_strict.go +++ b/vendor/github.com/json-iterator/go/iter_skip_strict.go @@ -1,5 +1,4 @@ -//go:build !jsoniter_sloppy -// +build !jsoniter_sloppy +//+build !jsoniter_sloppy package jsoniter diff --git a/vendor/github.com/json-iterator/go/reflect_array.go b/vendor/github.com/json-iterator/go/reflect_array.go index 7eb5b1dc9..13a0b7b08 100644 --- a/vendor/github.com/json-iterator/go/reflect_array.go +++ b/vendor/github.com/json-iterator/go/reflect_array.go @@ -2,10 +2,9 @@ package jsoniter import ( "fmt" + "github.com/modern-go/reflect2" "io" "unsafe" - - "github.com/modern-go/reflect2" ) func decoderOfArray(ctx *ctx, typ reflect2.Type) ValDecoder { diff --git a/vendor/github.com/json-iterator/go/reflect_dynamic.go b/vendor/github.com/json-iterator/go/reflect_dynamic.go index 71a0fe273..8b6bc8b43 100644 --- a/vendor/github.com/json-iterator/go/reflect_dynamic.go +++ b/vendor/github.com/json-iterator/go/reflect_dynamic.go @@ -1,10 +1,9 @@ package jsoniter import ( + "github.com/modern-go/reflect2" "reflect" "unsafe" - - "github.com/modern-go/reflect2" ) type dynamicEncoder struct { diff --git a/vendor/github.com/json-iterator/go/reflect_extension.go b/vendor/github.com/json-iterator/go/reflect_extension.go index a820f10ca..74a97bfe5 100644 --- a/vendor/github.com/json-iterator/go/reflect_extension.go +++ b/vendor/github.com/json-iterator/go/reflect_extension.go @@ -2,13 +2,12 @@ package jsoniter import ( "fmt" + "github.com/modern-go/reflect2" "reflect" "sort" "strings" "unicode" "unsafe" - - "github.com/modern-go/reflect2" ) var typeDecoders = map[string]ValDecoder{} diff --git a/vendor/github.com/json-iterator/go/reflect_json_number.go b/vendor/github.com/json-iterator/go/reflect_json_number.go index 52e11bf3f..98d45c1ec 100644 --- a/vendor/github.com/json-iterator/go/reflect_json_number.go +++ b/vendor/github.com/json-iterator/go/reflect_json_number.go @@ -2,10 +2,9 @@ package jsoniter import ( "encoding/json" + "github.com/modern-go/reflect2" "strconv" "unsafe" - - "github.com/modern-go/reflect2" ) type Number string diff --git a/vendor/github.com/json-iterator/go/reflect_json_raw_message.go b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go index 521e38a89..eba434f2f 100644 --- a/vendor/github.com/json-iterator/go/reflect_json_raw_message.go +++ b/vendor/github.com/json-iterator/go/reflect_json_raw_message.go @@ -2,9 +2,8 @@ package jsoniter import ( "encoding/json" - "unsafe" - "github.com/modern-go/reflect2" + "unsafe" ) var jsonRawMessageType = reflect2.TypeOfPtr((*json.RawMessage)(nil)).Elem() diff --git a/vendor/github.com/json-iterator/go/reflect_map.go b/vendor/github.com/json-iterator/go/reflect_map.go index 696194bde..582967130 100644 --- a/vendor/github.com/json-iterator/go/reflect_map.go +++ b/vendor/github.com/json-iterator/go/reflect_map.go @@ -2,12 +2,11 @@ package jsoniter import ( "fmt" + "github.com/modern-go/reflect2" "io" "reflect" "sort" "unsafe" - - "github.com/modern-go/reflect2" ) func decoderOfMap(ctx *ctx, typ reflect2.Type) ValDecoder { diff --git a/vendor/github.com/json-iterator/go/reflect_optional.go b/vendor/github.com/json-iterator/go/reflect_optional.go index 112c110a2..fa71f4748 100644 --- a/vendor/github.com/json-iterator/go/reflect_optional.go +++ b/vendor/github.com/json-iterator/go/reflect_optional.go @@ -1,9 +1,8 @@ package jsoniter import ( - "unsafe" - "github.com/modern-go/reflect2" + "unsafe" ) func decoderOfOptional(ctx *ctx, typ reflect2.Type) ValDecoder { diff --git a/vendor/github.com/json-iterator/go/reflect_slice.go b/vendor/github.com/json-iterator/go/reflect_slice.go index f363a7169..9441d79df 100644 --- a/vendor/github.com/json-iterator/go/reflect_slice.go +++ b/vendor/github.com/json-iterator/go/reflect_slice.go @@ -2,10 +2,9 @@ package jsoniter import ( "fmt" + "github.com/modern-go/reflect2" "io" "unsafe" - - "github.com/modern-go/reflect2" ) func decoderOfSlice(ctx *ctx, typ reflect2.Type) ValDecoder { diff --git a/vendor/github.com/json-iterator/go/reflect_struct_encoder.go b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go index edf77bf59..152e3ef5a 100644 --- a/vendor/github.com/json-iterator/go/reflect_struct_encoder.go +++ b/vendor/github.com/json-iterator/go/reflect_struct_encoder.go @@ -2,11 +2,10 @@ package jsoniter import ( "fmt" + "github.com/modern-go/reflect2" "io" "reflect" "unsafe" - - "github.com/modern-go/reflect2" ) func encoderOfStruct(ctx *ctx, typ reflect2.Type) ValEncoder { diff --git a/vendor/github.com/klauspost/compress/flate/gen_inflate.go b/vendor/github.com/klauspost/compress/flate/gen_inflate.go deleted file mode 100644 index 25ba3c714..000000000 --- a/vendor/github.com/klauspost/compress/flate/gen_inflate.go +++ /dev/null @@ -1,277 +0,0 @@ -//go:build generate -// +build generate - -//go:generate go run $GOFILE && gofmt -w inflate_gen.go - -package main - -import ( - "os" - "strings" -) - -func main() { - f, err := os.Create("inflate_gen.go") - if err != nil { - panic(err) - } - defer f.Close() - types := []string{"*bytes.Buffer", "*bytes.Reader", "*bufio.Reader", "*strings.Reader"} - names := []string{"BytesBuffer", "BytesReader", "BufioReader", "StringsReader"} - imports := []string{"bytes", "bufio", "io", "strings", "math/bits"} - f.WriteString(`// Code generated by go generate gen_inflate.go. DO NOT EDIT. - -package flate - -import ( -`) - - for _, imp := range imports { - f.WriteString("\t\"" + imp + "\"\n") - } - f.WriteString(")\n\n") - - template := ` - -// Decode a single Huffman block from f. -// hl and hd are the Huffman states for the lit/length values -// and the distance values, respectively. If hd == nil, using the -// fixed distance encoding associated with fixed Huffman blocks. -func (f *decompressor) $FUNCNAME$() { - const ( - stateInit = iota // Zero value must be stateInit - stateDict - ) - fr := f.r.($TYPE$) - moreBits := func() error { - c, err := fr.ReadByte() - if err != nil { - return noEOF(err) - } - f.roffset++ - f.b |= uint32(c) << f.nb - f.nb += 8 - return nil - } - - switch f.stepState { - case stateInit: - goto readLiteral - case stateDict: - goto copyHistory - } - -readLiteral: - // Read literal and/or (length, distance) according to RFC section 3.2.3. - { - var v int - { - // Inlined v, err := f.huffSym(f.hl) - // Since a huffmanDecoder can be empty or be composed of a degenerate tree - // with single element, huffSym must error on these two edge cases. In both - // cases, the chunks slice will be 0 for the invalid sequence, leading it - // satisfy the n == 0 check below. - n := uint(f.hl.maxRead) - // Optimization. Compiler isn't smart enough to keep f.b,f.nb in registers, - // but is smart enough to keep local variables in registers, so use nb and b, - // inline call to moreBits and reassign b,nb back to f on return. - nb, b := f.nb, f.b - for { - for nb < n { - c, err := fr.ReadByte() - if err != nil { - f.b = b - f.nb = nb - f.err = noEOF(err) - return - } - f.roffset++ - b |= uint32(c) << (nb & regSizeMaskUint32) - nb += 8 - } - chunk := f.hl.chunks[b&(huffmanNumChunks-1)] - n = uint(chunk & huffmanCountMask) - if n > huffmanChunkBits { - chunk = f.hl.links[chunk>>huffmanValueShift][(b>>huffmanChunkBits)&f.hl.linkMask] - n = uint(chunk & huffmanCountMask) - } - if n <= nb { - if n == 0 { - f.b = b - f.nb = nb - if debugDecode { - fmt.Println("huffsym: n==0") - } - f.err = CorruptInputError(f.roffset) - return - } - f.b = b >> (n & regSizeMaskUint32) - f.nb = nb - n - v = int(chunk >> huffmanValueShift) - break - } - } - } - - var n uint // number of bits extra - var length int - var err error - switch { - case v < 256: - f.dict.writeByte(byte(v)) - if f.dict.availWrite() == 0 { - f.toRead = f.dict.readFlush() - f.step = (*decompressor).$FUNCNAME$ - f.stepState = stateInit - return - } - goto readLiteral - case v == 256: - f.finishBlock() - return - // otherwise, reference to older data - case v < 265: - length = v - (257 - 3) - n = 0 - case v < 269: - length = v*2 - (265*2 - 11) - n = 1 - case v < 273: - length = v*4 - (269*4 - 19) - n = 2 - case v < 277: - length = v*8 - (273*8 - 35) - n = 3 - case v < 281: - length = v*16 - (277*16 - 67) - n = 4 - case v < 285: - length = v*32 - (281*32 - 131) - n = 5 - case v < maxNumLit: - length = 258 - n = 0 - default: - if debugDecode { - fmt.Println(v, ">= maxNumLit") - } - f.err = CorruptInputError(f.roffset) - return - } - if n > 0 { - for f.nb < n { - if err = moreBits(); err != nil { - if debugDecode { - fmt.Println("morebits n>0:", err) - } - f.err = err - return - } - } - length += int(f.b & uint32(1<<(n®SizeMaskUint32)-1)) - f.b >>= n & regSizeMaskUint32 - f.nb -= n - } - - var dist uint32 - if f.hd == nil { - for f.nb < 5 { - if err = f.moreBits(); err != nil { - if debugDecode { - fmt.Println("morebits f.nb<5:", err) - } - f.err = err - return - } - } - dist = uint32(bits.Reverse8(uint8(f.b & 0x1F << 3))) - f.b >>= 5 - f.nb -= 5 - } else { - sym, err := f.huffSym(f.hd) - if err != nil { - if debugDecode { - fmt.Println("huffsym:", err) - } - f.err = err - return - } - dist = uint32(sym) - } - - switch { - case dist < 4: - dist++ - case dist < maxNumDist: - nb := uint(dist-2) >> 1 - // have 1 bit in bottom of dist, need nb more. - extra := (dist & 1) << (nb & regSizeMaskUint32) - for f.nb < nb { - if err = f.moreBits(); err != nil { - if debugDecode { - fmt.Println("morebits f.nb>= nb & regSizeMaskUint32 - f.nb -= nb - dist = 1<<((nb+1)®SizeMaskUint32) + 1 + extra - default: - if debugDecode { - fmt.Println("dist too big:", dist, maxNumDist) - } - f.err = CorruptInputError(f.roffset) - return - } - - // No check on length; encoding can be prescient. - if dist > uint32(f.dict.histSize()) { - if debugDecode { - fmt.Println("dist > f.dict.histSize():", dist, f.dict.histSize()) - } - f.err = CorruptInputError(f.roffset) - return - } - - f.copyLen, f.copyDist = length, int(dist) - goto copyHistory - } - -copyHistory: - // Perform a backwards copy according to RFC section 3.2.3. - { - cnt := f.dict.tryWriteCopy(f.copyDist, f.copyLen) - if cnt == 0 { - cnt = f.dict.writeCopy(f.copyDist, f.copyLen) - } - f.copyLen -= cnt - - if f.dict.availWrite() == 0 || f.copyLen > 0 { - f.toRead = f.dict.readFlush() - f.step = (*decompressor).$FUNCNAME$ // We need to continue this work - f.stepState = stateDict - return - } - goto readLiteral - } -} - -` - for i, t := range types { - s := strings.Replace(template, "$FUNCNAME$", "huffman"+names[i], -1) - s = strings.Replace(s, "$TYPE$", t, -1) - f.WriteString(s) - } - f.WriteString("func (f *decompressor) huffmanBlockDecoder() func() {\n") - f.WriteString("\tswitch f.r.(type) {\n") - for i, t := range types { - f.WriteString("\t\tcase " + t + ":\n") - f.WriteString("\t\t\treturn f.huffman" + names[i] + "\n") - } - f.WriteString("\t\tdefault:\n") - f.WriteString("\t\t\treturn f.huffmanBlockGeneric") - f.WriteString("\t}\n}\n") -} diff --git a/vendor/github.com/klauspost/cpuid/detect_intel.go b/vendor/github.com/klauspost/cpuid/detect_intel.go deleted file mode 100644 index 09f9d6c15..000000000 --- a/vendor/github.com/klauspost/cpuid/detect_intel.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (c) 2015 Klaus Post, released under MIT License. See LICENSE file. - -//go:build (386 && !gccgo) || (amd64 && !gccgo) -// +build 386,!gccgo amd64,!gccgo - -package cpuid - -func asmCpuid(op uint32) (eax, ebx, ecx, edx uint32) -func asmCpuidex(op, op2 uint32) (eax, ebx, ecx, edx uint32) -func asmXgetbv(index uint32) (eax, edx uint32) -func asmRdtscpAsm() (eax, ebx, ecx, edx uint32) - -func initCPU() { - cpuid = asmCpuid - cpuidex = asmCpuidex - xgetbv = asmXgetbv - rdtscpAsm = asmRdtscpAsm -} diff --git a/vendor/github.com/klauspost/cpuid/detect_ref.go b/vendor/github.com/klauspost/cpuid/detect_ref.go deleted file mode 100644 index 8281367ac..000000000 --- a/vendor/github.com/klauspost/cpuid/detect_ref.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) 2015 Klaus Post, released under MIT License. See LICENSE file. - -//go:build (!amd64 && !386) || gccgo -// +build !amd64,!386 gccgo - -package cpuid - -func initCPU() { - cpuid = func(op uint32) (eax, ebx, ecx, edx uint32) { - return 0, 0, 0, 0 - } - - cpuidex = func(op, op2 uint32) (eax, ebx, ecx, edx uint32) { - return 0, 0, 0, 0 - } - - xgetbv = func(index uint32) (eax, edx uint32) { - return 0, 0 - } - - rdtscpAsm = func() (eax, ebx, ecx, edx uint32) { - return 0, 0, 0, 0 - } -} diff --git a/vendor/github.com/klauspost/reedsolomon/galoisAvx512_amd64.go b/vendor/github.com/klauspost/reedsolomon/galoisAvx512_amd64.go deleted file mode 100644 index 0f240b7d6..000000000 --- a/vendor/github.com/klauspost/reedsolomon/galoisAvx512_amd64.go +++ /dev/null @@ -1,337 +0,0 @@ -//go:build !noasm && !appengine && !gccgo -// +build !noasm,!appengine,!gccgo - -// Copyright 2015, Klaus Post, see LICENSE for details. -// Copyright 2019, Minio, Inc. - -package reedsolomon - -import ( - "sync" -) - -//go:noescape -func _galMulAVX512Parallel81(in, out [][]byte, matrix *[matrixSize81]byte, addTo bool) - -//go:noescape -func _galMulAVX512Parallel82(in, out [][]byte, matrix *[matrixSize82]byte, addTo bool) - -//go:noescape -func _galMulAVX512Parallel84(in, out [][]byte, matrix *[matrixSize84]byte, addTo bool) - -const ( - dimIn = 8 // Number of input rows processed simultaneously - dimOut81 = 1 // Number of output rows processed simultaneously for x1 routine - dimOut82 = 2 // Number of output rows processed simultaneously for x2 routine - dimOut84 = 4 // Number of output rows processed simultaneously for x4 routine - matrixSize81 = (16 + 16) * dimIn * dimOut81 // Dimension of slice of matrix coefficient passed into x1 routine - matrixSize82 = (16 + 16) * dimIn * dimOut82 // Dimension of slice of matrix coefficient passed into x2 routine - matrixSize84 = (16 + 16) * dimIn * dimOut84 // Dimension of slice of matrix coefficient passed into x4 routine -) - -// Construct block of matrix coefficients for single output row in parallel -func setupMatrix81(matrixRows [][]byte, inputOffset, outputOffset int, matrix *[matrixSize81]byte) { - offset := 0 - for c := inputOffset; c < inputOffset+dimIn; c++ { - for iRow := outputOffset; iRow < outputOffset+dimOut81; iRow++ { - if c < len(matrixRows[iRow]) { - coeff := matrixRows[iRow][c] - copy(matrix[offset*32:], mulTableLow[coeff][:]) - copy(matrix[offset*32+16:], mulTableHigh[coeff][:]) - } else { - // coefficients not used for this input shard (so null out) - v := matrix[offset*32 : offset*32+32] - for i := range v { - v[i] = 0 - } - } - offset += dimIn - if offset >= dimIn*dimOut81 { - offset -= dimIn*dimOut81 - 1 - } - } - } -} - -// Construct block of matrix coefficients for 2 output rows in parallel -func setupMatrix82(matrixRows [][]byte, inputOffset, outputOffset int, matrix *[matrixSize82]byte) { - offset := 0 - for c := inputOffset; c < inputOffset+dimIn; c++ { - for iRow := outputOffset; iRow < outputOffset+dimOut82; iRow++ { - if c < len(matrixRows[iRow]) { - coeff := matrixRows[iRow][c] - copy(matrix[offset*32:], mulTableLow[coeff][:]) - copy(matrix[offset*32+16:], mulTableHigh[coeff][:]) - } else { - // coefficients not used for this input shard (so null out) - v := matrix[offset*32 : offset*32+32] - for i := range v { - v[i] = 0 - } - } - offset += dimIn - if offset >= dimIn*dimOut82 { - offset -= dimIn*dimOut82 - 1 - } - } - } -} - -// Construct block of matrix coefficients for 4 output rows in parallel -func setupMatrix84(matrixRows [][]byte, inputOffset, outputOffset int, matrix *[matrixSize84]byte) { - offset := 0 - for c := inputOffset; c < inputOffset+dimIn; c++ { - for iRow := outputOffset; iRow < outputOffset+dimOut84; iRow++ { - if c < len(matrixRows[iRow]) { - coeff := matrixRows[iRow][c] - copy(matrix[offset*32:], mulTableLow[coeff][:]) - copy(matrix[offset*32+16:], mulTableHigh[coeff][:]) - } else { - // coefficients not used for this input shard (so null out) - v := matrix[offset*32 : offset*32+32] - for i := range v { - v[i] = 0 - } - } - offset += dimIn - if offset >= dimIn*dimOut84 { - offset -= dimIn*dimOut84 - 1 - } - } - } -} - -// Invoke AVX512 routine for single output row in parallel -func galMulAVX512Parallel81(in, out [][]byte, matrixRows [][]byte, inputOffset, outputOffset, start, stop int, matrix81 *[matrixSize81]byte) { - done := stop - start - if done <= 0 { - return - } - - inputEnd := inputOffset + dimIn - if inputEnd > len(in) { - inputEnd = len(in) - } - outputEnd := outputOffset + dimOut81 - if outputEnd > len(out) { - outputEnd = len(out) - } - - // We know the max size, alloc temp array. - var inTmp [dimIn][]byte - for i, v := range in[inputOffset:inputEnd] { - inTmp[i] = v[start:stop] - } - var outTmp [dimOut81][]byte - for i, v := range out[outputOffset:outputEnd] { - outTmp[i] = v[start:stop] - } - - addTo := inputOffset != 0 // Except for the first input column, add to previous results - _galMulAVX512Parallel81(inTmp[:inputEnd-inputOffset], outTmp[:outputEnd-outputOffset], matrix81, addTo) - - done = start + ((done >> 6) << 6) - if done < stop { - galMulAVX512LastInput(inputOffset, inputEnd, outputOffset, outputEnd, matrixRows, done, stop, out, in) - } -} - -// Invoke AVX512 routine for 2 output rows in parallel -func galMulAVX512Parallel82(in, out [][]byte, matrixRows [][]byte, inputOffset, outputOffset, start, stop int, matrix82 *[matrixSize82]byte) { - done := stop - start - if done <= 0 { - return - } - - inputEnd := inputOffset + dimIn - if inputEnd > len(in) { - inputEnd = len(in) - } - outputEnd := outputOffset + dimOut82 - if outputEnd > len(out) { - outputEnd = len(out) - } - - // We know the max size, alloc temp array. - var inTmp [dimIn][]byte - for i, v := range in[inputOffset:inputEnd] { - inTmp[i] = v[start:stop] - } - var outTmp [dimOut82][]byte - for i, v := range out[outputOffset:outputEnd] { - outTmp[i] = v[start:stop] - } - - addTo := inputOffset != 0 // Except for the first input column, add to previous results - _galMulAVX512Parallel82(inTmp[:inputEnd-inputOffset], outTmp[:outputEnd-outputOffset], matrix82, addTo) - - done = start + ((done >> 6) << 6) - if done < stop { - galMulAVX512LastInput(inputOffset, inputEnd, outputOffset, outputEnd, matrixRows, done, stop, out, in) - } -} - -// Invoke AVX512 routine for 4 output rows in parallel -func galMulAVX512Parallel84(in, out [][]byte, matrixRows [][]byte, inputOffset, outputOffset, start, stop int, matrix84 *[matrixSize84]byte) { - done := stop - start - if done <= 0 { - return - } - - inputEnd := inputOffset + dimIn - if inputEnd > len(in) { - inputEnd = len(in) - } - outputEnd := outputOffset + dimOut84 - if outputEnd > len(out) { - outputEnd = len(out) - } - - // We know the max size, alloc temp array. - var inTmp [dimIn][]byte - for i, v := range in[inputOffset:inputEnd] { - inTmp[i] = v[start:stop] - } - var outTmp [dimOut84][]byte - for i, v := range out[outputOffset:outputEnd] { - outTmp[i] = v[start:stop] - } - - addTo := inputOffset != 0 // Except for the first input column, add to previous results - _galMulAVX512Parallel84(inTmp[:inputEnd-inputOffset], outTmp[:outputEnd-outputOffset], matrix84, addTo) - - done = start + ((done >> 6) << 6) - if done < stop { - galMulAVX512LastInput(inputOffset, inputEnd, outputOffset, outputEnd, matrixRows, done, stop, out, in) - } -} - -func galMulAVX512LastInput(inputOffset int, inputEnd int, outputOffset int, outputEnd int, matrixRows [][]byte, done int, stop int, out [][]byte, in [][]byte) { - for c := inputOffset; c < inputEnd; c++ { - for iRow := outputOffset; iRow < outputEnd; iRow++ { - if c < len(matrixRows[iRow]) { - mt := mulTable[matrixRows[iRow][c]][:256] - for i := done; i < stop; i++ { - if c == 0 { // only set value for first input column - out[iRow][i] = mt[in[c][i]] - } else { // and add for all others - out[iRow][i] ^= mt[in[c][i]] - } - } - } - } - } -} - -// Perform the same as codeSomeShards, but taking advantage of -// AVX512 parallelism for up to 4x faster execution as compared to AVX2 -func (r *reedSolomon) codeSomeShardsAvx512(matrixRows, inputs, outputs [][]byte, outputCount, byteCount int) { - // Process using no goroutines - start, end := 0, r.o.perRound - if end > byteCount { - end = byteCount - } - for start < byteCount { - matrix84 := [matrixSize84]byte{} - matrix82 := [matrixSize82]byte{} - matrix81 := [matrixSize81]byte{} - - outputRow := 0 - // First process (multiple) batches of 4 output rows in parallel - if outputRow+dimOut84 <= outputCount { - for ; outputRow+dimOut84 <= outputCount; outputRow += dimOut84 { - for inputRow := 0; inputRow < len(inputs); inputRow += dimIn { - setupMatrix84(matrixRows, inputRow, outputRow, &matrix84) - galMulAVX512Parallel84(inputs, outputs, matrixRows, inputRow, outputRow, start, end, &matrix84) - } - } - } - // Then process a (single) batch of 2 output rows in parallel - if outputRow+dimOut82 <= outputCount { - for inputRow := 0; inputRow < len(inputs); inputRow += dimIn { - setupMatrix82(matrixRows, inputRow, outputRow, &matrix82) - galMulAVX512Parallel82(inputs, outputs, matrixRows, inputRow, outputRow, start, end, &matrix82) - } - outputRow += dimOut82 - } - // Lastly, we may have a single output row left (for uneven parity) - if outputRow < outputCount { - for inputRow := 0; inputRow < len(inputs); inputRow += dimIn { - setupMatrix81(matrixRows, inputRow, outputRow, &matrix81) - galMulAVX512Parallel81(inputs, outputs, matrixRows, inputRow, outputRow, start, end, &matrix81) - } - } - - start = end - end += r.o.perRound - if end > byteCount { - end = byteCount - } - } -} - -// Perform the same as codeSomeShards, but taking advantage of -// AVX512 parallelism for up to 4x faster execution as compared to AVX2 -func (r *reedSolomon) codeSomeShardsAvx512P(matrixRows, inputs, outputs [][]byte, outputCount, byteCount int) { - var wg sync.WaitGroup - do := byteCount / r.o.maxGoroutines - if do < r.o.minSplitSize { - do = r.o.minSplitSize - } - // Make sizes divisible by 64 - do = (do + 63) & (^63) - start := 0 - for start < byteCount { - if start+do > byteCount { - do = byteCount - start - } - wg.Add(1) - go func(grStart, grStop int) { - start, stop := grStart, grStart+r.o.perRound - if stop > grStop { - stop = grStop - } - // Loop for each round. - matrix84 := [matrixSize84]byte{} - matrix82 := [matrixSize82]byte{} - matrix81 := [matrixSize81]byte{} - for start < grStop { - outputRow := 0 - // First process (multiple) batches of 4 output rows in parallel - if outputRow+dimOut84 <= outputCount { - // 1K matrix buffer - for ; outputRow+dimOut84 <= outputCount; outputRow += dimOut84 { - for inputRow := 0; inputRow < len(inputs); inputRow += dimIn { - setupMatrix84(matrixRows, inputRow, outputRow, &matrix84) - galMulAVX512Parallel84(inputs, outputs, matrixRows, inputRow, outputRow, start, stop, &matrix84) - } - } - } - // Then process a (single) batch of 2 output rows in parallel - if outputRow+dimOut82 <= outputCount { - // 512B matrix buffer - for inputRow := 0; inputRow < len(inputs); inputRow += dimIn { - setupMatrix82(matrixRows, inputRow, outputRow, &matrix82) - galMulAVX512Parallel82(inputs, outputs, matrixRows, inputRow, outputRow, start, stop, &matrix82) - } - outputRow += dimOut82 - } - // Lastly, we may have a single output row left (for uneven parity) - if outputRow < outputCount { - for inputRow := 0; inputRow < len(inputs); inputRow += dimIn { - setupMatrix81(matrixRows, inputRow, outputRow, &matrix81) - galMulAVX512Parallel81(inputs, outputs, matrixRows, inputRow, outputRow, start, stop, &matrix81) - } - } - start = stop - stop += r.o.perRound - if stop > grStop { - stop = grStop - } - } - wg.Done() - }(start, start+do) - start += do - } - wg.Wait() -} diff --git a/vendor/github.com/klauspost/reedsolomon/gen.go b/vendor/github.com/klauspost/reedsolomon/gen.go deleted file mode 100644 index 416d4cc80..000000000 --- a/vendor/github.com/klauspost/reedsolomon/gen.go +++ /dev/null @@ -1,250 +0,0 @@ -//go:build generate -// +build generate - -//go:generate go run gen.go -out galois_gen_amd64.s -stubs galois_gen_amd64.go -//go:generate gofmt -w galois_gen_switch_amd64.go - -package main - -import ( - "bufio" - "fmt" - "os" - - . "github.com/mmcloughlin/avo/build" - "github.com/mmcloughlin/avo/buildtags" - . "github.com/mmcloughlin/avo/operand" - "github.com/mmcloughlin/avo/reg" -) - -// Technically we can do slightly bigger, but we stay reasonable. -const inputMax = 10 -const outputMax = 8 - -var switchDefs [inputMax][outputMax]string -var switchDefsX [inputMax][outputMax]string - -const perLoopBits = 5 -const perLoop = 1 << perLoopBits - -func main() { - Constraint(buildtags.Not("appengine").ToConstraint()) - Constraint(buildtags.Not("noasm").ToConstraint()) - Constraint(buildtags.Not("nogen").ToConstraint()) - Constraint(buildtags.Term("gc").ToConstraint()) - - for i := 1; i <= inputMax; i++ { - for j := 1; j <= outputMax; j++ { - //genMulAvx2(fmt.Sprintf("mulAvxTwoXor_%dx%d", i, j), i, j, true) - genMulAvx2(fmt.Sprintf("mulAvxTwo_%dx%d", i, j), i, j, false) - } - } - f, err := os.Create("galois_gen_switch_amd64.go") - if err != nil { - panic(err) - } - defer f.Close() - w := bufio.NewWriter(f) - defer w.Flush() - w.WriteString(`// Code generated by command: go generate ` + os.Getenv("GOFILE") + `. DO NOT EDIT. - -// +build !appengine -// +build !noasm -// +build gc -// +build !nogen - -package reedsolomon - -import "fmt" - -`) - - w.WriteString("const avx2CodeGen = true\n") - w.WriteString(fmt.Sprintf("const maxAvx2Inputs = %d\nconst maxAvx2Outputs = %d\n", inputMax, outputMax)) - w.WriteString(` - -func galMulSlicesAvx2(matrix []byte, in, out [][]byte, start, stop int) int { - n := stop-start -`) - - w.WriteString(fmt.Sprintf("n = (n>>%d)<<%d\n\n", perLoopBits, perLoopBits)) - w.WriteString(`switch len(in) { -`) - for in, defs := range switchDefs[:] { - w.WriteString(fmt.Sprintf(" case %d:\n switch len(out) {\n", in+1)) - for out, def := range defs[:] { - w.WriteString(fmt.Sprintf(" case %d:\n", out+1)) - w.WriteString(def) - } - w.WriteString("}\n") - } - w.WriteString(`} - panic(fmt.Sprintf("unhandled size: %dx%d", len(in), len(out))) -} -`) - Generate() -} - -func genMulAvx2(name string, inputs int, outputs int, xor bool) { - total := inputs * outputs - - doc := []string{ - fmt.Sprintf("%s takes %d inputs and produces %d outputs.", name, inputs, outputs), - } - if !xor { - doc = append(doc, "The output is initialized to 0.") - } - - // Load shuffle masks on every use. - var loadNone bool - // Use registers for destination registers. - var regDst = true - - // lo, hi, 1 in, 1 out, 2 tmp, 1 mask - est := total*2 + outputs + 5 - if outputs == 1 { - // We don't need to keep a copy of the input if only 1 output. - est -= 2 - } - - if est > 16 { - loadNone = true - // We run out of GP registers first, now. - if inputs+outputs > 12 { - regDst = false - } - } - - TEXT(name, 0, fmt.Sprintf("func(matrix []byte, in [][]byte, out [][]byte, start, n int)")) - - // SWITCH DEFINITION: - s := fmt.Sprintf(" mulAvxTwo_%dx%d(matrix, in, out, start, n)\n", inputs, outputs) - s += fmt.Sprintf("\t\t\t\treturn n\n") - switchDefs[inputs-1][outputs-1] = s - - if loadNone { - Comment("Loading no tables to registers") - } else { - // loadNone == false - Comment("Loading all tables to registers") - } - - Doc(doc...) - Pragma("noescape") - Commentf("Full registers estimated %d YMM used", est) - - length := Load(Param("n"), GP64()) - matrixBase := GP64() - MOVQ(Param("matrix").Base().MustAddr(), matrixBase) - SHRQ(U8(perLoopBits), length) - TESTQ(length, length) - JZ(LabelRef(name + "_end")) - - dst := make([]reg.VecVirtual, outputs) - dstPtr := make([]reg.GPVirtual, outputs) - outBase := Param("out").Base().MustAddr() - outSlicePtr := GP64() - MOVQ(outBase, outSlicePtr) - for i := range dst { - dst[i] = YMM() - if !regDst { - continue - } - ptr := GP64() - MOVQ(Mem{Base: outSlicePtr, Disp: i * 24}, ptr) - dstPtr[i] = ptr - } - - inLo := make([]reg.VecVirtual, total) - inHi := make([]reg.VecVirtual, total) - - for i := range inLo { - if loadNone { - break - } - tableLo := YMM() - tableHi := YMM() - VMOVDQU(Mem{Base: matrixBase, Disp: i * 64}, tableLo) - VMOVDQU(Mem{Base: matrixBase, Disp: i*64 + 32}, tableHi) - inLo[i] = tableLo - inHi[i] = tableHi - } - - inPtrs := make([]reg.GPVirtual, inputs) - inSlicePtr := GP64() - MOVQ(Param("in").Base().MustAddr(), inSlicePtr) - for i := range inPtrs { - ptr := GP64() - MOVQ(Mem{Base: inSlicePtr, Disp: i * 24}, ptr) - inPtrs[i] = ptr - } - - tmpMask := GP64() - MOVQ(U32(15), tmpMask) - lowMask := YMM() - MOVQ(tmpMask, lowMask.AsX()) - VPBROADCASTB(lowMask.AsX(), lowMask) - - offset := GP64() - MOVQ(Param("start").MustAddr(), offset) - Label(name + "_loop") - if xor { - Commentf("Load %d outputs", outputs) - } else { - Commentf("Clear %d outputs", outputs) - } - for i := range dst { - if xor { - if regDst { - VMOVDQU(Mem{Base: dstPtr[i], Index: offset, Scale: 1}, dst[i]) - continue - } - ptr := GP64() - MOVQ(outBase, ptr) - VMOVDQU(Mem{Base: ptr, Index: offset, Scale: 1}, dst[i]) - } else { - VPXOR(dst[i], dst[i], dst[i]) - } - } - - lookLow, lookHigh := YMM(), YMM() - inLow, inHigh := YMM(), YMM() - for i := range inPtrs { - Commentf("Load and process 32 bytes from input %d to %d outputs", i, outputs) - VMOVDQU(Mem{Base: inPtrs[i], Index: offset, Scale: 1}, inLow) - VPSRLQ(U8(4), inLow, inHigh) - VPAND(lowMask, inLow, inLow) - VPAND(lowMask, inHigh, inHigh) - for j := range dst { - if loadNone { - VMOVDQU(Mem{Base: matrixBase, Disp: 64 * (i*outputs + j)}, lookLow) - VMOVDQU(Mem{Base: matrixBase, Disp: 32 + 64*(i*outputs+j)}, lookHigh) - VPSHUFB(inLow, lookLow, lookLow) - VPSHUFB(inHigh, lookHigh, lookHigh) - } else { - VPSHUFB(inLow, inLo[i*outputs+j], lookLow) - VPSHUFB(inHigh, inHi[i*outputs+j], lookHigh) - } - VPXOR(lookLow, lookHigh, lookLow) - VPXOR(lookLow, dst[j], dst[j]) - } - } - Commentf("Store %d outputs", outputs) - for i := range dst { - if regDst { - VMOVDQU(dst[i], Mem{Base: dstPtr[i], Index: offset, Scale: 1}) - continue - } - ptr := GP64() - MOVQ(Mem{Base: outSlicePtr, Disp: i * 24}, ptr) - VMOVDQU(dst[i], Mem{Base: ptr, Index: offset, Scale: 1}) - } - Comment("Prepare for next loop") - ADDQ(U8(perLoop), offset) - DECQ(length) - JNZ(LabelRef(name + "_loop")) - VZEROUPPER() - - Label(name + "_end") - RET() -} diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go index e81692cf5..57f530ae8 100644 --- a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go +++ b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences.go @@ -1,4 +1,3 @@ -//go:build windows // +build windows package sequences diff --git a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go index 4c5817416..df61a6f2f 100644 --- a/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go +++ b/vendor/github.com/konsorten/go-windows-terminal-sequences/sequences_dummy.go @@ -1,4 +1,3 @@ -//go:build linux || darwin // +build linux darwin package sequences diff --git a/vendor/github.com/modern-go/concurrent/go_above_19.go b/vendor/github.com/modern-go/concurrent/go_above_19.go index 7db701945..aeabf8c4f 100644 --- a/vendor/github.com/modern-go/concurrent/go_above_19.go +++ b/vendor/github.com/modern-go/concurrent/go_above_19.go @@ -1,5 +1,4 @@ -//go:build go1.9 -// +build go1.9 +//+build go1.9 package concurrent diff --git a/vendor/github.com/modern-go/concurrent/go_below_19.go b/vendor/github.com/modern-go/concurrent/go_below_19.go index 64544f5b3..b9c8df7f4 100644 --- a/vendor/github.com/modern-go/concurrent/go_below_19.go +++ b/vendor/github.com/modern-go/concurrent/go_below_19.go @@ -1,5 +1,4 @@ -//go:build !go1.9 -// +build !go1.9 +//+build !go1.9 package concurrent diff --git a/vendor/github.com/modern-go/concurrent/log.go b/vendor/github.com/modern-go/concurrent/log.go index 4899eed02..9756fcc75 100644 --- a/vendor/github.com/modern-go/concurrent/log.go +++ b/vendor/github.com/modern-go/concurrent/log.go @@ -1,13 +1,13 @@ package concurrent import ( - "io/ioutil" - "log" "os" + "log" + "io/ioutil" ) // ErrorLogger is used to print out error, can be set to writer other than stderr var ErrorLogger = log.New(os.Stderr, "", 0) // InfoLogger is used to print informational message, default to off -var InfoLogger = log.New(ioutil.Discard, "", 0) +var InfoLogger = log.New(ioutil.Discard, "", 0) \ No newline at end of file diff --git a/vendor/github.com/modern-go/concurrent/unbounded_executor.go b/vendor/github.com/modern-go/concurrent/unbounded_executor.go index 5ea18eb7b..05a77dceb 100644 --- a/vendor/github.com/modern-go/concurrent/unbounded_executor.go +++ b/vendor/github.com/modern-go/concurrent/unbounded_executor.go @@ -3,11 +3,11 @@ package concurrent import ( "context" "fmt" - "reflect" "runtime" "runtime/debug" "sync" "time" + "reflect" ) // HandlePanic logs goroutine panic by default diff --git a/vendor/github.com/modern-go/reflect2/go_above_118.go b/vendor/github.com/modern-go/reflect2/go_above_118.go index 05f07835e..2b4116f6c 100644 --- a/vendor/github.com/modern-go/reflect2/go_above_118.go +++ b/vendor/github.com/modern-go/reflect2/go_above_118.go @@ -1,5 +1,4 @@ -//go:build go1.18 -// +build go1.18 +//+build go1.18 package reflect2 @@ -21,4 +20,4 @@ func (type2 *UnsafeMapType) UnsafeIterate(obj unsafe.Pointer) MapIterator { pKeyRType: type2.pKeyRType, pElemRType: type2.pElemRType, } -} +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/go_above_19.go b/vendor/github.com/modern-go/reflect2/go_above_19.go index 03ccb43c6..974f7685e 100644 --- a/vendor/github.com/modern-go/reflect2/go_above_19.go +++ b/vendor/github.com/modern-go/reflect2/go_above_19.go @@ -1,5 +1,4 @@ -//go:build go1.9 -// +build go1.9 +//+build go1.9 package reflect2 diff --git a/vendor/github.com/modern-go/reflect2/go_below_118.go b/vendor/github.com/modern-go/reflect2/go_below_118.go index 3501097ad..00003dbd7 100644 --- a/vendor/github.com/modern-go/reflect2/go_below_118.go +++ b/vendor/github.com/modern-go/reflect2/go_below_118.go @@ -1,5 +1,4 @@ -//go:build !go1.18 -// +build !go1.18 +//+build !go1.18 package reflect2 @@ -19,4 +18,4 @@ func (type2 *UnsafeMapType) UnsafeIterate(obj unsafe.Pointer) MapIterator { pKeyRType: type2.pKeyRType, pElemRType: type2.pElemRType, } -} +} \ No newline at end of file diff --git a/vendor/github.com/modern-go/reflect2/type_map.go b/vendor/github.com/modern-go/reflect2/type_map.go index 0e2382b80..4b13c3155 100644 --- a/vendor/github.com/modern-go/reflect2/type_map.go +++ b/vendor/github.com/modern-go/reflect2/type_map.go @@ -1,4 +1,3 @@ -//go:build !gccgo // +build !gccgo package reflect2 diff --git a/vendor/github.com/pkg/errors/go113.go b/vendor/github.com/pkg/errors/go113.go index 2c83c7245..be0d10d0c 100644 --- a/vendor/github.com/pkg/errors/go113.go +++ b/vendor/github.com/pkg/errors/go113.go @@ -1,4 +1,3 @@ -//go:build go1.13 // +build go1.13 package errors diff --git a/vendor/github.com/sirupsen/logrus/hooks/syslog/syslog.go b/vendor/github.com/sirupsen/logrus/hooks/syslog/syslog.go index 0f7d15715..02b8df380 100644 --- a/vendor/github.com/sirupsen/logrus/hooks/syslog/syslog.go +++ b/vendor/github.com/sirupsen/logrus/hooks/syslog/syslog.go @@ -1,4 +1,3 @@ -//go:build !windows && !nacl && !plan9 // +build !windows,!nacl,!plan9 package syslog diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go b/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go index 45de3e2b6..2403de981 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go @@ -1,4 +1,3 @@ -//go:build appengine // +build appengine package logrus diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go index e3fa38b71..499789984 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go @@ -1,4 +1,3 @@ -//go:build (darwin || dragonfly || freebsd || netbsd || openbsd) && !js // +build darwin dragonfly freebsd netbsd openbsd // +build !js diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_js.go b/vendor/github.com/sirupsen/logrus/terminal_check_js.go index 9e951f1b4..ebdae3ec6 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_js.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_js.go @@ -1,4 +1,3 @@ -//go:build js // +build js package logrus diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go b/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go index 04232da19..97af92c68 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go @@ -1,4 +1,3 @@ -//go:build js || nacl || plan9 // +build js nacl plan9 package logrus diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go b/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go index 1b4a99e32..3293fb3ca 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go @@ -1,4 +1,3 @@ -//go:build !appengine && !js && !windows && !nacl && !plan9 // +build !appengine,!js,!windows,!nacl,!plan9 package logrus diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_unix.go b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go index f3154b17f..04748b851 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_unix.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go @@ -1,4 +1,3 @@ -//go:build (linux || aix || zos) && !js // +build linux aix zos // +build !js diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_windows.go b/vendor/github.com/sirupsen/logrus/terminal_check_windows.go index 893c62410..2879eb50e 100644 --- a/vendor/github.com/sirupsen/logrus/terminal_check_windows.go +++ b/vendor/github.com/sirupsen/logrus/terminal_check_windows.go @@ -1,4 +1,3 @@ -//go:build !appengine && !js && windows // +build !appengine,!js,windows package logrus diff --git a/vendor/github.com/skycoin/dmsg/internal/servermetrics/victoria_metrics.go b/vendor/github.com/skycoin/dmsg/internal/servermetrics/victoria_metrics.go index b61ab63e6..900acedf5 100644 --- a/vendor/github.com/skycoin/dmsg/internal/servermetrics/victoria_metrics.go +++ b/vendor/github.com/skycoin/dmsg/internal/servermetrics/victoria_metrics.go @@ -5,7 +5,6 @@ import ( "fmt" "github.com/VictoriaMetrics/metrics" - "github.com/skycoin/skywire-utilities/pkg/metricsutil" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/disc/client.go b/vendor/github.com/skycoin/dmsg/pkg/disc/client.go index a22c02300..a74be3be4 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/disc/client.go +++ b/vendor/github.com/skycoin/dmsg/pkg/disc/client.go @@ -11,7 +11,6 @@ import ( "time" jsoniter "github.com/json-iterator/go" - "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsg/entity_common.go b/vendor/github.com/skycoin/dmsg/pkg/dmsg/entity_common.go index 2dff1e955..9ead2b5d7 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsg/entity_common.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsg/entity_common.go @@ -9,7 +9,6 @@ import ( "time" "github.com/sirupsen/logrus" - "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" "github.com/skycoin/skywire-utilities/pkg/netutil" diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsg/server.go b/vendor/github.com/skycoin/dmsg/pkg/dmsg/server.go index d74692a32..4985c57e2 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsg/server.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsg/server.go @@ -8,7 +8,6 @@ import ( "time" "github.com/sirupsen/logrus" - "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" "github.com/skycoin/skywire-utilities/pkg/netutil" diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsgget/dmsgget.go b/vendor/github.com/skycoin/dmsg/pkg/dmsgget/dmsgget.go index 5bbfdc64d..0193d6dbc 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsgget/dmsgget.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsgget/dmsgget.go @@ -14,7 +14,6 @@ import ( jsoniter "github.com/json-iterator/go" "github.com/sirupsen/logrus" - "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/cli.go b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/cli.go index 3497a6e06..eb9ca0225 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/cli.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/cli.go @@ -12,7 +12,6 @@ import ( "syscall" "github.com/sirupsen/logrus" - "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/host.go b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/host.go index b1e4b8f71..6784ae2f6 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/host.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/host.go @@ -13,7 +13,6 @@ import ( "sync/atomic" "github.com/sirupsen/logrus" - "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/pty_client.go b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/pty_client.go index 246d00ddc..d6e10063b 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/pty_client.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/pty_client.go @@ -8,7 +8,6 @@ import ( "sync" "github.com/sirupsen/logrus" - "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/ui.go b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/ui.go index 9fb760885..5aa52afe8 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/ui.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsgpty/ui.go @@ -13,10 +13,9 @@ import ( "time" "github.com/sirupsen/logrus" - "nhooyr.io/websocket" - "github.com/skycoin/skywire-utilities/pkg/httputil" "github.com/skycoin/skywire-utilities/pkg/logging" + "nhooyr.io/websocket" ) const ( diff --git a/vendor/github.com/skycoin/dmsg/pkg/dmsgtest/env.go b/vendor/github.com/skycoin/dmsg/pkg/dmsgtest/env.go index 06d510a78..9a294ea84 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/dmsgtest/env.go +++ b/vendor/github.com/skycoin/dmsg/pkg/dmsgtest/env.go @@ -8,9 +8,8 @@ import ( "testing" "time" - "golang.org/x/net/nettest" - "github.com/skycoin/skywire-utilities/pkg/cipher" + "golang.org/x/net/nettest" "github.com/skycoin/dmsg/pkg/disc" dmsg "github.com/skycoin/dmsg/pkg/dmsg" diff --git a/vendor/github.com/skycoin/dmsg/pkg/noise/net.go b/vendor/github.com/skycoin/dmsg/pkg/noise/net.go index 9f87e09a2..87f2561c6 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/noise/net.go +++ b/vendor/github.com/skycoin/dmsg/pkg/noise/net.go @@ -9,7 +9,6 @@ import ( "time" "github.com/skycoin/noise" - "github.com/skycoin/skywire-utilities/pkg/cipher" ) diff --git a/vendor/github.com/skycoin/dmsg/pkg/noise/noise.go b/vendor/github.com/skycoin/dmsg/pkg/noise/noise.go index e5ef11d67..aa35d668f 100644 --- a/vendor/github.com/skycoin/dmsg/pkg/noise/noise.go +++ b/vendor/github.com/skycoin/dmsg/pkg/noise/noise.go @@ -8,7 +8,6 @@ import ( "fmt" "github.com/skycoin/noise" - "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire-utilities/pkg/logging" ) diff --git a/vendor/github.com/skycoin/noise/patterns.go b/vendor/github.com/skycoin/noise/patterns.go index 7d29d5ba7..094cf38bf 100644 --- a/vendor/github.com/skycoin/noise/patterns.go +++ b/vendor/github.com/skycoin/noise/patterns.go @@ -99,7 +99,7 @@ var HandshakeXX = HandshakePattern{ } var HandshakeXXfallback = HandshakePattern{ - Name: "XXfallback", + Name: "XXfallback", ResponderPreMessages: []MessagePattern{MessagePatternE}, Messages: [][]MessagePattern{ {MessagePatternE, MessagePatternDHEE, MessagePatternS, MessagePatternDHSE}, diff --git a/vendor/github.com/skycoin/skycoin/src/cipher/secp256k1-go/secp256k1-go2/secp256k1.go b/vendor/github.com/skycoin/skycoin/src/cipher/secp256k1-go/secp256k1-go2/secp256k1.go index db8f044ee..1cbb4ae33 100644 --- a/vendor/github.com/skycoin/skycoin/src/cipher/secp256k1-go/secp256k1-go2/secp256k1.go +++ b/vendor/github.com/skycoin/skycoin/src/cipher/secp256k1-go/secp256k1-go2/secp256k1.go @@ -22,8 +22,8 @@ func initConstants() { 0xBA, 0xAE, 0xDC, 0xE6, 0xAF, 0x48, 0xA0, 0x3B, 0xBF, 0xD2, 0x5E, 0x8C, 0xD0, 0x36, 0x41, 0x41}) TheCurve.halfOrder.SetBytes([]byte{ - 0x7F, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, - 0x5D, 0x57, 0x6E, 0x73, 0x57, 0xA4, 0x50, 0x1D, 0xDF, 0xE9, 0x2F, 0x46, 0x68, 0x1B, 0x20, 0xA0}) + 0X7F, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, 0XFF, + 0X5D, 0X57, 0X6E, 0X73, 0X57, 0XA4, 0X50, 0X1D, 0XDF, 0XE9, 0X2F, 0X46, 0X68, 0X1B, 0X20, 0XA0}) TheCurve.p.SetBytes([]byte{ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, diff --git a/vendor/github.com/songgao/water/params_others.go b/vendor/github.com/songgao/water/params_others.go index e5bb0c9b5..c5c4f6e31 100644 --- a/vendor/github.com/songgao/water/params_others.go +++ b/vendor/github.com/songgao/water/params_others.go @@ -1,4 +1,3 @@ -//go:build !linux && !darwin && !windows // +build !linux,!darwin,!windows package water diff --git a/vendor/github.com/songgao/water/syscalls_darwin_go1.11.go b/vendor/github.com/songgao/water/syscalls_darwin_go1.11.go index 752d7fcea..b02f734fe 100644 --- a/vendor/github.com/songgao/water/syscalls_darwin_go1.11.go +++ b/vendor/github.com/songgao/water/syscalls_darwin_go1.11.go @@ -1,4 +1,3 @@ -//go:build darwin && go1.11 // +build darwin,go1.11 package water diff --git a/vendor/github.com/songgao/water/syscalls_darwin_legacy.go b/vendor/github.com/songgao/water/syscalls_darwin_legacy.go index 7e80be5bc..d1745409a 100644 --- a/vendor/github.com/songgao/water/syscalls_darwin_legacy.go +++ b/vendor/github.com/songgao/water/syscalls_darwin_legacy.go @@ -1,4 +1,3 @@ -//go:build darwin && !go1.11 // +build darwin,!go1.11 package water diff --git a/vendor/github.com/songgao/water/syscalls_linux_go1.11.go b/vendor/github.com/songgao/water/syscalls_linux_go1.11.go index 780815cb6..90c47a123 100644 --- a/vendor/github.com/songgao/water/syscalls_linux_go1.11.go +++ b/vendor/github.com/songgao/water/syscalls_linux_go1.11.go @@ -1,4 +1,3 @@ -//go:build linux && go1.11 // +build linux,go1.11 package water diff --git a/vendor/github.com/songgao/water/syscalls_linux_legacy.go b/vendor/github.com/songgao/water/syscalls_linux_legacy.go index 8e8b2514e..6499b379a 100644 --- a/vendor/github.com/songgao/water/syscalls_linux_legacy.go +++ b/vendor/github.com/songgao/water/syscalls_linux_legacy.go @@ -1,4 +1,3 @@ -//go:build linux && !go1.11 // +build linux,!go1.11 package water diff --git a/vendor/github.com/songgao/water/syscalls_other.go b/vendor/github.com/songgao/water/syscalls_other.go index 50d72dbf1..c5ed1b371 100644 --- a/vendor/github.com/songgao/water/syscalls_other.go +++ b/vendor/github.com/songgao/water/syscalls_other.go @@ -1,4 +1,3 @@ -//go:build !linux && !darwin && !windows // +build !linux,!darwin,!windows package water diff --git a/vendor/github.com/stretchr/testify/require/require.go b/vendor/github.com/stretchr/testify/require/require.go index 8b365bef0..63f852147 100644 --- a/vendor/github.com/stretchr/testify/require/require.go +++ b/vendor/github.com/stretchr/testify/require/require.go @@ -6,11 +6,10 @@ package require import ( + assert "github.com/stretchr/testify/assert" http "net/http" url "net/url" time "time" - - assert "github.com/stretchr/testify/assert" ) // Condition uses a Comparison to assert a complex condition. diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go b/vendor/github.com/stretchr/testify/require/require_forward.go index 8009f7500..3b5b09330 100644 --- a/vendor/github.com/stretchr/testify/require/require_forward.go +++ b/vendor/github.com/stretchr/testify/require/require_forward.go @@ -6,11 +6,10 @@ package require import ( + assert "github.com/stretchr/testify/assert" http "net/http" url "net/url" time "time" - - assert "github.com/stretchr/testify/assert" ) // Condition uses a Comparison to assert a complex condition. diff --git a/vendor/github.com/syndtr/gocapability/capability/capability_noop.go b/vendor/github.com/syndtr/gocapability/capability/capability_noop.go index 21642feef..9bb3070c5 100644 --- a/vendor/github.com/syndtr/gocapability/capability/capability_noop.go +++ b/vendor/github.com/syndtr/gocapability/capability/capability_noop.go @@ -4,7 +4,6 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -//go:build !linux // +build !linux package capability diff --git a/vendor/github.com/templexxx/cpufeat/cpu_x86.go b/vendor/github.com/templexxx/cpufeat/cpu_x86.go index 741af3901..19d6d22ca 100644 --- a/vendor/github.com/templexxx/cpufeat/cpu_x86.go +++ b/vendor/github.com/templexxx/cpufeat/cpu_x86.go @@ -2,7 +2,6 @@ // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. -//go:build 386 || amd64 || amd64p32 // +build 386 amd64 amd64p32 package cpufeat diff --git a/vendor/github.com/templexxx/xor/xor_other.go b/vendor/github.com/templexxx/xor/xor_other.go index 5c39ea450..4aa2967c4 100644 --- a/vendor/github.com/templexxx/xor/xor_other.go +++ b/vendor/github.com/templexxx/xor/xor_other.go @@ -1,4 +1,3 @@ -//go:build !amd64 || noasm // +build !amd64 noasm package xor diff --git a/vendor/github.com/tjfoc/gmsm/sm4/sm4.go b/vendor/github.com/tjfoc/gmsm/sm4/sm4.go index 66f895eed..9956af2df 100644 --- a/vendor/github.com/tjfoc/gmsm/sm4/sm4.go +++ b/vendor/github.com/tjfoc/gmsm/sm4/sm4.go @@ -248,10 +248,14 @@ func (c *Sm4Cipher) Encrypt(dst, src []byte) { cryptBlock(c.subkeys, c.block1, c.block2, dst, src, false) } + + func (c *Sm4Cipher) Decrypt(dst, src []byte) { cryptBlock(c.subkeys, c.block1, c.block2, dst, src, true) } + + func xor(in, iv []byte) (out []byte) { if len(in) != len(iv) { return nil diff --git a/vendor/github.com/xtaci/kcp-go/readloop_generic.go b/vendor/github.com/xtaci/kcp-go/readloop_generic.go index 08e72cb8e..5dbe4f442 100644 --- a/vendor/github.com/xtaci/kcp-go/readloop_generic.go +++ b/vendor/github.com/xtaci/kcp-go/readloop_generic.go @@ -1,4 +1,3 @@ -//go:build !linux // +build !linux package kcp diff --git a/vendor/github.com/xtaci/kcp-go/readloop_linux.go b/vendor/github.com/xtaci/kcp-go/readloop_linux.go index ef08b2b2e..62264788b 100644 --- a/vendor/github.com/xtaci/kcp-go/readloop_linux.go +++ b/vendor/github.com/xtaci/kcp-go/readloop_linux.go @@ -1,4 +1,3 @@ -//go:build linux // +build linux package kcp diff --git a/vendor/github.com/xtaci/kcp-go/tx_generic.go b/vendor/github.com/xtaci/kcp-go/tx_generic.go index df33e5b5a..0b4f34941 100644 --- a/vendor/github.com/xtaci/kcp-go/tx_generic.go +++ b/vendor/github.com/xtaci/kcp-go/tx_generic.go @@ -1,4 +1,3 @@ -//go:build !linux // +build !linux package kcp diff --git a/vendor/github.com/xtaci/kcp-go/tx_linux.go b/vendor/github.com/xtaci/kcp-go/tx_linux.go index 2a0793e06..4f19df567 100644 --- a/vendor/github.com/xtaci/kcp-go/tx_linux.go +++ b/vendor/github.com/xtaci/kcp-go/tx_linux.go @@ -1,4 +1,3 @@ -//go:build linux // +build linux package kcp diff --git a/vendor/modules.txt b/vendor/modules.txt index c315b87ab..a443a5678 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -41,6 +41,9 @@ github.com/bitfield/script # github.com/blang/semver/v4 v4.0.0 ## explicit; go 1.14 github.com/blang/semver/v4 +# github.com/boltdb/bolt v1.3.1 +## explicit +github.com/boltdb/bolt # github.com/bytedance/sonic v1.10.0 ## explicit; go 1.16 github.com/bytedance/sonic @@ -188,7 +191,7 @@ github.com/itchyny/timefmt-go # github.com/ivanpirog/coloredcobra v1.0.1 ## explicit; go 1.15 github.com/ivanpirog/coloredcobra -# github.com/james-barrow/golang-ipc v1.2.4 +# github.com/james-barrow/golang-ipc v1.1.0 ## explicit; go 1.15 github.com/james-barrow/golang-ipc # github.com/jaypipes/ghw v0.12.0 From e8d98103d0556667e789ddf7f18ce94e67553aeb Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Wed, 30 Aug 2023 23:17:54 +0200 Subject: [PATCH 59/72] fix skywire.conf for latest commits --- skywire.conf | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/skywire.conf b/skywire.conf index 4c446df4f..630b39bd1 100644 --- a/skywire.conf +++ b/skywire.conf @@ -32,7 +32,7 @@ DISABLEPUBLICAUTOCONN="true" #VPNCLIENTAUTOSTART="false" #VPNSERVERPORT="44" #VPNSERVERAUTOSTART="false" -#SKYCHATARGS=("-addr" ":8001") +#SKYCHATARGS=("--httpport=:8001") #SKYCHATPORT="1" #SKYCHATAUTOSTART="false" #SKYSOCKSAUTOSTART="true" @@ -40,7 +40,7 @@ DISABLEPUBLICAUTOCONN="true" #SKYSOCKSCLIENTAUTOSTART="false" #SKYSOCKSCLIENTPORT="13" #APPLAUNCHERSERVERADDR="localhost:5505" -#APPSBINPATH="./apps", +#APPSBINPATH="./build/apps", #DISPLAYNODEIP="false" #ISHYPERVISOR=false HYPERVISORPKS=("027087fe40d97f7f0be4a0dc768462ddbb371d4b9e7679d4f11f117d757b9856ed") From 73c40a0d2733b4cf66b438df330c3e4024c0c2ea Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Wed, 30 Aug 2023 23:18:17 +0200 Subject: [PATCH 60/72] fix build path in Readme --- README.md | 30 +++++++++++++++++------------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/README.md b/README.md index d88cf5f11..5049790c4 100644 --- a/README.md +++ b/README.md @@ -120,25 +120,29 @@ git checkout develop make build1 ``` -To compile skywire directly from source archive, first download the latest source archive from the release section with your browser or another utility. Extract it with an archiving utility, enter the directory where the sources were extracted, and run `make build1`. +To compile skywire directly from source archive, first download the latest source archive from the release section with your browser or another utility. Extract it with an archiving utility, enter the directory where the sources were extracted, and run `make build`. -`make build1` builds the binaries and apps with `go build` +`make build` builds the binaries and apps with `go build` -`skywire-cli` and `skywire-visor` binaries will populate in the current directory; app binaries will populate the `apps` directory. +`skywire-cli` and `skywire-visor` binaries will populate in the `build` directory; app binaries will populate the `build\apps` directory. Build output: ``` -├──skywire-cli -└─┬skywire-visor - └─┬apps - ├──skychat - ├──skysocks - ├──skysocks-client - ├──vpn-client - ├──vpn-server - └──skychat +build +└─┬──setup-node + ├──skywire-cli + ├──skywire-systray + ├──skywire-visor + └─┬skywire + └─┬apps + ├──skychat + ├──skysocks + ├──skysocks-client + ├──vpn-client + ├──vpn-server + └──skychat ``` 'install' these executables to the `GOPATH`: @@ -153,7 +157,7 @@ For more options, run `make help`. To run skywire from this point, first generate a config. ``` -./skywire-cli config gen -birx +./build/skywire-cli config gen -birx ``` `-b --bestproto` use the best protocol (dmsg | direct) to connect to the skywire production deployment `-i --ishv` create a local hypervisor configuration From bdf0453850c0f2e229a7d4ec4aabbd1956411d58 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Thu, 31 Aug 2023 18:13:13 +0200 Subject: [PATCH 61/72] Add new Skychat Readme [WIP] --- cmd/apps/skychat/README.md | 217 +++++++++++++++++++++++++++++++------ 1 file changed, 181 insertions(+), 36 deletions(-) diff --git a/cmd/apps/skychat/README.md b/cmd/apps/skychat/README.md index 4a64bc5f9..160d22f8a 100644 --- a/cmd/apps/skychat/README.md +++ b/cmd/apps/skychat/README.md @@ -1,53 +1,198 @@ -# Skywire Chat app +# Skywire Chat App Chat implements basic text messaging between skywire visors. +It is possible to send messages p2p or in groups. + +The group feature is structured in a way that it is possible for everyone to host and join multiple servers. + +Those servers are structured like that: + + - Public Key of Visor + - Public Key of Server 1 + - Public Key of Room 1.1 + - Public Key of Room 1.2 + - ... + - Public Key of Server 2 + - Public Key of Room 2.1 + - Public Key of Room 2.2 + +And the chats are adressed with a so called public key route (pkroute): + - Route to a Room = [PK of Visor, PK of Server, PK of Room] + - P2P Route = [PK of Visor, PK of Visor, PK of Visor] + + Messaging UI is exposed via web interface. Chat only supports one WEB client user at a time. -## Local setup -Create 2 visor config files: +# Development Info +The app is written with 'Clean Architecture' based on the blog entry of Panayiotis Kritiotis [Clean Architecture in Go](https://pkritiotis.io/clean-architecture-in-golang/) + +To get a basic understanding on how it is structured, reading the blog will help. -`skywire1.json` +## Sequence Diagrams +### Init +```plantuml +@startuml +Main -> Main: flag.Parse() +Main -> Main: init Services +Main -> MessengerService.Listen: go +activate MessengerService.Listen +deactivate MessengerService.Listen -```json -{ - "apps": [ - { - "app": "skychat", - "version": "1.0", - "auto_start": true, - "port": 1 - } - ] -} +Main -> HTTPServer: ListenAndServe +activate HTTPServer +deactivate +@enduml ``` -`skywire2.json` - -```json -{ - "apps": [ - { - "app": "skychat", - "version": "1.0", - "auto_start": true, - "port": 1, - "args": ["-addr", ":8002"] - } - ] -} +### MessengerService.Listen +```plantuml +@startuml +box "MessengerService" +participant Listen +participant Handle +participant ErrorRoutine +end box + +Listen -> CliRepo: GetClient +CliRepo --> Listen: Client +Listen -> ErrorRoutine: go(error channel) +activate ErrorRoutine +deactivate +Listen -> Listen: for +activate Listen +Listen -> Listen: l.Accept() +Listen -> Listen: Client: AddConnection +Listen -> CliRepo: SetClient +CliRepo --> Listen: errSetClient +Listen -> Handle: go(cipher.PubKey) +activate Handle +deactivate +@enduml +``` + +### MessengerService.Handle +```plantuml +@startuml +box "MessengerService" +participant Handle +participant handleP2PMessage +participant handleRemoteServerMessage +participant handleLocalServerMessage +end box + +-> Handle: cipher.PubKey +Handle -> CliRepo: GetClient +CliRepo --> Handle: Client +Handle -> Handle: conn := Client.GetConn(cipher.PubKey) +Handle -> Handle: for +activate Handle +Handle -> Handle: err := conn.Read(buf) +alt #Pink err != nil + Handle -> Handle: Client.DeleteConn(cipher.PubKey) +else #LightBlue err = nil + Handle -> Handle: json.Unmarshal(buf) + alt P2P + Handle -> handleP2PMessage: go (Message) + activate handleP2PMessage + deactivate handleP2PMessage + else RemoteServerMessage + Handle -> handleRemoteServerMessage: go (Message) + activate handleRemoteServerMessage + deactivate handleRemoteServerMessage + else LocalServerMessage + Handle -> handleLocalServerMessage: go (Message) + activate handleLocalServerMessage + deactivate handleLocalServerMessage + end +end +deactivate +@enduml ``` +### MessengerService.handleP2PMessage +```plantuml +@startuml +participant Alice.Notification order 9 +participant Alice.VisorRepo order 10 +participant Alice order 20 +participant Alice2.VisorRepo order 25 +participant Alice2 order 25 +participant Bob order 30 +participant Bob.VisorRepo order 40 +participant Bob.Notification order 50 +== Handling ChatRequest == +Alice -> Bob: ChatRequestMessage +activate Bob +alt NotInBlacklist + Bob <-> Bob.VisorRepo: visor = GetByPK + Bob -> Bob: visor.AddMessage + Bob -> Bob.VisorRepo: SetVisor + Bob -> Bob.Notification: NewP2PChatNotification & Notify + Bob -> Alice: ChatAcceptMessage + activate Alice + Bob -> Alice2: InfoMessage + deactivate Bob + activate Alice2 + Alice2 -> Alice2: visor.SetRouteInfo + Alice2 -> Alice2.VisorRepo: SetVisor + Alice2 -> Alice.Notification: NewMsgNotification & Notify + deactivate Alice2 + Alice <-> Alice.VisorRepo: visor = GetByPK + Alice -> Alice: visor.AddMessage + Alice -> Alice.VisorRepo: SetVisor + Alice -> Alice.Notification: NewMsgNotification & Notify + Alice -> Bob: InfoMessage + deactivate Alice + activate Bob + Bob -> Bob: visor.SetRouteInfo + Bob -> Bob.VisorRepo: SetVisor + Bob -> Bob.Notification: NewMsgNotification & Notify + deactivate Bob + deactivate Alice2 +else InBlacklist + Bob -> Alice: ChatRejectMessage + activate Bob + activate Alice + Bob -> Bob.VisorRepo: GetByPK + Bob.VisorRepo --> Bob: Visor + Bob -> Bob.VisorRepo: if no server of visor DeleteVisor + deactivate Bob + Alice <-> Alice.VisorRepo: visor = GetByPK + Alice -> Alice: visor.AddMessage + Alice -> Alice.VisorRepo: SetVisor + Alice -> Alice.Notification: NewMsgNotification & Notify + deactivate Alice +end + +== Handling Text Messages == +Alice -> Bob: TextMessage +activate Bob +Bob -> Bob: visor.AddMessage +Bob -> Bob.VisorRepo: SetVisor +Bob -> Bob.Notification: NewMsgNotification & Notify +deactivate Bob -Compile binaries and start 2 visors: +== Handling Info Messages == +Alice -> Bob: InfoMessage +activate Bob +Bob -> Bob: visor.AddMessage +Bob -> Bob.VisorRepo: SetVisor +Bob -> Bob: json.Unmarshal -> to info.Info +Bob -> Bob: visor.SetRouteInfo(info) +Bob -> Bob.VisorRepo: SetVisor +Bob -> Bob.Notification: NewMsgNotification & Notify +deactivate Bob -```bash -$ go build -o ./build/apps/skychat.v1.0 ./cmd/apps/skychat -$ cd ./build -$ ./skywire-visor skywire1.json -$ ./skywire-visor skywire2.json +@enduml ``` -Chat interface will be available on ports `8001` and `8002`. +### MessengerService.handleRemoteServerMessage (This is the client-side handling of servers) +TODO +### MessengerService.handleLocalServerMessage (This is the server-side handling of servers) +TODO + +### Usecases +TODO From 828a5f67afd663253ea6a15c2d6861e57e34b244 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Thu, 31 Aug 2023 23:26:36 +0200 Subject: [PATCH 62/72] first try to implement plantuml rendering into skychat readme --- cmd/apps/skychat/README.md | 154 +----------------- cmd/apps/skychat/doc/init.iuml | 11 ++ .../skychat/doc/messengerServiceHandle.iuml | 35 ++++ .../doc/messengerServiceHandleP2PMessage | 73 +++++++++ .../skychat/doc/messengerServiceListen.iuml | 22 +++ 5 files changed, 146 insertions(+), 149 deletions(-) create mode 100644 cmd/apps/skychat/doc/init.iuml create mode 100644 cmd/apps/skychat/doc/messengerServiceHandle.iuml create mode 100644 cmd/apps/skychat/doc/messengerServiceHandleP2PMessage create mode 100644 cmd/apps/skychat/doc/messengerServiceListen.iuml diff --git a/cmd/apps/skychat/README.md b/cmd/apps/skychat/README.md index 160d22f8a..86288590a 100644 --- a/cmd/apps/skychat/README.md +++ b/cmd/apps/skychat/README.md @@ -34,160 +34,16 @@ To get a basic understanding on how it is structured, reading the blog will help ## Sequence Diagrams ### Init -```plantuml -@startuml -Main -> Main: flag.Parse() -Main -> Main: init Services -Main -> MessengerService.Listen: go -activate MessengerService.Listen -deactivate MessengerService.Listen - -Main -> HTTPServer: ListenAndServe -activate HTTPServer -deactivate -@enduml -``` +![Init](http://plantuml.com/plantuml/proxy?cache=no&src=https://github.com/4rchim3d3s/skywire-mainnet/tree/feature/skychat/cmd/apps/skychat/doc/init.iuml) ### MessengerService.Listen -```plantuml -@startuml -box "MessengerService" -participant Listen -participant Handle -participant ErrorRoutine -end box - -Listen -> CliRepo: GetClient -CliRepo --> Listen: Client -Listen -> ErrorRoutine: go(error channel) -activate ErrorRoutine -deactivate -Listen -> Listen: for -activate Listen -Listen -> Listen: l.Accept() -Listen -> Listen: Client: AddConnection -Listen -> CliRepo: SetClient -CliRepo --> Listen: errSetClient -Listen -> Handle: go(cipher.PubKey) -activate Handle -deactivate -@enduml -``` +![MessengerService.Listen](http://plantuml.com/plantuml/proxy?cache=no&src=https://github.com/4rchim3d3s/skywire-mainnet/tree/feature/skychat/cmd/apps/skychat/doc/messengerServiceListen.iuml) ### MessengerService.Handle -```plantuml -@startuml -box "MessengerService" -participant Handle -participant handleP2PMessage -participant handleRemoteServerMessage -participant handleLocalServerMessage -end box - --> Handle: cipher.PubKey -Handle -> CliRepo: GetClient -CliRepo --> Handle: Client -Handle -> Handle: conn := Client.GetConn(cipher.PubKey) -Handle -> Handle: for -activate Handle -Handle -> Handle: err := conn.Read(buf) -alt #Pink err != nil - Handle -> Handle: Client.DeleteConn(cipher.PubKey) -else #LightBlue err = nil - Handle -> Handle: json.Unmarshal(buf) - alt P2P - Handle -> handleP2PMessage: go (Message) - activate handleP2PMessage - deactivate handleP2PMessage - else RemoteServerMessage - Handle -> handleRemoteServerMessage: go (Message) - activate handleRemoteServerMessage - deactivate handleRemoteServerMessage - else LocalServerMessage - Handle -> handleLocalServerMessage: go (Message) - activate handleLocalServerMessage - deactivate handleLocalServerMessage - end -end -deactivate -@enduml -``` +![Init](http://plantuml.com/plantuml/proxy?cache=no&src=https://github.com/4rchim3d3s/skywire-mainnet/tree/feature/skychat/cmd/apps/skychat/doc/messengerServiceHandle.iuml) + ### MessengerService.handleP2PMessage -```plantuml -@startuml -participant Alice.Notification order 9 -participant Alice.VisorRepo order 10 -participant Alice order 20 -participant Alice2.VisorRepo order 25 -participant Alice2 order 25 -participant Bob order 30 -participant Bob.VisorRepo order 40 -participant Bob.Notification order 50 -== Handling ChatRequest == -Alice -> Bob: ChatRequestMessage -activate Bob -alt NotInBlacklist - Bob <-> Bob.VisorRepo: visor = GetByPK - Bob -> Bob: visor.AddMessage - Bob -> Bob.VisorRepo: SetVisor - Bob -> Bob.Notification: NewP2PChatNotification & Notify - Bob -> Alice: ChatAcceptMessage - activate Alice - Bob -> Alice2: InfoMessage - deactivate Bob - activate Alice2 - Alice2 -> Alice2: visor.SetRouteInfo - Alice2 -> Alice2.VisorRepo: SetVisor - Alice2 -> Alice.Notification: NewMsgNotification & Notify - deactivate Alice2 - Alice <-> Alice.VisorRepo: visor = GetByPK - Alice -> Alice: visor.AddMessage - Alice -> Alice.VisorRepo: SetVisor - Alice -> Alice.Notification: NewMsgNotification & Notify - Alice -> Bob: InfoMessage - deactivate Alice - activate Bob - Bob -> Bob: visor.SetRouteInfo - Bob -> Bob.VisorRepo: SetVisor - Bob -> Bob.Notification: NewMsgNotification & Notify - deactivate Bob - deactivate Alice2 -else InBlacklist - Bob -> Alice: ChatRejectMessage - activate Bob - activate Alice - Bob -> Bob.VisorRepo: GetByPK - Bob.VisorRepo --> Bob: Visor - Bob -> Bob.VisorRepo: if no server of visor DeleteVisor - deactivate Bob - Alice <-> Alice.VisorRepo: visor = GetByPK - Alice -> Alice: visor.AddMessage - Alice -> Alice.VisorRepo: SetVisor - Alice -> Alice.Notification: NewMsgNotification & Notify - deactivate Alice -end - -== Handling Text Messages == -Alice -> Bob: TextMessage -activate Bob -Bob -> Bob: visor.AddMessage -Bob -> Bob.VisorRepo: SetVisor -Bob -> Bob.Notification: NewMsgNotification & Notify -deactivate Bob - -== Handling Info Messages == -Alice -> Bob: InfoMessage -activate Bob -Bob -> Bob: visor.AddMessage -Bob -> Bob.VisorRepo: SetVisor -Bob -> Bob: json.Unmarshal -> to info.Info -Bob -> Bob: visor.SetRouteInfo(info) -Bob -> Bob.VisorRepo: SetVisor -Bob -> Bob.Notification: NewMsgNotification & Notify -deactivate Bob - -@enduml -``` +![Init](http://plantuml.com/plantuml/proxy?cache=no&src=https://github.com/4rchim3d3s/skywire-mainnet/tree/feature/skychat/cmd/apps/skychat/doc/messengerServiceHandleP2PMessage.iuml) ### MessengerService.handleRemoteServerMessage (This is the client-side handling of servers) TODO diff --git a/cmd/apps/skychat/doc/init.iuml b/cmd/apps/skychat/doc/init.iuml new file mode 100644 index 000000000..3521a0f0b --- /dev/null +++ b/cmd/apps/skychat/doc/init.iuml @@ -0,0 +1,11 @@ +@startuml +Main -> Main: flag.Parse() +Main -> Main: init Services +Main -> MessengerService.Listen: go +activate MessengerService.Listen +deactivate MessengerService.Listen + +Main -> HTTPServer: ListenAndServe +activate HTTPServer +deactivate +@enduml \ No newline at end of file diff --git a/cmd/apps/skychat/doc/messengerServiceHandle.iuml b/cmd/apps/skychat/doc/messengerServiceHandle.iuml new file mode 100644 index 000000000..761b20a15 --- /dev/null +++ b/cmd/apps/skychat/doc/messengerServiceHandle.iuml @@ -0,0 +1,35 @@ +@startuml +box "MessengerService" +participant Handle +participant handleP2PMessage +participant handleRemoteServerMessage +participant handleLocalServerMessage +end box + +-> Handle: cipher.PubKey +Handle -> CliRepo: GetClient +CliRepo --> Handle: Client +Handle -> Handle: conn := Client.GetConn(cipher.PubKey) +Handle -> Handle: for +activate Handle +Handle -> Handle: err := conn.Read(buf) +alt #Pink err != nil + Handle -> Handle: Client.DeleteConn(cipher.PubKey) +else #LightBlue err = nil + Handle -> Handle: json.Unmarshal(buf) + alt P2P + Handle -> handleP2PMessage: go (Message) + activate handleP2PMessage + deactivate handleP2PMessage + else RemoteServerMessage + Handle -> handleRemoteServerMessage: go (Message) + activate handleRemoteServerMessage + deactivate handleRemoteServerMessage + else LocalServerMessage + Handle -> handleLocalServerMessage: go (Message) + activate handleLocalServerMessage + deactivate handleLocalServerMessage + end +end +deactivate +@enduml \ No newline at end of file diff --git a/cmd/apps/skychat/doc/messengerServiceHandleP2PMessage b/cmd/apps/skychat/doc/messengerServiceHandleP2PMessage new file mode 100644 index 000000000..9a461ba92 --- /dev/null +++ b/cmd/apps/skychat/doc/messengerServiceHandleP2PMessage @@ -0,0 +1,73 @@ +@startuml +participant Alice.Notification order 9 +participant Alice.VisorRepo order 10 +participant Alice order 20 +participant Alice2.VisorRepo order 25 +participant Alice2 order 25 +participant Bob order 30 +participant Bob.VisorRepo order 40 +participant Bob.Notification order 50 +== Handling ChatRequest == +Alice -> Bob: ChatRequestMessage +activate Bob +alt NotInBlacklist + Bob <-> Bob.VisorRepo: visor = GetByPK + Bob -> Bob: visor.AddMessage + Bob -> Bob.VisorRepo: SetVisor + Bob -> Bob.Notification: NewP2PChatNotification & Notify + Bob -> Alice: ChatAcceptMessage + activate Alice + Bob -> Alice2: InfoMessage + deactivate Bob + activate Alice2 + Alice2 -> Alice2: visor.SetRouteInfo + Alice2 -> Alice2.VisorRepo: SetVisor + Alice2 -> Alice.Notification: NewMsgNotification & Notify + deactivate Alice2 + Alice <-> Alice.VisorRepo: visor = GetByPK + Alice -> Alice: visor.AddMessage + Alice -> Alice.VisorRepo: SetVisor + Alice -> Alice.Notification: NewMsgNotification & Notify + Alice -> Bob: InfoMessage + deactivate Alice + activate Bob + Bob -> Bob: visor.SetRouteInfo + Bob -> Bob.VisorRepo: SetVisor + Bob -> Bob.Notification: NewMsgNotification & Notify + deactivate Bob + deactivate Alice2 +else InBlacklist + Bob -> Alice: ChatRejectMessage + activate Bob + activate Alice + Bob -> Bob.VisorRepo: GetByPK + Bob.VisorRepo --> Bob: Visor + Bob -> Bob.VisorRepo: if no server of visor DeleteVisor + deactivate Bob + Alice <-> Alice.VisorRepo: visor = GetByPK + Alice -> Alice: visor.AddMessage + Alice -> Alice.VisorRepo: SetVisor + Alice -> Alice.Notification: NewMsgNotification & Notify + deactivate Alice +end + +== Handling Text Messages == +Alice -> Bob: TextMessage +activate Bob +Bob -> Bob: visor.AddMessage +Bob -> Bob.VisorRepo: SetVisor +Bob -> Bob.Notification: NewMsgNotification & Notify +deactivate Bob + +== Handling Info Messages == +Alice -> Bob: InfoMessage +activate Bob +Bob -> Bob: visor.AddMessage +Bob -> Bob.VisorRepo: SetVisor +Bob -> Bob: json.Unmarshal -> to info.Info +Bob -> Bob: visor.SetRouteInfo(info) +Bob -> Bob.VisorRepo: SetVisor +Bob -> Bob.Notification: NewMsgNotification & Notify +deactivate Bob + +@enduml \ No newline at end of file diff --git a/cmd/apps/skychat/doc/messengerServiceListen.iuml b/cmd/apps/skychat/doc/messengerServiceListen.iuml new file mode 100644 index 000000000..a90b1d10b --- /dev/null +++ b/cmd/apps/skychat/doc/messengerServiceListen.iuml @@ -0,0 +1,22 @@ +@startuml +box "MessengerService" +participant Listen +participant Handle +participant ErrorRoutine +end box + +Listen -> CliRepo: GetClient +CliRepo --> Listen: Client +Listen -> ErrorRoutine: go(error channel) +activate ErrorRoutine +deactivate +Listen -> Listen: for +activate Listen +Listen -> Listen: l.Accept() +Listen -> Listen: Client: AddConnection +Listen -> CliRepo: SetClient +CliRepo --> Listen: errSetClient +Listen -> Handle: go(cipher.PubKey) +activate Handle +deactivate +@enduml \ No newline at end of file From 356d2f187155575dd4236d65b22a13b970e33ca4 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Thu, 31 Aug 2023 23:29:32 +0200 Subject: [PATCH 63/72] skychat: next try rendering plantuml inside readme --- cmd/apps/skychat/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cmd/apps/skychat/README.md b/cmd/apps/skychat/README.md index 86288590a..1c12e7364 100644 --- a/cmd/apps/skychat/README.md +++ b/cmd/apps/skychat/README.md @@ -34,16 +34,16 @@ To get a basic understanding on how it is structured, reading the blog will help ## Sequence Diagrams ### Init -![Init](http://plantuml.com/plantuml/proxy?cache=no&src=https://github.com/4rchim3d3s/skywire-mainnet/tree/feature/skychat/cmd/apps/skychat/doc/init.iuml) +![Init](http://plantuml.com/plantuml/proxy?cache=no&src=https://raw.githubusercontent.com/4rchim3d3s/skywire-mainnet/feature/skychat/cmd/apps/skychat/doc/init.iuml) ### MessengerService.Listen -![MessengerService.Listen](http://plantuml.com/plantuml/proxy?cache=no&src=https://github.com/4rchim3d3s/skywire-mainnet/tree/feature/skychat/cmd/apps/skychat/doc/messengerServiceListen.iuml) +![MessengerService.Listen](http://plantuml.com/plantuml/proxy?cache=no&src=https://raw.githubusercontent.com/4rchim3d3s/skywire-mainnet/feature/skychat/cmd/apps/skychat/doc/messengerServiceListen.iuml) ### MessengerService.Handle -![Init](http://plantuml.com/plantuml/proxy?cache=no&src=https://github.com/4rchim3d3s/skywire-mainnet/tree/feature/skychat/cmd/apps/skychat/doc/messengerServiceHandle.iuml) +![Init](http://plantuml.com/plantuml/proxy?cache=no&src=https://raw.githubusercontent.com/4rchim3d3s/skywire-mainnet/feature/skychat/cmd/apps/skychat/doc/messengerServiceHandle.iuml) ### MessengerService.handleP2PMessage -![Init](http://plantuml.com/plantuml/proxy?cache=no&src=https://github.com/4rchim3d3s/skywire-mainnet/tree/feature/skychat/cmd/apps/skychat/doc/messengerServiceHandleP2PMessage.iuml) +![Init](http://plantuml.com/plantuml/proxy?cache=no&src=https://raw.githubusercontent.com/4rchim3d3s/skywire-mainnet/feature/skychat/cmd/apps/skychat/doc/messengerServiceHandleP2PMessage.iuml) ### MessengerService.handleRemoteServerMessage (This is the client-side handling of servers) TODO From e176874b6f7c71220470f65b7c0dfff613c696f6 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Thu, 31 Aug 2023 23:31:17 +0200 Subject: [PATCH 64/72] skychat: fix file ending for plantuml rendering inside readme --- ...viceHandleP2PMessage => messengerServiceHandleP2PMessage.iuml} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename cmd/apps/skychat/doc/{messengerServiceHandleP2PMessage => messengerServiceHandleP2PMessage.iuml} (100%) diff --git a/cmd/apps/skychat/doc/messengerServiceHandleP2PMessage b/cmd/apps/skychat/doc/messengerServiceHandleP2PMessage.iuml similarity index 100% rename from cmd/apps/skychat/doc/messengerServiceHandleP2PMessage rename to cmd/apps/skychat/doc/messengerServiceHandleP2PMessage.iuml From 1080855a21cf869d77d3a18c844c9caafcbdd92b Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Mon, 11 Mar 2024 22:49:25 +0100 Subject: [PATCH 65/72] websockets for notifications & refactoring for future implementation of dmsg --- .../connectionhandler/connection_handler.go | 18 +++ .../internal/app/messenger/messenger.go | 5 +- .../skychat/internal/inputports/cli/root.go | 12 +- .../http/notification.go/handler.go | 48 ------- .../inputports/http/notification.go/sse.go | 51 +++++++ .../http/notification.go/websocket.go | 75 +++++++++++ .../internal/inputports/http/server.go | 24 +++- .../internal/inputports/http/static/index.js | 41 ++++-- .../skychat/internal/inputports/rpc/client.go | 8 +- .../skychat/internal/inputports/rpc/server.go | 11 +- .../skychat/internal/inputports/services.go | 8 +- .../netcon/messenger_service.go | 124 +++++------------- .../messenger/messenger_service.go | 114 ++++++++++++++++ .../messenger_service_local_server.go | 2 +- .../{netcon => }/messenger_service_p2p.go | 2 +- .../messenger_service_remote_server.go | 2 +- .../messenger_service_send_messages.go | 2 +- .../internal/interfaceadapters/services.go | 33 +++-- cmd/apps/skychat/skychat.go | 8 -- 19 files changed, 389 insertions(+), 199 deletions(-) create mode 100644 cmd/apps/skychat/internal/app/connectionhandler/connection_handler.go create mode 100644 cmd/apps/skychat/internal/inputports/http/notification.go/sse.go create mode 100644 cmd/apps/skychat/internal/inputports/http/notification.go/websocket.go rename cmd/apps/skychat/internal/interfaceadapters/{messenger => connectionhandler}/netcon/messenger_service.go (70%) create mode 100644 cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service.go rename cmd/apps/skychat/internal/interfaceadapters/messenger/{netcon => }/messenger_service_local_server.go (99%) rename cmd/apps/skychat/internal/interfaceadapters/messenger/{netcon => }/messenger_service_p2p.go (99%) rename cmd/apps/skychat/internal/interfaceadapters/messenger/{netcon => }/messenger_service_remote_server.go (99%) rename cmd/apps/skychat/internal/interfaceadapters/messenger/{netcon => }/messenger_service_send_messages.go (99%) diff --git a/cmd/apps/skychat/internal/app/connectionhandler/connection_handler.go b/cmd/apps/skychat/internal/app/connectionhandler/connection_handler.go new file mode 100644 index 000000000..58183e343 --- /dev/null +++ b/cmd/apps/skychat/internal/app/connectionhandler/connection_handler.go @@ -0,0 +1,18 @@ +// Package connectionhandler contains the interface Service required by the chat app +package connectionhandler + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// Service interface is the interface to the service +type Service interface { + HandleConnection(pk cipher.PubKey) + DeleteConnFromHandled(pk cipher.PubKey) error //TODO: refactor to better handling -> this is not beautiful + Listen() + + GetReceiveChannel() chan message.Message + SendMessage(pkroute util.PKRoute, m message.Message, addToDatabase bool) error +} diff --git a/cmd/apps/skychat/internal/app/messenger/messenger.go b/cmd/apps/skychat/internal/app/messenger/messenger.go index 797c18cf4..9a25210f5 100644 --- a/cmd/apps/skychat/internal/app/messenger/messenger.go +++ b/cmd/apps/skychat/internal/app/messenger/messenger.go @@ -4,14 +4,13 @@ package messenger import ( "github.com/skycoin/skywire-utilities/pkg/cipher" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/info" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" ) // Service interface is the interface to the service type Service interface { - HandleConnection(pk cipher.PubKey) - DeleteConnFromHandled(pk cipher.PubKey) error //TODO: refactor to better handling -> this is not beautiful - Listen() + HandleReceivedMessage(message.Message) error //only used as client/p2p SendRouteRequestMessage(route util.PKRoute) error diff --git a/cmd/apps/skychat/internal/inputports/cli/root.go b/cmd/apps/skychat/internal/inputports/cli/root.go index 7c1b7a80d..3b39516eb 100644 --- a/cmd/apps/skychat/internal/inputports/cli/root.go +++ b/cmd/apps/skychat/internal/inputports/cli/root.go @@ -45,17 +45,16 @@ var rootCmd = &cobra.Command{ interfaceadapters.InterfaceAdapterServices.NotificationService, interfaceadapters.InterfaceAdapterServices.MessengerService) - inputports.InputportsServices = inputports.NewServices(app.AppServices) + inputports.InputportsServices = inputports.NewServices(app.AppServices, httpport, rpcport) - //messengerService listen - go interfaceadapters.InterfaceAdapterServices.MessengerService.Listen() + //connectionHandlerService listen + go interfaceadapters.InterfaceAdapterServices.ConnectionHandlerService.Listen() //rpc-server for cli functionality - rpcport = ":4040" - go inputports.InputportsServices.RPCServer.ListenAndServe(&rpcport) + go inputports.InputportsServices.RPCServer.ListenAndServe() //http-server for web-ui - inputports.InputportsServices.HTTPServer.ListenAndServe(&httpport) + inputports.InputportsServices.HTTPServer.ListenAndServe() }, } @@ -70,6 +69,7 @@ func init() { rootCmd.PersistentFlags().MarkHidden("help") //nolint rootCmd.Flags().StringVar(&httpport, "httpport", ":8001", "port to bind") + rootCmd.Flags().StringVar(&rpcport, "rpcport", ":4040", "port to bind") } // Execute executes root CLI command. diff --git a/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go b/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go index 7577a2393..468cdbb10 100644 --- a/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go +++ b/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go @@ -2,9 +2,6 @@ package notification import ( - "fmt" - "net/http" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" ) @@ -17,48 +14,3 @@ type Handler struct { func NewHandler(ns notification.Service) *Handler { return &Handler{ns: ns} } - -// SubscribeNotifications sends all received msgs from channel to http -func (c Handler) SubscribeNotifications(w http.ResponseWriter, r *http.Request) { - - fmt.Println("Get handshake from client") - - // prepare the flusher - f, ok := w.(http.Flusher) - if !ok { - http.Error(w, "Streaming unsupported!", http.StatusInternalServerError) - return - } - - // prepare the header - w.Header().Set("Content-Type", "text/event-stream") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - w.Header().Set("Transfer-Encoding", "chunked") - w.Header().Set("Access-Control-Allow-Origin", "*") - - // instantiate the channel - c.ns.InitChannel() - - // close the channel after exit the function - defer func() { - c.ns.DeferChannel() - }() - - for { - select { - case <-r.Context().Done(): - fmt.Println("SSE: connection was closed.") - return - - default: - msg, ok := <-c.ns.GetChannel() - if !ok { - fmt.Println("GetChannel not ok") - return - } - fmt.Fprintf(w, "data: %s\n\n", msg) - f.Flush() - } - } -} diff --git a/cmd/apps/skychat/internal/inputports/http/notification.go/sse.go b/cmd/apps/skychat/internal/inputports/http/notification.go/sse.go new file mode 100644 index 000000000..277c1bb87 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/notification.go/sse.go @@ -0,0 +1,51 @@ +package notification + +import ( + "fmt" + "net/http" +) + +// SubscribeNotificationsSSE sends all notifications from the app to http as sse +func (c Handler) SubscribeNotificationsSSE(w http.ResponseWriter, r *http.Request) { + + fmt.Println("Get handshake from client") + + // prepare the flusher + f, ok := w.(http.Flusher) + if !ok { + http.Error(w, "Streaming unsupported!", http.StatusInternalServerError) + return + } + + // prepare the header + w.Header().Set("Access-Control-Allow-Origin", "*") + w.Header().Set("Access-Control-Allow-Methods", "GET") + w.Header().Set("Access-Control-Expose-Headers", "Content-Type") + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-cache") + w.Header().Set("Connection", "keep-alive") + w.Header().Set("Transfer-Encoding", "chunked") + + // instantiate the channel + c.ns.InitChannel() + + // close the channel after exit the function + defer func() { + c.ns.DeferChannel() + }() + + for { + select { + case msg, ok := <-c.ns.GetChannel(): + if !ok { + fmt.Println("GetChannel not ok") + return + } + fmt.Fprintf(w, "data: %s\n\n", msg) + f.Flush() + case <-r.Context().Done(): + fmt.Println("SSE: connection was closed.") + return + } + } +} diff --git a/cmd/apps/skychat/internal/inputports/http/notification.go/websocket.go b/cmd/apps/skychat/internal/inputports/http/notification.go/websocket.go new file mode 100644 index 000000000..a77177cb2 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/notification.go/websocket.go @@ -0,0 +1,75 @@ +package notification + +import ( + "fmt" + "log" + "net/http" + + "github.com/gorilla/websocket" +) + +type appwebsocket struct { + con *websocket.Conn +} + +var upgrader = websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, +} + +var savedsocketreader []*appwebsocket + +// SubscribeNotificationsWebsocket sends all notifications from the app to a websocket +func (c Handler) SubscribeNotificationsWebsocket(w http.ResponseWriter, r *http.Request) { + log.Println("socket request") + if savedsocketreader == nil { + savedsocketreader = make([]*appwebsocket, 0) + } + + defer func() { + err := recover() + if err != nil { + log.Println(err) + } + err = r.Body.Close() + if err != nil { + log.Println(err) + } + + }() + con, err := upgrader.Upgrade(w, r, nil) + if err != nil { + log.Println(err) + } + + ptrSocketReader := &appwebsocket{ + con: con, + } + + savedsocketreader = append(savedsocketreader, ptrSocketReader) + + // instantiate the channel + c.ns.InitChannel() + + // close the channel after exit the function + defer func() { + c.ns.DeferChannel() + }() + + for { + select { + case msg, ok := <-c.ns.GetChannel(): + if !ok { + fmt.Println("GetChannel not ok") + return + } + err := ptrSocketReader.con.WriteMessage(websocket.TextMessage, []byte(msg)) + if err != nil { + log.Println(err) + } + case <-r.Context().Done(): + fmt.Println("SSE: connection was closed.") + return + } + } +} diff --git a/cmd/apps/skychat/internal/inputports/http/server.go b/cmd/apps/skychat/internal/inputports/http/server.go index a97663b83..f568f019f 100644 --- a/cmd/apps/skychat/internal/inputports/http/server.go +++ b/cmd/apps/skychat/internal/inputports/http/server.go @@ -26,11 +26,14 @@ var embededFiles embed.FS type Server struct { appServices app.Services router *mux.Router + port string } // NewServer HTTP Server constructor -func NewServer(appServices app.Services) *Server { +func NewServer(appServices app.Services, port string) *Server { httpServer := &Server{appServices: appServices} + httpServer.port = port + httpServer.router = mux.NewRouter() httpServer.router.Handle("/", http.FileServer(getFileSystem())) httpServer.router.Handle("/favicon.ico", http.FileServer(getFileSystem())) @@ -96,14 +99,15 @@ func (httpServer *Server) AddUserHTTPRoutes() { func (httpServer *Server) AddNotificationHTTPRoutes() { const notificationHTTPRoutePath = "/notifications" // - httpServer.router.HandleFunc(notificationHTTPRoutePath, notification.NewHandler(httpServer.appServices.NotificationService).SubscribeNotifications).Methods("GET") + httpServer.router.HandleFunc(notificationHTTPRoutePath, notification.NewHandler(httpServer.appServices.NotificationService).SubscribeNotificationsWebsocket).Methods("GET") + httpServer.router.HandleFunc(notificationHTTPRoutePath+"/"+"websocket", httpServer.getPort).Methods("GET") } // ListenAndServe Starts listening for requests -func (httpServer *Server) ListenAndServe(addr *string) { - fmt.Println("Serving HTTP on", *addr) +func (httpServer *Server) ListenAndServe() { + fmt.Println("Serving HTTP on", httpServer.port) srv := &http.Server{ - Addr: *addr, + Addr: httpServer.port, ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, } @@ -121,3 +125,13 @@ func getFileSystem() http.FileSystem { return http.FS(fsys) } + +func (httpServer *Server) getPort(w http.ResponseWriter, _ *http.Request) { + + _, err := w.Write([]byte(httpServer.port)) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } +} diff --git a/cmd/apps/skychat/internal/inputports/http/static/index.js b/cmd/apps/skychat/internal/inputports/http/static/index.js index 223642af3..457ca97c9 100644 --- a/cmd/apps/skychat/internal/inputports/http/static/index.js +++ b/cmd/apps/skychat/internal/inputports/http/static/index.js @@ -346,10 +346,12 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa if (!test) { return Promise.all([this.getUserInfo(), this.getUserSettings(), - this.getChatAll() - ]).then(([userInfo,userSettings,chats]) => { + this.getChatAll(), + this.getWebsocketPort() + ]).then(([userInfo,userSettings,chats,port]) => { this.user = new User(userInfo,userSettings); this.chats = chats + this.port = port return this.init() }); } @@ -376,8 +378,8 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa if (this.chats != null){ this.chats.forEach(r => this._addChat(r)); } - - this.notificationsSubscribe(); + + this.notificationsSubscribe(this.port); return this; } @@ -813,6 +815,7 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa }); } + //// PUT setUserInfo(el){ let info = new Info(this.user.info.pk, el[0].value.trim(), el[1].value.trim(), el[2].value.trim()); @@ -1251,9 +1254,25 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa //// HTTP /notification ///////////////////////////////////////////////////////////// //// Subscribe - notificationsSubscribe() { - const source = new EventSource('/notifications'); - source.onmessage = async(event) => { + + + async getWebsocketPort() { + return fetch('notifications/websocket', { method: 'GET', body: null }) + .then(async res => { + if (res.ok) { + return res.text().then(text => { + return text; + }); + } else { + res.text().then(text => alert(`Failed to get websocket`)); + } + }); + } + + notificationsSubscribe(port) { + var socket = new WebSocket('ws://localhost'+ port + '/notifications'); + + socket.onmessage = async(event) => { const data = JSON.parse(event.data); console.log(data) console.log("Notification DataType: " + data.type) @@ -1303,9 +1322,15 @@ dummyChatP2P2 = new Room(dummyChatP2P2Route,dummyChatP2P2Info,dummyChatP2P2Messa break; } } - source.onerror = async(event) => { + socket.onerror = async(event) => { console.error("EventSource failed:", event) } + socket.onclose = async() => { + console.log("socket opened") + } + socket.onclose = async() => { + console.log("socket closed") + } }; ///////////////////////////////////////////////////////////// diff --git a/cmd/apps/skychat/internal/inputports/rpc/client.go b/cmd/apps/skychat/internal/inputports/rpc/client.go index ee40fa666..b0024317a 100644 --- a/cmd/apps/skychat/internal/inputports/rpc/client.go +++ b/cmd/apps/skychat/internal/inputports/rpc/client.go @@ -13,19 +13,19 @@ import ( // Client represents the rpc client running for this service type Client struct { appServices app.Services + rpcPort string } // NewClient RPC Client constructor -func NewClient(appServices app.Services) *Client { - rc := &Client{appServices: appServices} +func NewClient(appServices app.Services, rpcPort string) *Client { + rc := &Client{appServices: appServices, rpcPort: rpcPort} return rc } // SendTextMessage sends the command to send a message via rpc func (c *Client) SendTextMessage(VisorPk cipher.PubKey, ServerPk cipher.PubKey, RoomPk cipher.PubKey, Message string) error { - //TODO: fix so that rpc address is dynamic from cobra args here. - rpcClient, err := rpc.DialHTTP("tcp", ":4040") + rpcClient, err := rpc.DialHTTP("tcp", c.rpcPort) if err != nil { log.Fatal("Connection error: ", err) } diff --git a/cmd/apps/skychat/internal/inputports/rpc/server.go b/cmd/apps/skychat/internal/inputports/rpc/server.go index 357e3b659..8a1911af8 100644 --- a/cmd/apps/skychat/internal/inputports/rpc/server.go +++ b/cmd/apps/skychat/internal/inputports/rpc/server.go @@ -18,18 +18,19 @@ import ( type Server struct { appServices app.Services router *mux.Router + rpcPort string } // NewServer RPC Server constructor -func NewServer(appServices app.Services) *Server { - rpcServer := &Server{appServices: appServices} +func NewServer(appServices app.Services, rpcPort string) *Server { + rpcServer := &Server{appServices: appServices, rpcPort: rpcPort} rpcServer.router = mux.NewRouter() return rpcServer } // ListenAndServe Starts listening for requests -func (rpcServer *Server) ListenAndServe(port *string) { +func (rpcServer *Server) ListenAndServe() { api := chat.NewHandler(rpcServer.appServices.ChatServices) err := rpc.Register(api) @@ -39,10 +40,10 @@ func (rpcServer *Server) ListenAndServe(port *string) { rpc.HandleHTTP() - fmt.Println("Serving RPC on", *port) + fmt.Println("Serving RPC on", rpcServer.rpcPort) srv := &http.Server{ - Addr: *port, + Addr: rpcServer.rpcPort, ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, } diff --git a/cmd/apps/skychat/internal/inputports/services.go b/cmd/apps/skychat/internal/inputports/services.go index 76819a3aa..0e3ef0411 100644 --- a/cmd/apps/skychat/internal/inputports/services.go +++ b/cmd/apps/skychat/internal/inputports/services.go @@ -18,10 +18,10 @@ type Services struct { } // NewServices instantiates the services of input ports -func NewServices(appServices app.Services) Services { +func NewServices(appServices app.Services, httpPort string, rpcPort string) Services { return Services{ - HTTPServer: http.NewServer(appServices), - RPCServer: rpc.NewServer(appServices), - RPCClient: rpc.NewClient(appServices), + HTTPServer: http.NewServer(appServices, httpPort), + RPCServer: rpc.NewServer(appServices, rpcPort), + RPCClient: rpc.NewClient(appServices, rpcPort), } } diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/connectionhandler/netcon/messenger_service.go similarity index 70% rename from cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go rename to cmd/apps/skychat/internal/interfaceadapters/connectionhandler/netcon/messenger_service.go index 49a4ec969..c7b61720d 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service.go +++ b/cmd/apps/skychat/internal/interfaceadapters/connectionhandler/netcon/messenger_service.go @@ -16,32 +16,32 @@ import ( "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" "github.com/skycoin/skywire/pkg/app/appnet" ) -// MessengerService provides a netcon implementation of the Service -type MessengerService struct { +// ConnectionHandlerService provides a netcon implementation of the Service +type ConnectionHandlerService struct { ctx context.Context ns notification.Service cliRepo client.Repository - usrRepo user.Repository visorRepo chat.Repository + msgrx chan message.Message // out-channel for this servie (when the connection received a message and wants to send it to other services) errs chan error - conns map[cipher.PubKey]net.Conn //TODO: find better way on handling active conns - handledConns map[cipher.PubKey]net.Conn //TODO: find better way on handling active conns + conns map[cipher.PubKey]net.Conn + handledConns map[cipher.PubKey]net.Conn } -// NewMessengerService constructor for MessengerService -func NewMessengerService(ns notification.Service, cR client.Repository, uR user.Repository, chR chat.Repository) *MessengerService { - ms := MessengerService{} +// NewConnectionHandlerService constructor for ConnectionHandlerService +func NewConnectionHandlerService(ns notification.Service, cR client.Repository, chR chat.Repository, msgrx chan message.Message) *ConnectionHandlerService { + ms := ConnectionHandlerService{} ms.ns = ns ms.cliRepo = cR - ms.usrRepo = uR ms.visorRepo = chR + ms.msgrx = msgrx + ms.conns = make(map[cipher.PubKey]net.Conn) ms.errs = make(chan error, 1) @@ -49,7 +49,7 @@ func NewMessengerService(ns notification.Service, cR client.Repository, uR user. } // HandleConnection handles the connection to the given Pubkey and incoming messages -func (ms MessengerService) HandleConnection(pk cipher.PubKey) { +func (ms ConnectionHandlerService) HandleConnection(pk cipher.PubKey) { connection, err := ms.GetConnByPK(pk) if err != nil { @@ -88,15 +88,17 @@ func (ms MessengerService) HandleConnection(pk cipher.PubKey) { continue } - err = ms.handleReceivedMessage(*receivedMessage) - if err != nil { - ms.errs <- err - continue - } + ms.msgrx <- *receivedMessage + } } +// GetReceiveChannel returns the channel used to 'broadcast' received messages from the connectionhandler +func (ms ConnectionHandlerService) GetReceiveChannel() chan message.Message { + return ms.msgrx +} + // readMessageLengthFromConnection reads a prefix message of the connection to get the length of the upcoming message func readMessageLengthFromConnection(conn net.Conn) (*uint32, error) { prefixMessage := make([]byte, 4) @@ -144,27 +146,6 @@ func readNBytesFromConnection(n uint32, conn net.Conn) ([]byte, error) { return receivedBytes, nil } -// handleReceivedMessage handles a received message -func (ms MessengerService) handleReceivedMessage(receivedMessage message.Message) error { - chatClient, err := ms.cliRepo.GetClient() - if err != nil { - return err - } - - localPK := chatClient.GetAppClient().Config().VisorPK - - if receivedMessage.IsFromRemoteP2PToLocalP2P(localPK) { - go ms.handleP2PMessage(receivedMessage) - } else if receivedMessage.IsFromRemoteServer() { - go ms.handleRemoteServerMessage(receivedMessage) - } else if receivedMessage.IsFromRemoteToLocalServer(localPK) { - go ms.handleLocalServerMessage(receivedMessage) - } else { - return fmt.Errorf("received message that can't be matched to remote server, local server or p2p chat") - } - return nil -} - // decodeReceivedBytesToMessage decodes the given bytes to a message.Message func decodeReceivedBytesToMessage(messageBytes []byte) (*message.Message, error) { receivedRawMessage := message.RAWMessage{} @@ -179,7 +160,7 @@ func decodeReceivedBytesToMessage(messageBytes []byte) (*message.Message, error) } // DialPubKey dials the remote chat -func (ms MessengerService) DialPubKey(pk cipher.PubKey) (net.Conn, error) { +func (ms ConnectionHandlerService) DialPubKey(pk cipher.PubKey) (net.Conn, error) { chatClient, err := ms.cliRepo.GetClient() if err != nil { @@ -213,16 +194,6 @@ func (ms MessengerService) DialPubKey(pk cipher.PubKey) (net.Conn, error) { return conn, nil } -// sendMessageAndSaveItToDatabase sends a message and saves it to the database -func (ms MessengerService) sendMessageAndSaveItToDatabase(pkroute util.PKRoute, m message.Message) error { - return ms.sendMessage(pkroute, m, true) -} - -// sendMessageAndDontSaveItToDatabase sends a message but doesn't save it to the database -func (ms MessengerService) sendMessageAndDontSaveItToDatabase(pkroute util.PKRoute, m message.Message) error { - return ms.sendMessage(pkroute, m, false) -} - func addP2PIfEmpty(v *chat.Visor) error { if v.P2PIsEmpty() { p2p := chat.NewDefaultP2PRoom(v.GetPK()) @@ -235,10 +206,11 @@ func addP2PIfEmpty(v *chat.Visor) error { return nil } -// sendMessage sends a message to the given route +// SendMessage sends a message to the given route // // if addToDatabase is true the message will be saved locally, otherwise not. -func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, addToDatabase bool) error { +// Attention: a destination pkroute can also be a local destination so m.destination and pkroute can differ +func (ms ConnectionHandlerService) SendMessage(pkroute util.PKRoute, m message.Message, addToDatabase bool) error { v, err := ms.getVisorAndSetupIfNecessary(pkroute) if err != nil { @@ -291,7 +263,7 @@ func (ms MessengerService) sendMessage(pkroute util.PKRoute, m message.Message, return nil } -func (ms MessengerService) getVisorAndSetupIfNecessary(pkroute util.PKRoute) (*chat.Visor, error) { +func (ms ConnectionHandlerService) getVisorAndSetupIfNecessary(pkroute util.PKRoute) (*chat.Visor, error) { v, err := ms.getExistingVisorOrAddNewIfNotExists(pkroute) if err != nil { return nil, err @@ -321,7 +293,7 @@ func (ms MessengerService) getVisorAndSetupIfNecessary(pkroute util.PKRoute) (*c return v, nil } -func (ms MessengerService) getExistingVisorOrAddNewIfNotExists(pkroute util.PKRoute) (*chat.Visor, error) { +func (ms ConnectionHandlerService) getExistingVisorOrAddNewIfNotExists(pkroute util.PKRoute) (*chat.Visor, error) { if ms.visorExists(pkroute) { return ms.visorRepo.GetByPK(pkroute.Visor) @@ -343,45 +315,13 @@ func (ms MessengerService) getExistingVisorOrAddNewIfNotExists(pkroute util.PKRo } -func (ms MessengerService) visorExists(pkroute util.PKRoute) bool { +func (ms ConnectionHandlerService) visorExists(pkroute util.PKRoute) bool { _, err := ms.visorRepo.GetByPK(pkroute.Visor) return err == nil } -// sendMessageToRemoteRoute sends the given message to a remote route (as p2p and client) -func (ms MessengerService) sendMessageToRemoteRoute(msg message.Message) error { - //if the message goes to p2p we save it in database, if not we wait for the remote server to send us our message - //this way we can see that the message was received by the remote server - if msg.IsFromLocalToRemoteP2P() { - err := ms.sendMessageAndSaveItToDatabase(msg.Dest, msg) - if err != nil { - return err - } - } else { - err := ms.sendMessageAndDontSaveItToDatabase(msg.Dest, msg) - if err != nil { - return err - } - } - - n := notification.NewMsgNotification(msg.Dest) - err := ms.ns.Notify(n) - if err != nil { - return err - } - - return nil -} - -// sendMessageToLocalRoute "sends" the message to local server, so local server handles it, as it was sent from a remote route (used for messages send from server host, but as client) -func (ms MessengerService) sendMessageToLocalRoute(msg message.Message) error { - go ms.handleLocalServerMessage(msg) - - return nil -} - // Listen is used to listen for new incoming connections and pass them to the HandleConnection routine -func (ms MessengerService) Listen() { +func (ms ConnectionHandlerService) Listen() { chatClient, err := ms.cliRepo.GetClient() if err != nil { fmt.Printf("error getting client from repository: %s", err) @@ -430,7 +370,7 @@ func (ms MessengerService) Listen() { } // GetConnByPK returns the conn of the given visor pk or an error if there is no open connection to the requested visor -func (ms *MessengerService) GetConnByPK(pk cipher.PubKey) (net.Conn, error) { +func (ms *ConnectionHandlerService) GetConnByPK(pk cipher.PubKey) (net.Conn, error) { //check if conn already added if conn, ok := ms.conns[pk]; ok { return conn, nil @@ -439,7 +379,7 @@ func (ms *MessengerService) GetConnByPK(pk cipher.PubKey) (net.Conn, error) { } // AddConn adds the given net.Conn to the map to keep track of active connections -func (ms *MessengerService) AddConn(pk cipher.PubKey, conn net.Conn) error { +func (ms *ConnectionHandlerService) AddConn(pk cipher.PubKey, conn net.Conn) error { //check if conn already added if _, ok := ms.conns[pk]; ok { return fmt.Errorf("conn already added") @@ -449,7 +389,7 @@ func (ms *MessengerService) AddConn(pk cipher.PubKey, conn net.Conn) error { } // DeleteConn removes the given net.Conn from the map -func (ms *MessengerService) DeleteConn(pk cipher.PubKey) error { +func (ms *ConnectionHandlerService) DeleteConn(pk cipher.PubKey) error { //check if conn is added if _, ok := ms.conns[pk]; ok { delete(ms.conns, pk) @@ -459,7 +399,7 @@ func (ms *MessengerService) DeleteConn(pk cipher.PubKey) error { } // ConnectionToPkHandled returns if a connection to the given pk is handled in a go routine -func (ms *MessengerService) ConnectionToPkHandled(pk cipher.PubKey) bool { +func (ms *ConnectionHandlerService) ConnectionToPkHandled(pk cipher.PubKey) bool { if _, ok := ms.handledConns[pk]; ok { return true } @@ -467,7 +407,7 @@ func (ms *MessengerService) ConnectionToPkHandled(pk cipher.PubKey) bool { } // AddConnToHandled adds the given net.Conn to the map to keep track of handled connections -func (ms *MessengerService) AddConnToHandled(pk cipher.PubKey, conn net.Conn) error { +func (ms *ConnectionHandlerService) AddConnToHandled(pk cipher.PubKey, conn net.Conn) error { //check if conn already added if _, ok := ms.handledConns[pk]; ok { return fmt.Errorf("conn already added") @@ -477,7 +417,7 @@ func (ms *MessengerService) AddConnToHandled(pk cipher.PubKey, conn net.Conn) er } // DeleteConnFromHandled removes the given net.Conn from the handledConns map -func (ms *MessengerService) DeleteConnFromHandled(pk cipher.PubKey) error { +func (ms *ConnectionHandlerService) DeleteConnFromHandled(pk cipher.PubKey) error { //check if conn is added if _, ok := ms.handledConns[pk]; ok { delete(ms.handledConns, pk) diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service.go new file mode 100644 index 000000000..6e334360d --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service.go @@ -0,0 +1,114 @@ +// Package messengerimpl implements a messenger service to handle received and sent messages +package messengerimpl + +import ( + "fmt" + + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/connectionhandler" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// MessengerService provides a netcon implementation of the Service +type MessengerService struct { + ns notification.Service + cliRepo client.Repository + usrRepo user.Repository + visorRepo chat.Repository + ch connectionhandler.Service + errs chan error +} + +// NewMessengerService constructor for MessengerService +func NewMessengerService(ns notification.Service, cR client.Repository, uR user.Repository, chR chat.Repository, ch connectionhandler.Service) *MessengerService { + ms := MessengerService{} + + ms.ns = ns + ms.cliRepo = cR + ms.usrRepo = uR + ms.visorRepo = chR + ms.ch = ch + + ms.errs = make(chan error, 1) + + go ms.HandleReceivedMessages() + + return &ms +} + +// HandleReceivedMessages waits for incoming messages on channel and then handles them +func (ms MessengerService) HandleReceivedMessages() { + for msg := range ms.ch.GetReceiveChannel() { + err := ms.HandleReceivedMessage(msg) + if err != nil { + ms.errs <- err + } + } +} + +// HandleReceivedMessage handles a received message +func (ms MessengerService) HandleReceivedMessage(receivedMessage message.Message) error { + chatClient, err := ms.cliRepo.GetClient() + if err != nil { + return err + } + + localPK := chatClient.GetAppClient().Config().VisorPK + + if receivedMessage.IsFromRemoteP2PToLocalP2P(localPK) { + go ms.handleP2PMessage(receivedMessage) + } else if receivedMessage.IsFromRemoteServer() { + go ms.handleRemoteServerMessage(receivedMessage) + } else if receivedMessage.IsFromRemoteToLocalServer(localPK) { + go ms.handleLocalServerMessage(receivedMessage) + } else { + return fmt.Errorf("received message that can't be matched to remote server, local server or p2p chat") + } + return nil +} + +// sendMessageAndSaveItToDatabase sends a message and saves it to the database +func (ms MessengerService) sendMessageAndSaveItToDatabase(pkroute util.PKRoute, m message.Message) error { + return ms.ch.SendMessage(pkroute, m, true) +} + +// sendMessageAndDontSaveItToDatabase sends a message but doesn't save it to the database +func (ms MessengerService) sendMessageAndDontSaveItToDatabase(pkroute util.PKRoute, m message.Message) error { + return ms.ch.SendMessage(pkroute, m, false) +} + +// sendMessageToRemoteRoute sends the given message to a remote route (as p2p and client) +func (ms MessengerService) sendMessageToRemoteRoute(msg message.Message) error { + //if the message goes to p2p we save it in database, if not we wait for the remote server to send us our message + //this way we can see that the message was received by the remote server + if msg.IsFromLocalToRemoteP2P() { + err := ms.sendMessageAndSaveItToDatabase(msg.Dest, msg) + if err != nil { + return err + } + } else { + err := ms.sendMessageAndDontSaveItToDatabase(msg.Dest, msg) + if err != nil { + return err + } + } + + n := notification.NewMsgNotification(msg.Dest) + err := ms.ns.Notify(n) + if err != nil { + return err + } + + return nil +} + +// sendMessageToLocalRoute "sends" the message to local server, so local server handles it, as it was sent from a remote route (used for messages send from server host, but as client) +func (ms MessengerService) sendMessageToLocalRoute(msg message.Message) error { + go ms.handleLocalServerMessage(msg) + + return nil +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_local_server.go similarity index 99% rename from cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go rename to cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_local_server.go index 6f8eb814d..cebdf6bb5 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_local_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_local_server.go @@ -1,4 +1,4 @@ -package netcon +package messengerimpl import ( "encoding/json" diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_p2p.go similarity index 99% rename from cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go rename to cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_p2p.go index 66d7881eb..a61544f0d 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_p2p.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_p2p.go @@ -1,4 +1,4 @@ -package netcon +package messengerimpl import ( "encoding/json" diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_remote_server.go similarity index 99% rename from cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go rename to cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_remote_server.go index b00fe4308..5fd90bfa4 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_remote_server.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_remote_server.go @@ -1,4 +1,4 @@ -package netcon +package messengerimpl import ( "encoding/json" diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_send_messages.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_send_messages.go similarity index 99% rename from cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_send_messages.go rename to cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_send_messages.go index 888345518..b3d721bea 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon/messenger_service_send_messages.go +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_send_messages.go @@ -1,4 +1,4 @@ -package netcon +package messengerimpl import ( "encoding/json" diff --git a/cmd/apps/skychat/internal/interfaceadapters/services.go b/cmd/apps/skychat/internal/interfaceadapters/services.go index 24979fde4..7468b38f8 100644 --- a/cmd/apps/skychat/internal/interfaceadapters/services.go +++ b/cmd/apps/skychat/internal/interfaceadapters/services.go @@ -4,12 +4,15 @@ package interfaceadapters import ( "fmt" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/connectionhandler" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/messenger" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app/notification" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/chat" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/client" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/message" "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/user" - "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/messenger/netcon" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/connectionhandler/netcon" + messengerimpl "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/messenger" channel "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/notification/http" "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/storage/boltdb" "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters/storage/memory" @@ -20,11 +23,12 @@ var InterfaceAdapterServices Services // Services contains the exposed services of interface adapters type Services struct { - ClientRepository client.Repository - UserRepository user.Repository - VisorRepository chat.Repository - MessengerService messenger.Service - NotificationService notification.Service + ClientRepository client.Repository + UserRepository user.Repository + VisorRepository chat.Repository + MessengerService messenger.Service + ConnectionHandlerService connectionhandler.Service + NotificationService notification.Service } // NewServices Instantiates the interface adapter services @@ -34,14 +38,19 @@ func NewServices() Services { usrRepo := boltdb.NewUserRepo(cli.GetAppClient().Config().VisorPK) vsrRepo := boltdb.NewVisorRepo() ns := channel.NewNotificationService() - ms := netcon.NewMessengerService(ns, cliRepo, usrRepo, vsrRepo) + + //channel is for communication between the next two services, that otherwise would be dependent on each other + messagesReceived := make(chan message.Message) + ch := netcon.NewConnectionHandlerService(ns, cliRepo, vsrRepo, messagesReceived) + ms := messengerimpl.NewMessengerService(ns, cliRepo, usrRepo, vsrRepo, ch) return Services{ - ClientRepository: cliRepo, - UserRepository: usrRepo, - VisorRepository: vsrRepo, - MessengerService: ms, - NotificationService: ns, + ClientRepository: cliRepo, + UserRepository: usrRepo, + VisorRepository: vsrRepo, + MessengerService: ms, + ConnectionHandlerService: ch, + NotificationService: ns, } } diff --git a/cmd/apps/skychat/skychat.go b/cmd/apps/skychat/skychat.go index 21e394458..300c0e926 100644 --- a/cmd/apps/skychat/skychat.go +++ b/cmd/apps/skychat/skychat.go @@ -11,11 +11,3 @@ func main() { cli.Execute() } - -//TEST: -// cd .. -// cd .. -// cd .. -// mingw32-make build-windows -// .\skywire-cli.exe config gen -i -r -o .\skywire-config.json -// .\build\skywire-visor.exe -c .\skywire-config.json --loglvl debug From f22f09abee1d12d9dfb8260b12925729971c0c33 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Mon, 11 Mar 2024 22:50:42 +0100 Subject: [PATCH 66/72] Update go mod --- go.mod | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/go.mod b/go.mod index a22f8a722..956a74f3a 100644 --- a/go.mod +++ b/go.mod @@ -22,7 +22,7 @@ require ( github.com/hashicorp/go-version v1.6.0 github.com/hashicorp/yamux v0.1.1 github.com/ivanpirog/coloredcobra v1.0.1 - github.com/james-barrow/golang-ipc v1.1.0 + github.com/james-barrow/golang-ipc v1.2.4 github.com/jaypipes/ghw v0.12.0 github.com/konsorten/go-windows-terminal-sequences v1.0.3 github.com/lib/pq v1.10.9 @@ -45,7 +45,7 @@ require ( github.com/xtaci/kcp-go v5.4.20+incompatible github.com/zcalusic/sysinfo v1.0.1 go.etcd.io/bbolt v1.3.7 - golang.org/x/net v0.14.0 + golang.org/x/net v0.17.0 golang.org/x/sync v0.3.0 golang.org/x/sys v0.15.0 golang.zx2c4.com/wireguard v0.0.20200320 @@ -96,6 +96,7 @@ require ( github.com/google/pprof v0.0.0-20230821062121-407c9e7a662f // indirect github.com/gookit/color v1.5.4 // indirect github.com/gopherjs/gopherjs v1.17.2 // indirect + github.com/gorilla/websocket v1.5.1 github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/itchyny/gojq v0.12.13 // indirect github.com/itchyny/timefmt-go v0.1.5 // indirect From 5ff6f78af6c0c8f9de61f8176700dddf595901ce Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Mon, 11 Mar 2024 23:13:26 +0100 Subject: [PATCH 67/72] fix cli skychat banner, and merge problem --- cmd/apps/skychat/commands/skychat.go | 328 ------------------ .../skychat/internal/inputports/cli/root.go | 15 +- 2 files changed, 9 insertions(+), 334 deletions(-) delete mode 100644 cmd/apps/skychat/commands/skychat.go diff --git a/cmd/apps/skychat/commands/skychat.go b/cmd/apps/skychat/commands/skychat.go deleted file mode 100644 index 96a05f432..000000000 --- a/cmd/apps/skychat/commands/skychat.go +++ /dev/null @@ -1,328 +0,0 @@ -// Package commands cmd/apps/skychat/skychat.go -package commands - -import ( - "context" - "embed" - "encoding/json" - "fmt" - "io/fs" - "log" - "net" - "net/http" - "os" - "os/signal" - "runtime" - "sync" - "time" - - ipc "github.com/james-barrow/golang-ipc" - "github.com/spf13/cobra" - - "github.com/skycoin/skywire-utilities/pkg/buildinfo" - "github.com/skycoin/skywire-utilities/pkg/cipher" - "github.com/skycoin/skywire-utilities/pkg/netutil" - "github.com/skycoin/skywire/pkg/app" - "github.com/skycoin/skywire/pkg/app/appnet" - "github.com/skycoin/skywire/pkg/app/appserver" - "github.com/skycoin/skywire/pkg/routing" - "github.com/skycoin/skywire/pkg/visor/visorconfig" -) - -const ( - netType = appnet.TypeSkynet - port = routing.Port(1) -) - -// var addr = flag.String("addr", ":8001", "address to bind, put an * before the port if you want to be able to access outside localhost") -var r = netutil.NewRetrier(nil, 50*time.Millisecond, netutil.DefaultMaxBackoff, 5, 2) - -var ( - addr string - appCl *app.Client - clientCh chan string - conns map[cipher.PubKey]net.Conn // Chat connections - connsMu sync.Mutex -) - -// the go embed static points to skywire/cmd/apps/skychat/static - -//go:embed static -var embededFiles embed.FS - -func init() { - RootCmd.Flags().StringVar(&addr, "addr", ":8001", "address to bind, put an * before the port if you want to be able to access outside localhost") -} - -// RootCmd is the root command for skywire-cli -var RootCmd = &cobra.Command{ - Use: "skychat", - Short: "skywire chat application", - Long: ` - ┌─┐┬┌─┬ ┬┌─┐┬ ┬┌─┐┌┬┐ - └─┐├┴┐└┬┘│ ├─┤├─┤ │ - └─┘┴ ┴ ┴ └─┘┴ ┴┴ ┴ ┴ `, - SilenceErrors: true, - SilenceUsage: true, - DisableSuggestions: true, - DisableFlagsInUseLine: true, - Version: buildinfo.Version(), - Run: func(cmd *cobra.Command, args []string) { - - appCl = app.NewClient(nil) - defer appCl.Close() - - if _, err := buildinfo.Get().WriteTo(os.Stdout); err != nil { - print(fmt.Sprintf("Failed to output build info: %v\n", err)) - } - - fmt.Println("Successfully started skychat.") - - clientCh = make(chan string) - defer close(clientCh) - - conns = make(map[cipher.PubKey]net.Conn) - go listenLoop() - - if runtime.GOOS == "windows" { - ipcClient, err := ipc.StartClient(visorconfig.SkychatName, nil) - if err != nil { - print(fmt.Sprintf("Error creating ipc server for skychat client: %v\n", err)) - setAppError(appCl, err) - os.Exit(1) - } - go handleIPCSignal(ipcClient) - } - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() - - http.Handle("/", http.FileServer(getFileSystem())) - http.HandleFunc("/message", messageHandler(ctx)) - http.HandleFunc("/sse", sseHandler) - - url := "" - // address := *addr - address := addr - if len(address) < 5 || (address[:1] != ":" && address[:2] != "*:") { - url = "127.0.0.1:8001" - } else if address[:1] == ":" { - url = "127.0.0.1" + address - } else if address[:2] == "*:" { - url = address[1:] - } else { - url = "127.0.0.1:8001" - } - - fmt.Println("Serving HTTP on", url) - - if runtime.GOOS != "windows" { - termCh := make(chan os.Signal, 1) - signal.Notify(termCh, os.Interrupt) - - go func() { - <-termCh - setAppStatus(appCl, appserver.AppDetailedStatusStopped) - os.Exit(1) - }() - } - setAppStatus(appCl, appserver.AppDetailedStatusRunning) - srv := &http.Server{ //nolint gosec - Addr: url, - ReadTimeout: 5 * time.Second, - WriteTimeout: 10 * time.Second, - } - err := srv.ListenAndServe() - if err != nil { - print(err.Error()) - setAppError(appCl, err) - os.Exit(1) - } - - }, -} - -// Execute executes root CLI command. -func Execute() { - if err := RootCmd.Execute(); err != nil { - log.Fatal("Failed to execute command: ", err) - } -} - -func listenLoop() { - l, err := appCl.Listen(netType, port) - if err != nil { - print(fmt.Sprintf("Error listening network %v on port %d: %v\n", netType, port, err)) - setAppError(appCl, err) - return - } - - setAppPort(appCl, port) - - for { - fmt.Println("Accepting skychat conn...") - conn, err := l.Accept() - if err != nil { - print(fmt.Sprintf("Failed to accept conn: %v\n", err)) - return - } - fmt.Println("Accepted skychat conn") - - raddr := conn.RemoteAddr().(appnet.Addr) - connsMu.Lock() - conns[raddr.PubKey] = conn - connsMu.Unlock() - fmt.Printf("Accepted skychat conn on %s from %s\n", conn.LocalAddr(), raddr.PubKey) - - go handleConn(conn) - } -} - -func handleConn(conn net.Conn) { - raddr := conn.RemoteAddr().(appnet.Addr) - for { - buf := make([]byte, 32*1024) - n, err := conn.Read(buf) - if err != nil { - fmt.Println("Failed to read packet:", err) - raddr := conn.RemoteAddr().(appnet.Addr) - connsMu.Lock() - delete(conns, raddr.PubKey) - connsMu.Unlock() - return - } - - clientMsg, err := json.Marshal(map[string]string{"sender": raddr.PubKey.Hex(), "message": string(buf[:n])}) - if err != nil { - print(fmt.Sprintf("Failed to marshal json: %v\n", err)) - } - select { - case clientCh <- string(clientMsg): - fmt.Printf("Received and sent to ui: %s\n", clientMsg) - default: - fmt.Printf("Received and trashed: %s\n", clientMsg) - } - } -} - -func messageHandler(ctx context.Context) func(w http.ResponseWriter, rreq *http.Request) { - return func(w http.ResponseWriter, req *http.Request) { - - data := map[string]string{} - if err := json.NewDecoder(req.Body).Decode(&data); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - pk := cipher.PubKey{} - if err := pk.UnmarshalText([]byte(data["recipient"])); err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - addr := appnet.Addr{ - Net: netType, - PubKey: pk, - Port: 1, - } - connsMu.Lock() - conn, ok := conns[pk] - connsMu.Unlock() - - if !ok { - var err error - err = r.Do(ctx, func() error { - conn, err = appCl.Dial(addr) - return err - }) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - return - } - - connsMu.Lock() - conns[pk] = conn - connsMu.Unlock() - - go handleConn(conn) - } - - _, err := conn.Write([]byte(data["message"])) - if err != nil { - http.Error(w, err.Error(), http.StatusBadRequest) - - connsMu.Lock() - delete(conns, pk) - connsMu.Unlock() - - return - } - } -} - -func sseHandler(w http.ResponseWriter, req *http.Request) { - f, ok := w.(http.Flusher) - if !ok { - http.Error(w, "Streaming unsupported!", http.StatusBadRequest) - return - } - - w.Header().Set("Content-Type", "text/event-stream") - w.Header().Set("Cache-Control", "no-cache") - w.Header().Set("Connection", "keep-alive") - w.Header().Set("Transfer-Encoding", "chunked") - - for { - select { - case msg, ok := <-clientCh: - if !ok { - return - } - _, _ = fmt.Fprintf(w, "data: %s\n\n", msg) - f.Flush() - - case <-req.Context().Done(): - fmt.Print("SSE connection were closed.") - return - } - } -} - -func getFileSystem() http.FileSystem { - fsys, err := fs.Sub(embededFiles, "static") - if err != nil { - panic(err) - } - return http.FS(fsys) -} - -func handleIPCSignal(client *ipc.Client) { - for { - m, err := client.Read() - if err != nil { - fmt.Printf("%s IPC received error: %v", visorconfig.SkychatName, err) - } - if m.MsgType == visorconfig.IPCShutdownMessageType { - fmt.Println("Stopping " + visorconfig.SkychatName + " via IPC") - break - } - } - os.Exit(0) -} - -func setAppStatus(appCl *app.Client, status appserver.AppDetailedStatus) { - if err := appCl.SetDetailedStatus(string(status)); err != nil { - print(fmt.Sprintf("Failed to set status %v: %v\n", status, err)) - } -} - -func setAppError(appCl *app.Client, appErr error) { - if err := appCl.SetError(appErr.Error()); err != nil { - print(fmt.Sprintf("Failed to set error %v: %v\n", appErr, err)) - } -} - -func setAppPort(appCl *app.Client, port routing.Port) { - if err := appCl.SetAppPort(port); err != nil { - print(fmt.Sprintf("Failed to set port %v: %v\n", port, err)) - } -} diff --git a/cmd/apps/skychat/internal/inputports/cli/root.go b/cmd/apps/skychat/internal/inputports/cli/root.go index 3b39516eb..033fb2a57 100644 --- a/cmd/apps/skychat/internal/inputports/cli/root.go +++ b/cmd/apps/skychat/internal/inputports/cli/root.go @@ -8,6 +8,7 @@ import ( cc "github.com/ivanpirog/coloredcobra" "github.com/spf13/cobra" + "github.com/skycoin/skywire-utilities/pkg/buildinfo" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app" "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports" clichat "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/cli/chat" @@ -21,12 +22,14 @@ var rootCmd = &cobra.Command{ Use: "skychat", Short: "Command Line Interface for skychat", Long: ` - ┌─┐┬┌─┬ ┬ ┌─┐┬ ┬ - └─┐├┴┐└┬┘ CHAT ──│ │ │ - └─┘┴ ┴ ┴ └─┘┴─┘┴`, - SilenceErrors: true, - SilenceUsage: true, - DisableSuggestions: true, + ┌─┐┬┌─┬ ┬┌─┐┬ ┬┌─┐┌┬┐ + └─┐├┴┐└┬┘│ ├─┤├─┤ │ + └─┘┴ ┴ ┴ └─┘┴ ┴┴ ┴ ┴ `, + SilenceErrors: true, + SilenceUsage: true, + DisableSuggestions: true, + DisableFlagsInUseLine: true, + Version: buildinfo.Version(), Run: func(cmd *cobra.Command, args []string) { //TODO: Setup Databases depending on flags/attributes From 4d09f4673582bdbeb4c040a1c42018cdab4d22db Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Mon, 11 Mar 2024 23:19:36 +0100 Subject: [PATCH 68/72] change .db files in gitignore --- .gitignore | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 669a85871..c6891d07f 100644 --- a/.gitignore +++ b/.gitignore @@ -26,7 +26,7 @@ pkg/visor/foo/ /bin /node -/users.db +/*.db /hypervisor /*-node /*-visor From 97d125d0e9d6ae0ddb2d0e4b54942678aaad87c6 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Mon, 11 Mar 2024 23:35:12 +0100 Subject: [PATCH 69/72] fix import link for skychat in skywire --- cmd/skywire/skywire.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/skywire/skywire.go b/cmd/skywire/skywire.go index 49826e2d8..c48846dc3 100644 --- a/cmd/skywire/skywire.go +++ b/cmd/skywire/skywire.go @@ -11,7 +11,7 @@ import ( "github.com/spf13/cobra" "github.com/skycoin/skywire-utilities/pkg/buildinfo" - sc "github.com/skycoin/skywire/cmd/apps/skychat/commands" + sc "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/cli" ssc "github.com/skycoin/skywire/cmd/apps/skysocks-client/commands" ss "github.com/skycoin/skywire/cmd/apps/skysocks/commands" vpnc "github.com/skycoin/skywire/cmd/apps/vpn-client/commands" From 473d40b6e51e0958f51d331b612a6bb8323d962c Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Mon, 11 Mar 2024 23:41:29 +0100 Subject: [PATCH 70/72] export skychat RootCmd for cobra --- .../skychat/internal/inputports/cli/root.go | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/cmd/apps/skychat/internal/inputports/cli/root.go b/cmd/apps/skychat/internal/inputports/cli/root.go index 033fb2a57..9d01e8592 100644 --- a/cmd/apps/skychat/internal/inputports/cli/root.go +++ b/cmd/apps/skychat/internal/inputports/cli/root.go @@ -18,9 +18,9 @@ import ( var httpport string var rpcport string -var rootCmd = &cobra.Command{ +var RootCmd = &cobra.Command{ Use: "skychat", - Short: "Command Line Interface for skychat", + Short: "skywire chat application", Long: ` ┌─┐┬┌─┬ ┬┌─┐┬ ┬┌─┐┌┬┐ └─┐├┴┐└┬┘│ ├─┤├─┤ │ @@ -62,23 +62,23 @@ var rootCmd = &cobra.Command{ } func init() { - rootCmd.AddCommand( + RootCmd.AddCommand( clichat.RootCmd, ) var helpflag bool - rootCmd.SetUsageTemplate(help) - rootCmd.PersistentFlags().BoolVarP(&helpflag, "help", "h", false, "help for "+rootCmd.Use) - rootCmd.SetHelpCommand(&cobra.Command{Hidden: true}) - rootCmd.PersistentFlags().MarkHidden("help") //nolint + RootCmd.SetUsageTemplate(help) + RootCmd.PersistentFlags().BoolVarP(&helpflag, "help", "h", false, "help for "+RootCmd.Use) + RootCmd.SetHelpCommand(&cobra.Command{Hidden: true}) + RootCmd.PersistentFlags().MarkHidden("help") //nolint - rootCmd.Flags().StringVar(&httpport, "httpport", ":8001", "port to bind") - rootCmd.Flags().StringVar(&rpcport, "rpcport", ":4040", "port to bind") + RootCmd.Flags().StringVar(&httpport, "httpport", ":8001", "port to bind") + RootCmd.Flags().StringVar(&rpcport, "rpcport", ":4040", "port to bind") } // Execute executes root CLI command. func Execute() { cc.Init(&cc.Config{ - RootCmd: rootCmd, + RootCmd: RootCmd, Headings: cc.HiBlue + cc.Bold, //+ cc.Underline, Commands: cc.HiBlue + cc.Bold, CmdShortDescr: cc.HiBlue, @@ -91,7 +91,7 @@ func Execute() { NoBottomNewline: true, }) - if err := rootCmd.Execute(); err != nil { + if err := RootCmd.Execute(); err != nil { log.Fatal("Failed to execute command: ", err) } } From e7fe9429b17f599c19e26ac9dc1e3a1697c1f8bd Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Mon, 11 Mar 2024 23:46:02 +0100 Subject: [PATCH 71/72] fix skychat import link in skywire-deployment --- cmd/skywire-deployment/skywire.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmd/skywire-deployment/skywire.go b/cmd/skywire-deployment/skywire.go index 6f67fcd12..e39661e0a 100644 --- a/cmd/skywire-deployment/skywire.go +++ b/cmd/skywire-deployment/skywire.go @@ -42,7 +42,7 @@ import ( tps "github.com/skycoin/skywire-services/cmd/transport-setup/commands" vpnmon "github.com/skycoin/skywire-services/cmd/vpn-monitor/commands" "github.com/skycoin/skywire-utilities/pkg/buildinfo" - sc "github.com/skycoin/skywire/cmd/apps/skychat/commands" + sc "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/cli" ssc "github.com/skycoin/skywire/cmd/apps/skysocks-client/commands" ss "github.com/skycoin/skywire/cmd/apps/skysocks/commands" vpnc "github.com/skycoin/skywire/cmd/apps/vpn-client/commands" From dadd325f45218ff5ba74f00581b9ea8a0d188021 Mon Sep 17 00:00:00 2001 From: 4rchim3d3s <4rchim3d3s@protonmail.com> Date: Tue, 12 Mar 2024 18:53:21 +0100 Subject: [PATCH 72/72] move cli out of internal and fix imports --- cmd/apps/skychat/{internal/inputports => }/cli/chat/root.go | 2 +- .../skychat/{internal/inputports => }/cli/chat/send/root.go | 0 .../{internal/inputports => }/cli/chat/send/textmessage.go | 0 cmd/apps/skychat/{internal/inputports => }/cli/root.go | 4 +++- cmd/apps/skychat/skychat.go | 2 +- cmd/skywire-deployment/skywire.go | 2 +- cmd/skywire/skywire.go | 2 +- 7 files changed, 7 insertions(+), 5 deletions(-) rename cmd/apps/skychat/{internal/inputports => }/cli/chat/root.go (77%) rename cmd/apps/skychat/{internal/inputports => }/cli/chat/send/root.go (100%) rename cmd/apps/skychat/{internal/inputports => }/cli/chat/send/textmessage.go (100%) rename cmd/apps/skychat/{internal/inputports => }/cli/root.go (97%) diff --git a/cmd/apps/skychat/internal/inputports/cli/chat/root.go b/cmd/apps/skychat/cli/chat/root.go similarity index 77% rename from cmd/apps/skychat/internal/inputports/cli/chat/root.go rename to cmd/apps/skychat/cli/chat/root.go index 4d752becd..48f48c893 100644 --- a/cmd/apps/skychat/internal/inputports/cli/chat/root.go +++ b/cmd/apps/skychat/cli/chat/root.go @@ -4,7 +4,7 @@ package clichat import ( "github.com/spf13/cobra" - clichatsend "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/cli/chat/send" + clichatsend "github.com/skycoin/skywire/cmd/apps/skychat/cli/chat/send" ) // RootCmd is the sub-command so interact with the chats diff --git a/cmd/apps/skychat/internal/inputports/cli/chat/send/root.go b/cmd/apps/skychat/cli/chat/send/root.go similarity index 100% rename from cmd/apps/skychat/internal/inputports/cli/chat/send/root.go rename to cmd/apps/skychat/cli/chat/send/root.go diff --git a/cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go b/cmd/apps/skychat/cli/chat/send/textmessage.go similarity index 100% rename from cmd/apps/skychat/internal/inputports/cli/chat/send/textmessage.go rename to cmd/apps/skychat/cli/chat/send/textmessage.go diff --git a/cmd/apps/skychat/internal/inputports/cli/root.go b/cmd/apps/skychat/cli/root.go similarity index 97% rename from cmd/apps/skychat/internal/inputports/cli/root.go rename to cmd/apps/skychat/cli/root.go index 9d01e8592..26630224f 100644 --- a/cmd/apps/skychat/internal/inputports/cli/root.go +++ b/cmd/apps/skychat/cli/root.go @@ -9,15 +9,17 @@ import ( "github.com/spf13/cobra" "github.com/skycoin/skywire-utilities/pkg/buildinfo" + + clichat "github.com/skycoin/skywire/cmd/apps/skychat/cli/chat" "github.com/skycoin/skywire/cmd/apps/skychat/internal/app" "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports" - clichat "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/cli/chat" "github.com/skycoin/skywire/cmd/apps/skychat/internal/interfaceadapters" ) var httpport string var rpcport string +// RootCmd is the root command for skychat var RootCmd = &cobra.Command{ Use: "skychat", Short: "skywire chat application", diff --git a/cmd/apps/skychat/skychat.go b/cmd/apps/skychat/skychat.go index 9a0e54b37..44973e409 100644 --- a/cmd/apps/skychat/skychat.go +++ b/cmd/apps/skychat/skychat.go @@ -1,7 +1,7 @@ // Package main cmd/apps/skychat/skychat.go package main -import "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/cli" +import "github.com/skycoin/skywire/cmd/apps/skychat/cli" func main() { //cobra-cli diff --git a/cmd/skywire-deployment/skywire.go b/cmd/skywire-deployment/skywire.go index e39661e0a..bf0085d48 100644 --- a/cmd/skywire-deployment/skywire.go +++ b/cmd/skywire-deployment/skywire.go @@ -42,7 +42,7 @@ import ( tps "github.com/skycoin/skywire-services/cmd/transport-setup/commands" vpnmon "github.com/skycoin/skywire-services/cmd/vpn-monitor/commands" "github.com/skycoin/skywire-utilities/pkg/buildinfo" - sc "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/cli" + sc "github.com/skycoin/skywire/cmd/apps/skychat/cli" ssc "github.com/skycoin/skywire/cmd/apps/skysocks-client/commands" ss "github.com/skycoin/skywire/cmd/apps/skysocks/commands" vpnc "github.com/skycoin/skywire/cmd/apps/vpn-client/commands" diff --git a/cmd/skywire/skywire.go b/cmd/skywire/skywire.go index c48846dc3..1827dc0ce 100644 --- a/cmd/skywire/skywire.go +++ b/cmd/skywire/skywire.go @@ -11,7 +11,7 @@ import ( "github.com/spf13/cobra" "github.com/skycoin/skywire-utilities/pkg/buildinfo" - sc "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports/cli" + sc "github.com/skycoin/skywire/cmd/apps/skychat/cli" ssc "github.com/skycoin/skywire/cmd/apps/skysocks-client/commands" ss "github.com/skycoin/skywire/cmd/apps/skysocks/commands" vpnc "github.com/skycoin/skywire/cmd/apps/vpn-client/commands"