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 diff --git a/Makefile b/Makefile index 4bdc2629f..ecd014e4d 100644 --- a/Makefile +++ b/Makefile @@ -223,8 +223,12 @@ example-apps: ## Build example apps ${OPTS} go build ${BUILD_OPTS} -o $(BUILD_PATH)apps/ ./example/... host-apps-windows: ## build apps on windows - 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 }' + 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 $(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 diff --git a/README.md b/README.md index a899ea21a..45023c63d 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 diff --git a/cmd/apps/skychat/README.md b/cmd/apps/skychat/README.md index 4a64bc5f9..1c12e7364 100644 --- a/cmd/apps/skychat/README.md +++ b/cmd/apps/skychat/README.md @@ -1,53 +1,54 @@ -# 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: - -`skywire1.json` - -```json -{ - "apps": [ - { - "app": "skychat", - "version": "1.0", - "auto_start": true, - "port": 1 - } - ] -} -``` - -`skywire2.json` - -```json -{ - "apps": [ - { - "app": "skychat", - "version": "1.0", - "auto_start": true, - "port": 1, - "args": ["-addr", ":8002"] - } - ] -} -``` - -Compile binaries and start 2 visors: - -```bash -$ go build -o ./build/apps/skychat.v1.0 ./cmd/apps/skychat -$ cd ./build -$ ./skywire-visor skywire1.json -$ ./skywire-visor skywire2.json -``` - -Chat interface will be available on ports `8001` and `8002`. + +# 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. + +## Sequence Diagrams +### Init +![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://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://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://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 +### MessengerService.handleLocalServerMessage (This is the server-side handling of servers) +TODO + +### Usecases +TODO diff --git a/cmd/apps/skychat/cli/chat/root.go b/cmd/apps/skychat/cli/chat/root.go new file mode 100644 index 000000000..48f48c893 --- /dev/null +++ b/cmd/apps/skychat/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/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/cli/chat/send/root.go b/cmd/apps/skychat/cli/chat/send/root.go new file mode 100644 index 000000000..2706683d7 --- /dev/null +++ b/cmd/apps/skychat/cli/chat/send/root.go @@ -0,0 +1,14 @@ +// Package clichatsend contains code of the cobra cli chat send commands +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/cli/chat/send/textmessage.go b/cmd/apps/skychat/cli/chat/send/textmessage.go new file mode 100644 index 000000000..32b396357 --- /dev/null +++ b/cmd/apps/skychat/cli/chat/send/textmessage.go @@ -0,0 +1,43 @@ +package clichatsend + +import ( + "fmt" + + "github.com/spf13/cobra" + "github.com/spf13/pflag" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/inputports" +) + +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 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) + } + }, +} + +// ParsePK parses a public key +func ParsePK(_ *pflag.FlagSet, _, 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/cli/root.go b/cmd/apps/skychat/cli/root.go new file mode 100644 index 000000000..26630224f --- /dev/null +++ b/cmd/apps/skychat/cli/root.go @@ -0,0 +1,109 @@ +// 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-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" + "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", + Long: ` + ┌─┐┬┌─┬ ┬┌─┐┬ ┬┌─┐┌┬┐ + └─┐├┴┐└┬┘│ ├─┤├─┤ │ + └─┘┴ ┴ ┴ └─┘┴ ┴┴ ┴ ┴ `, + 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 + + interfaceadapters.InterfaceAdapterServices = interfaceadapters.NewServices() + defer func() { + err := interfaceadapters.InterfaceAdapterServices.Close() + if err != nil { + fmt.Println(err.Error()) + } + }() + + app.AppServices = app.NewServices( + interfaceadapters.InterfaceAdapterServices.UserRepository, + interfaceadapters.InterfaceAdapterServices.VisorRepository, + interfaceadapters.InterfaceAdapterServices.NotificationService, + interfaceadapters.InterfaceAdapterServices.MessengerService) + + inputports.InputportsServices = inputports.NewServices(app.AppServices, httpport, rpcport) + + //connectionHandlerService listen + go interfaceadapters.InterfaceAdapterServices.ConnectionHandlerService.Listen() + + //rpc-server for cli functionality + go inputports.InputportsServices.RPCServer.ListenAndServe() + + //http-server for web-ui + inputports.InputportsServices.HTTPServer.ListenAndServe() + }, +} + +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(&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, + 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/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/commands/static/index.html b/cmd/apps/skychat/commands/static/index.html deleted file mode 100644 index df658eae0..000000000 --- a/cmd/apps/skychat/commands/static/index.html +++ /dev/null @@ -1,745 +0,0 @@ - - - - - - - - - - - - - -
- -
    - - -
    - - - - - - - \ No newline at end of file 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.iuml b/cmd/apps/skychat/doc/messengerServiceHandleP2PMessage.iuml new file mode 100644 index 000000000..9a461ba92 --- /dev/null +++ b/cmd/apps/skychat/doc/messengerServiceHandleP2PMessage.iuml @@ -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 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..13b5ea0e3 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/add_local_server.go @@ -0,0 +1,157 @@ +// 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" + "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 { + 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 + notifService notification.Service +} + +// NewAddLocalServerRequestHandler Initializes an AddCommandHandler +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 { + + visor, err := h.getLocalVisorOrAddIfNotExists() + if err != nil { + return err + } + + server, err := h.getNewServer(visor, command) + if err != nil { + return err + } + + room, err := h.getNewRoom(server, command) + if err != nil { + return err + } + + err = server.AddRoom(*room) + if err != nil { + return err + } + + err = visor.AddServer(*server) + if err != nil { + return err + } + err = h.visorRepo.Set(*visor) + if err != nil { + return err + } + + n := notification.NewAddRouteNotification(room.GetPKRoute()) + err = h.notifService.Notify(n) + if err != nil { + return err + } + + return nil +} + +func (h addLocalServerRequestHandler) getLocalVisorOrAddIfNotExists() (*chat.Visor, error) { + userPK, err := h.getUserPK() + if err != nil { + return nil, err + } + + visorIfExists, err := h.visorRepo.GetByPK(*userPK) + if err != nil { + newVisor := chat.NewUndefinedVisor(*userPK) + err = h.visorRepo.Add(newVisor) + if err != nil { + return nil, err + } + return &newVisor, nil + } + return visorIfExists, nil +} + +func (h addLocalServerRequestHandler) getUserPK() (*cipher.PubKey, error) { + usr, err := h.userRepo.GetUser() + if err != nil { + return nil, err + } + + 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/delete_route.go b/cmd/apps/skychat/internal/app/chat/commands/delete_route.go new file mode 100644 index 000000000..aa756738a --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/delete_route.go @@ -0,0 +1,241 @@ +// 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() { + //TODO: delete connection to Visor in client struct + 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/commands/join_remote_route.go b/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go new file mode 100644 index 000000000..7d2764663 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/join_remote_route.go @@ -0,0 +1,59 @@ +// 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" +) + +// JoinRemoteRouteRequest of JoinRemoteRouteRequestHandler +type JoinRemoteRouteRequest struct { + Route util.PKRoute +} + +// JoinRemoteRouteRequestHandler struct that allows handling JoinRemoteRouteRequest +type JoinRemoteRouteRequestHandler interface { + Handle(command JoinRemoteRouteRequest) error +} + +type joinRemoteRouteRequestHandler struct { + messengerService messenger.Service + visorRepo chat.Repository +} + +// NewJoinRemoteRouteRequestHandler Initializes an JoinCommandHandler +func NewJoinRemoteRouteRequestHandler(visorRepo chat.Repository, messengerService messenger.Service) JoinRemoteRouteRequestHandler { + return joinRemoteRouteRequestHandler{visorRepo: visorRepo, messengerService: messengerService} +} + +// Handle Handles the JoinRemoteRouteRequest +func (h joinRemoteRouteRequestHandler) Handle(command JoinRemoteRouteRequest) error { + if h.routeAlreadyJoined(command) { + return fmt.Errorf("already member of route %s", command.Route.String()) + } + + err := h.messengerService.SendRouteRequestMessage(command.Route) + if err != nil { + return err + } + + return nil +} + +// 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) + 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 new file mode 100644 index 000000000..8cb175f20 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/leave_remote_route.go @@ -0,0 +1,183 @@ +// Package commands contains commands to leave remote 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/user" + "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 { + ms messenger.Service + visorRepo chat.Repository + usrRepo user.Repository +} + +// NewLeaveRemoteRouteRequestHandler Handler constructor +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 { + if h.routeIsOfOwnVisor(command.Route) { + return fmt.Errorf("cannot leave route of own server") + } + + if command.isLeavingP2PRouteCommand() { + err := h.leaveP2PRoute(command.Route) + if err != nil { + return err + } + return nil + } + + if command.isLeavingServerRouteCommand() { + err := h.leaveServerRoute(command.Route) + if err != nil { + return err + } + return nil + } + + if command.isLeavingRoomRouteCommand() { + err := h.leaveRoomRoute(command.Route) + if err != nil { + return err + } + + err = h.leaveServerIfEmpty(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 + //TODO: handle different? + return true + } + + if route.Visor == usr.GetInfo().GetPK() { + return true + } + + 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) leaveP2PRoute(route util.PKRoute) error { + visor, err := h.visorRepo.GetByPK(route.Visor) + if err != nil { + return err + } + + if !visor.P2PIsEmpty() { + err = h.ms.SendLeaveRouteMessage(route) + if err != nil { + return err + } + } + + return h.visorRepo.Set(*visor) +} + +func (h leaveRemoteRouteRequestHandler) leaveServerRoute(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) + } + + return h.visorRepo.Set(*visor) +} + +func (h leaveRemoteRouteRequestHandler) leaveRoomRoute(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.GetRoomByPK(route.Room) + if err != nil { + return err + } + + err = h.ms.SendLeaveRouteMessage(route) + if err != nil { + fmt.Println(err) + } + + return nil +} + +func (h leaveRemoteRouteRequestHandler) leaveServerIfEmpty(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 { + //Prepare ServerRoute + serverroute := util.NewServerRoute(route.Visor, route.Server) + // Send LeaveChatMessage to remote server + err = h.ms.SendLeaveRouteMessage(serverroute) + if err != nil { + return err + } + + return nil + } + + return nil +} 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..2722683cb --- /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 add room 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 SendAddRoomMessageRequest +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..32c3cc171 --- /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 delete room 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/commands/send_fire_moderator_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_fire_moderator_message.go new file mode 100644 index 000000000..a564a8194 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/send_fire_moderator_message.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_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_hire_moderator_message.go new file mode 100644 index 000000000..43f6bc329 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/send_hire_moderator_message.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/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..ac3c79a38 --- /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 mute peer 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_text_message.go b/cmd/apps/skychat/internal/app/chat/commands/send_text_message.go new file mode 100644 index 000000000..92ba5fded --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/commands/send_text_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/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 { + Route util.PKRoute + Msg []byte +} + +// SendTextMessageRequestHandler struct that allows handling SendTextMessageRequest +type SendTextMessageRequestHandler interface { + Handle(command SendTextMessageRequest) error +} + +type sendTextMessageRequestHandler struct { + messengerService messenger.Service +} + +// NewSendTextMessageRequestHandler Initializes an AddCommandHandler +func NewSendTextMessageRequestHandler(messengerService messenger.Service) SendTextMessageRequestHandler { + return sendTextMessageRequestHandler{messengerService: messengerService} +} + +// Handle Handles the AddCragRequest +func (h sendTextMessageRequestHandler) Handle(command SendTextMessageRequest) error { + err := h.messengerService.SendTextMessage(command.Route, command.Msg) + 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..110f990b6 --- /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 unmute peer 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/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..4050b0c27 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/queries/get_all_messages_from_room_by_route.go @@ -0,0 +1,81 @@ +// 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) { + if query.isP2PRequest() { + return h.getP2PMessagesResult(query) + } + 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 + } + + msgs, err := visor.GetP2PMessages() + if err != nil { + return result, err + } + + 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 new file mode 100644 index 000000000..36686a6a1 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/queries/get_all_visors.go @@ -0,0 +1,53 @@ +// 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) { + var result []GetAllVisorsResult + + allVisors, err := h.visorRepo.GetAll() + if err != nil { + return nil, err + } + + 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(), + }) + } + 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..94e4e2751 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/queries/get_room_by_route.go @@ -0,0 +1,115 @@ +// 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 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) + 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) { + if query.isP2PRequest() { + return h.getP2PRoomResult(query) + } + return h.getRouteRoomResult(query) + +} + +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 + } + + 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, + } + return result, nil +} + +func (h getRoomByRouteRequestHandler) getRouteRoomResult(query GetRoomByRouteRequest) (GetRoomByRouteResult, error) { + var result GetRoomByRouteResult + + visor, err := h.visorRepo.GetByPK(query.Route.Visor) + 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: 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 new file mode 100644 index 000000000..29c3e0676 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/queries/get_server_by_route.go @@ -0,0 +1,69 @@ +// 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) { + 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, + } + + 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..8d8728478 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/queries/get_visor_by_pk.go @@ -0,0 +1,56 @@ +// 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 new file mode 100644 index 000000000..0312b1198 --- /dev/null +++ b/cmd/apps/skychat/internal/app/chat/services.go @@ -0,0 +1,67 @@ +// Package chatservices contains services required by the chat app +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/app/notification" + "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 { + 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 { + AddLocalServerHandler commands.AddLocalServerRequestHandler + JoinRemoteRouteHandler commands.JoinRemoteRouteRequestHandler + DeleteRouteHandler commands.DeleteRouteRequestHandler + 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 +type ChatServices struct { + Queries Queries + Commands Commands +} + +// NewServices Bootstraps Application Layer dependencies +func NewServices(visorRepo chat.Repository, userRepo user.Repository, ms messenger.Service, ns notification.Service) ChatServices { + return ChatServices{ + Queries: Queries{ + GetRoomByRouteHandler: queries.NewGetRoomByRouteRequestHandler(visorRepo), + GetServerByRouteHandler: queries.NewGetServerByRouteRequestHandler(visorRepo), + GetAllVisorsHandler: queries.NewGetAllVisorsRequestHandler(visorRepo), + GetVisorByPKHandler: queries.NewGetVisorByPKRequestHandler(visorRepo), + GetAllMessagesFromRoomHandler: queries.NewGetAllMessagesFromRoomRequestHandler(visorRepo), + }, + Commands: Commands{ + AddLocalServerHandler: commands.NewAddLocalServerRequestHandler(visorRepo, userRepo, ns), + JoinRemoteRouteHandler: commands.NewJoinRemoteRouteRequestHandler(visorRepo, ms), + DeleteRouteHandler: commands.NewDeleteRouteRequestHandler(ms, visorRepo, userRepo), + 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/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 new file mode 100644 index 000000000..9a25210f5 --- /dev/null +++ b/cmd/apps/skychat/internal/app/messenger/messenger.go @@ -0,0 +1,34 @@ +// Package messenger contains the interface Service required by the chat app +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 { + HandleReceivedMessage(message.Message) error + + //only used as client/p2p + SendRouteRequestMessage(route util.PKRoute) error + SendLeaveRouteMessage(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 + + //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 + + SendHireModeratorMessage(pkroute util.PKRoute, pk cipher.PubKey) error + SendFireModeratorMessage(pkroute util.PKRoute, pk cipher.PubKey) 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..4df967a07 --- /dev/null +++ b/cmd/apps/skychat/internal/app/notification/notification.go @@ -0,0 +1,87 @@ +// Package notification contains notification related code +package notification + +import ( + "encoding/json" + "fmt" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +const ( + // ErrNotifyType notifies about errors + ErrNotifyType = iota + //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 + NewMsgNotifyType + //DeleteChatNotifyType notifies about a deleted chat + DeleteChatNotifyType + //FUTUREFEATURE: add SentMsgNotifyType +) + +// Notification provides a struct to send messages via the Service +type Notification struct { + Type int `json:"type"` + Message string `json:"message"` +} + +// NewMsgNotification notifies the user of a new message +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 { + fmt.Printf("Failed to marshal json: %v", err) + } + return Notification{ + Type: NewMsgNotifyType, + Message: string(clientMsg), + } +} + +// 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: NewAddRouteNotifyType, + Message: string(clientMsg), + } +} + +// 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) + } + return Notification{ + Type: NewChatNotifyType, + Message: string(clientMsg), + } +} + +// 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 new file mode 100644 index 000000000..6c22f97ad --- /dev/null +++ b/cmd/apps/skychat/internal/app/services.go @@ -0,0 +1,29 @@ +// Package app contains the Services struct for the app +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/user" +) + +// AppServices holds the apps services as variable +var AppServices Services + +// 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(usrRepo user.Repository, visorRepo chat.Repository, notifyService notification.Service, ms messenger.Service) Services { + return Services{ + NotificationService: notifyService, + ChatServices: chatservices.NewServices(visorRepo, usrRepo, ms, notifyService), + UserServices: userservices.NewServices(usrRepo, ms, visorRepo)} +} 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 new file mode 100644 index 000000000..6fa5210c3 --- /dev/null +++ b/cmd/apps/skychat/internal/app/user/commands/set_info.go @@ -0,0 +1,96 @@ +// Package commands contains commands to set info of a user +package commands + +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 +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 { + ms messenger.Service + usrRepo user.Repository + visorRepo chat.Repository +} + +// NewSetInfoRequestHandler Initializes an SetInfoHandler +func NewSetInfoRequestHandler(ms messenger.Service, usrRepo user.Repository, visorRepo chat.Repository) SetInfoRequestHandler { + return setInfoRequestHandler{ms: ms, usrRepo: usrRepo, visorRepo: visorRepo} +} + +// Handle Handles the SetInfoRequest +func (h setInfoRequestHandler) Handle(req SetInfoRequest) error { + + pUsr, err := h.usrRepo.GetUser() + if err != nil { + return errors.New("failed to get user") + } + + i := info.NewInfo(pUsr.GetInfo().GetPK(), req.Alias, req.Desc, req.Img) + + pUsr.SetInfo(i) + + //get all visors + 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/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 new file mode 100644 index 000000000..6b85e0032 --- /dev/null +++ b/cmd/apps/skychat/internal/app/user/commands/set_settings.go @@ -0,0 +1,43 @@ +// Package commands contains commands to set settings of a user +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" +) + +// SetSettingsRequest 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.Repository +} + +// NewSetSettingsRequestHandler Initializes an SetSettingsRequestHandler +func NewSetSettingsRequestHandler(usrRepo user.Repository) 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:(ersonp) check if something else needs to be done/closed on returning an error + return err + } + + 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..d8e6e4905 --- /dev/null +++ b/cmd/apps/skychat/internal/app/user/queries/get_info.go @@ -0,0 +1,40 @@ +// Package queries contains queries to get info of a user +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.Repository +} + +// NewGetUserInfoRequestHandler Handler constructor +func NewGetUserInfoRequestHandler(usrRepo user.Repository) 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_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 new file mode 100644 index 000000000..d902a0736 --- /dev/null +++ b/cmd/apps/skychat/internal/app/user/queries/get_settings.go @@ -0,0 +1,40 @@ +// Package queries contains queries to get settings of a user +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 []cipher.PubKey +} + +// GetUserSettingsRequestHandler Contains the dependencies of the Handler +type GetUserSettingsRequestHandler interface { + Handle() (*GetUserSettingsResult, error) +} + +type getUserSettingsRequestHandler struct { + usrRepo user.Repository +} + +// NewGetUserSettingsRequestHandler Handler constructor +func NewGetUserSettingsRequestHandler(usrRepo user.Repository) 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() + + 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 new file mode 100644 index 000000000..76a1f03fe --- /dev/null +++ b/cmd/apps/skychat/internal/app/user/services.go @@ -0,0 +1,50 @@ +// Package userservices contains structs for the user +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 +} + +// 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(usrRepo user.Repository, ms messenger.Service, visorRepo chat.Repository) UserServices { + return UserServices{ + Queries: Queries{ + GetUserPeerBookHandler: queries.NewGetUserPeerbookRequestHandler(usrRepo), + GetUserInfoHandler: queries.NewGetUserInfoRequestHandler(usrRepo), + GetUserSettingsHandler: queries.NewGetUserSettingsRequestHandler(usrRepo), + }, + Commands: Commands{ + AddPeerHandler: commands.NewAddPeerRequestHandler(usrRepo), + DeletePeerHandler: commands.NewDeletePeerRequestHandler(usrRepo), + SetPeerHandler: commands.NewSetPeerRequestHandler(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 new file mode 100644 index 000000000..38e750ee4 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/chat/room.go @@ -0,0 +1,332 @@ +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 +) + +// DefaultRoomType defines the default room type +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)) +// -> 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 + 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 int //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) { + fmt.Printf("Added Message to route: %s \n", &r.PKRoute) + 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() int { + return r.Type +} + +// SetType sets the room's type +func (r *Room) SetType(t int) { + 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() 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() 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 +} + +// 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{} + 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 int) 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..21579e221 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/chat/server.go @@ -0,0 +1,408 @@ +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(pkroute util.PKRoute, m message.Message) { + r := s.Rooms[pkroute.Room] + r.AddMessage(m) + 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 +} + +// 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) +} + +// 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 { + 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 + 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 { + s.Members[peer.GetPK()] = peer + return nil + + } + return fmt.Errorf("peer already member of server") + +} + +// 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 + } + 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 +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 + sMember, err := s.GetMemberByPK(i.GetPK()) + if err != nil { + return err + } + sMember.SetInfo(i) + err = s.SetMember(*sMember) + if err != nil { + return err + } + + //set info in rooms if the pk is member + for _, room := range s.Rooms { + rMember, err := room.GetMemberByPK(i.GetPK()) + if err != nil { + continue + } + rMember.SetInfo(i) + err = room.SetMember(*rMember) + if err != nil { + return err + } + err = s.SetRoom(room) + 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() 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() 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 +} + +// 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) + + 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 new file mode 100644 index 000000000..b4f8f2f18 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/chat/visor.go @@ -0,0 +1,253 @@ +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" +) + +// Visor defines a remote or the local visor with all its servers +type Visor struct { + PK cipher.PubKey + + //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 +} + +// GetP2P returns peer to peer Room +// if the p2p is empty it returns an empty pointer +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{}) +} + +// 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 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? +} + +// DeleteP2P removes the p2p-chat-room from the visor +func (v *Visor) DeleteP2P() error { + //check if p2p exists + 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? +} + +// 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) +} + +// GetServerByRouteOrAddNewIfNotExists does what it is named +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 { + v.P2P.AddMessage(m) + return + } + s := v.Server[pkroute.Server] + s.AddMessage(pkroute, m) + 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 +func NewUndefinedVisor(pk cipher.PubKey) Visor { + v := Visor{} + v.PK = pk + 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.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.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) + + 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/chat/visor_repository.go b/cmd/apps/skychat/internal/domain/chat/visor_repository.go new file mode 100644 index 000000000..a7953cc69 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/chat/visor_repository.go @@ -0,0 +1,17 @@ +// Package chat contains the interface Repository for domain +package chat + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" +) + +// Repository is the interface to the chat repository +type Repository interface { + GetByPK(pk cipher.PubKey) (*Visor, error) + GetAll() ([]Visor, error) + 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.go b/cmd/apps/skychat/internal/domain/client/client.go new file mode 100644 index 000000000..8e014a2cd --- /dev/null +++ b/cmd/apps/skychat/internal/domain/client/client.go @@ -0,0 +1,192 @@ +// Package client contains client related code for domain +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" + "github.com/skycoin/skywire/pkg/app/appserver" + "github.com/skycoin/skywire/pkg/routing" + "github.com/skycoin/skywire/pkg/visor/visorconfig" +) + +// 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 + conns map[cipher.PubKey]net.Conn // active connections + clientCh chan string // client channel +} + +// 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 +} + +// GetConns returns a map of active connections +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") +} + +// 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 + 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 +} + +// GetChannel returns chan string +func (c *Client) GetChannel() chan string { + return c.clientCh +} + +// NewClient returns *Client +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.conns = make(map[cipher.PubKey]net.Conn) + 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(visorconfig.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 +} + +// IsEmpty checks if the client is empty +func (c *Client) IsEmpty() bool { + return reflect.DeepEqual(*c, Client{}) +} + +// SetAppStatus sets appserver.AppDetailedStatus +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) + } +} + +// SetAppError sets the appErr.Error +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) + } +} + +// 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", visorconfig.SkychatName, err) + } + if m.MsgType == visorconfig.IPCShutdownMessageType { + fmt.Println("Stopping " + visorconfig.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..bd005691d --- /dev/null +++ b/cmd/apps/skychat/internal/domain/client/client_repository.go @@ -0,0 +1,10 @@ +// Package client contains the struct Repository code for domain +package client + +// Repository defines the interface to the client repository +type Repository interface { + New() (Client, error) + GetClient() (*Client, error) + SetClient(c Client) error + Close() 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..f558a21a6 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/info/info.go @@ -0,0 +1,85 @@ +// Package info contains the info required by the chat app +package info + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" +) + +// 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 + 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 +} + +// GetImg 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 = DefaultImage + + return 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+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" + +// IsEmpty checks if info is empty +func (i *Info) IsEmpty() bool { + return *i == Info{} +} 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 new file mode 100644 index 000000000..5225b4057 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/message/message.go @@ -0,0 +1,347 @@ +// Package message contains the code required by the chat app +package message + +import ( + "encoding/json" + "fmt" + "time" + + "github.com/skycoin/skywire-utilities/pkg/cipher" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" +) + +// types of messages +const ( + // 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 +const ( + // ErrConnMsg is used to handle connection error messages + ErrConnMsg = iota + // ConnMsgTypeRequest is used to handle connection message of type Request + ConnMsgTypeRequest + // ConnMsgTypeAccept is used to handle connection message of type Accept + ConnMsgTypeAccept + // ConnMsgTypeReject is used to handle connection message of type Reject + 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 + //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 + 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 +) + +// 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 +) + +// 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 is used to mute a peer + 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 + */ +) + +// Message defines a message +type Message struct { + 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 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 string `json:"Message"` + Status int `json:"Status"` + Seen bool `json:"Seen"` +} + +// NewJSONMessage return a JSONMessage from a message +func NewJSONMessage(m Message) JSONMessage { + return JSONMessage{ + m.ID, + m.Origin, + m.Time, + m.Root, + m.Dest, + m.MsgType, + m.MsgSubtype, + string(m.Message), + m.Status, + m.Seen, + } +} + +// 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 { + + 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 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, + m.Time, + m.Root, + m.Dest, + m.MsgType, + m.MsgSubtype, + data, + m.Status, + m.Seen, + } +} + +// MarshalJSON returns marshaled json message and error +func (m Message) MarshalJSON() ([]byte, error) { + return json.Marshal(NewJSONMessage(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 + } + + 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 + + return nil +} + +// GetID returns message ID +func (m *Message) GetID() int { + 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 +} + +// GetRootVisor returns the root visor public key +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 +} + +// 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 +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 +} + +// 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/peer.go b/cmd/apps/skychat/internal/domain/peer/peer.go new file mode 100644 index 000000000..9dfc40e0f --- /dev/null +++ b/cmd/apps/skychat/internal/domain/peer/peer.go @@ -0,0 +1,48 @@ +// Package peer contains the code required by the chat app for peering +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 + // 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..e3f3cde94 --- /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/settings/settings.go b/cmd/apps/skychat/internal/domain/settings/settings.go new file mode 100644 index 000000000..b7d490af7 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/settings/settings.go @@ -0,0 +1,50 @@ +// Package settings contains the code required by settings of the chat app +package settings + +import ( + "github.com/skycoin/skywire-utilities/pkg/cipher" +) + +// Settings defines chat setting +type Settings struct { + blacklist []cipher.PubKey // Blacklist to block inocming connections +} + +// GetBlacklist returns the blacklist +func (s Settings) GetBlacklist() []cipher.PubKey { + return s.blacklist +} + +// SetBlacklist sets the blacklist +func (s *Settings) SetBlacklist(bl []cipher.PubKey) { + s.blacklist = bl +} + +// InBlacklist checks blacklist for a public key +func (s Settings) InBlacklist(pk cipher.PubKey) bool { + for _, b := range s.blacklist { + if b == pk { + return true + } + } + return false +} + +// 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 new file mode 100644 index 000000000..932b984d2 --- /dev/null +++ b/cmd/apps/skychat/internal/domain/user/user.go @@ -0,0 +1,63 @@ +// Package user contains the code required by user of the chat app +package user + +import ( + "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" +) + +// 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 +} + +// 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 +} + +// 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 +} + +// SetSettings applies settings +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 { + u := User{} + + 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() { + return true + } + 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..ce151a85d --- /dev/null +++ b/cmd/apps/skychat/internal/domain/user/user_repository.go @@ -0,0 +1,10 @@ +// Package user contains the code required by user of the chat app +package user + +// Repository is the interface to the user repository +type Repository interface { + GetUser() (*User, error) + SetUser(u *User) error + + Close() error +} 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 new file mode 100644 index 000000000..16fd0681c --- /dev/null +++ b/cmd/apps/skychat/internal/domain/util/pkroute.go @@ -0,0 +1,36 @@ +// 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. +// P2PRoute: VisorPK == ServerPK == RoomPK +// ServerRoute: VisorPK != ServerPK && ServerPK == RoomPK +// RoomRoute: VisorPK != ServerPK && ServerPK != RoomPK +type PKRoute struct { + 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 new file mode 100644 index 000000000..41436fe77 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/chat/handler.go @@ -0,0 +1,1006 @@ +// Package chat is the http handler for inputports +package chat + +import ( + "encoding/json" + "fmt" + "net/http" + "strconv" + "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" + "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 +type Handler struct { + chatServices chatservices.ChatServices +} + +// NewHandler Constructor returns *Handler +func NewHandler(cs chatservices.ChatServices) *Handler { + return &Handler{chatServices: cs} +} + +// 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 { + //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 + } + + info := info.Info{} + info.SetAlias(requestModel.Alias) + info.SetDescription(requestModel.Desc) + info.SetImg(requestModel.Img) + + err := c.chatServices.Commands.AddLocalServerHandler.Handle(commands.AddLocalServerRequest{ + Info: info, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + w.WriteHeader(http.StatusOK) +} + +// JoinRemoteRouteURLParam contains the parameter identifier to be parsed by the handler +const JoinRemoteRouteURLParam = "joinRemoteRoute" + +// JoinRemoteRouteRequestModel represents the request model expected for Join request +type JoinRemoteRouteRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` +} + +// 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()) + return + } + + route := util.PKRoute{} + + visorpk := cipher.PubKey{} + 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 + } + } + + err = c.chatServices.Commands.JoinRemoteRouteHandler.Handle(commands.JoinRemoteRouteRequest{ + Route: route, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + w.WriteHeader(http.StatusOK) +} + +// SendDeleteRoomMessageURLParam contains the parameter identifier to be parsed by the handler +const SendDeleteRoomMessageURLParam = "sendDeleteRoomMessage" + +// SendDeleteRoomMessageRequestModel represents the request model expected for Delete request +type SendDeleteRoomMessageRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` +} + +// 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 + } + + 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.SendDeleteRoomMessageHandler.Handle(commands.SendDeleteRoomMessageRequest{ + Route: route, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + w.WriteHeader(http.StatusOK) +} + +// SendAddRoomMessageURLParam contains the parameter identifier to be parsed by the handler +const SendAddRoomMessageURLParam = "sendAddRoomMessage" + +// 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"` +} + +// 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) + 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 + 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 + } + + 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.SendAddRoomMessageHandler.Handle(commands.SendAddRoomMessageRequest{ + Route: route, + Info: info, + Type: roomType, + }) + 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 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) +} + +// SendUnmutePeerMessageURLParam 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) +} + +// 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) +} + +// DeleteRouteURLParam contains the parameter identifier to be parsed by the handler +const DeleteRouteURLParam = "deleteRoute" + +// DeleteRouteRequestModel represents the request model expected for Delete request +type DeleteRouteRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` +} + +// 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) + 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.DeleteRouteHandler.Handle(commands.DeleteRouteRequest{ + Route: route, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + w.WriteHeader(http.StatusOK) +} + +// LeaveRemoteRouteURLParam contains the parameter identifier to be parsed by the handler +const LeaveRemoteRouteURLParam = "leaveRemoteRoute" + +// LeaveRemoteRouteRequestModel represents the request model expected for Delete request +type LeaveRemoteRouteRequestModel struct { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` +} + +// 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) + 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.LeaveRemoteRouteHandler.Handle(commands.LeaveRemoteRouteRequest{ + Route: route, + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + w.WriteHeader(http.StatusOK) +} + +// 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 { + VisorPk string `json:"visorpk"` + ServerPk string `json:"serverpk"` + RoomPk string `json:"roompk"` + 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 + } + + 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.SendTextMessageHandler.Handle(commands.SendTextMessageRequest{ + Route: util.NewRoomRoute(visorpk, serverpk, roompk), + Msg: []byte(msgToSend.Msg), + }) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + return + } + 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 + 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() //nolint + 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..468cdbb10 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/notification.go/handler.go @@ -0,0 +1,16 @@ +// Package notification is the http handler for inputports +package notification + +import ( + "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} +} 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 new file mode 100644 index 000000000..f568f019f --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/server.go @@ -0,0 +1,137 @@ +// Package http is the server handler for inputports +package http + +import ( + "embed" + "fmt" + "io/fs" + "log" + "net/http" + "time" + + "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 + port string +} + +// NewServer HTTP Server constructor +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())) + httpServer.router.Handle("/index.js", http.FileServer(getFileSystem())) + httpServer.router.Handle("/stylesheet.css", http.FileServer(getFileSystem())) + + 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.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 + //Remote + httpServer.router.HandleFunc(chatsHTTPRoutePath+"/"+chat.JoinRemoteRouteURLParam, chat.NewHandler(httpServer.appServices.ChatServices).JoinRemoteRoute).Methods("POST") + 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") + + //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") + 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") + +} + +// 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") + 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 +func (httpServer *Server) AddNotificationHTTPRoutes() { + const notificationHTTPRoutePath = "/notifications" + // + 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() { + fmt.Println("Serving HTTP on", httpServer.port) + srv := &http.Server{ + Addr: httpServer.port, + ReadTimeout: 5 * time.Second, + WriteTimeout: 10 * time.Second, + } + + log.Fatal(srv.ListenAndServe()) + +} + +// getFileSystem gets index file +func getFileSystem() http.FileSystem { + fsys, err := fs.Sub(embededFiles, "static") + if err != nil { + panic(err) + } + + 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/favicon.ico b/cmd/apps/skychat/internal/inputports/http/static/favicon.ico new file mode 100644 index 000000000..cc325fd3c Binary files /dev/null and b/cmd/apps/skychat/internal/inputports/http/static/favicon.ico differ 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..0877f2660 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/static/index.html @@ -0,0 +1,50 @@ + + + + + + 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..457ca97c9 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/static/index.js @@ -0,0 +1,1427 @@ + +///////////////////////////////////////////////////////////// +//// 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+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" +//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(), + this.getWebsocketPort() + ]).then(([userInfo,userSettings,chats,port]) => { + this.user = new User(userInfo,userSettings); + this.chats = chats + this.port = port + 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(this.port); + 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('joinRemote').innerHTML += + ` +
        Join Remote Server and Rooms
        +
        `; + } + + _updateUser(c) { + this.user = c + + document.getElementById('user').innerHTML = + ` + +
        +
        + ${c.info.alias} +
        +
        + ${c.info.pk} +
        +
        +
        `; + } + + _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); + } + + + let lastMsg = this.getLastMessageFromRoute(r.route) + + let prefix = this._getRoomPrefix(r) + + document.getElementById('chatList').innerHTML += + ``; + + } + + _updateChat(r) { + var index = this.getChatIndexFromRoute(r.route) + this.chats[index] = r + + let lastMsg = this.getLastMessageFromRoute(r.route) + + let prefix = this._getRoomPrefix(r) + + document.getElementById('chat_'+ r.pk).innerHTML = + `
      • + +
        +
        + ${prefix} ${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.inJoinRemote = 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 join a remote P2P or Group you have to insert the right Public Keys
        +
      • P2P: VisorPK & ServerPK & RoomPK = RemotePK
      • +
      • Group/Server: VisorPK & ServerPK & RoomPK
      • +
        + + + + +
        +
        VisorPK --------------------------- ServerPK -------------------------- RoomPK
        +
        + `; + } + + _hideInJoinRemote(){ + this.user.inJoinRemote = false; + document.getElementById('form').innerHTML = + ``; + } + + + _showMessage(msg,route) { + let c = this.user; + + switch(msg.type) { + case 1: + let connMsgOrigin + if (msg.origin == 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 if (msg.subtype == 4){ + connMsg = "remote deleted chat" + } + 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._hideInJoinRemote(); + + 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] + async getUserInfo(){ + return fetch('user/getInfo', { method: 'GET', body: null }) + .then(async 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] + async getUserSettings(){ + + return fetch('user/getSettings', { method: 'GET', body: null }) + .then(async 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) { + res.text() + 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) { + res.text() + 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] + async getChatAll(){ + + return fetch('chats', { method: 'GET', body: null }) + .then(res => { + if (res.ok) { + return res.json().then(visors => { + + var v_ = [] + if (visors != null){ + visors.forEach( v => { + console.log(v) + var p2p + if (v.P2P != null && v.P2P.Type != 0) { + if (Object.keys(v.P2P).length){ + 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].p2p != null){ + 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 + async 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( async 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 + //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(); + 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/' + "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() + } else { + res.text().then(text => alert(`Failed to add room: ${text}`)); + } + }).catch(e => alert(e.message)); + }else{ + fetch('chats/' + "addLocalServer", { method: 'POST', body: JSON.stringify({alias: alias, desc: description, img: ""}) }) + .then(res => { + if (res.ok) { + res.text() + } 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 + 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()); + + + //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/' + "joinRemoteRoute", { method: 'POST', body: JSON.stringify({ visorpk: visorpk, serverpk: serverpk, roompk: roompk}) }) + .then(res => { + if (res.ok) { + res.text() + } 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() + el[0].value = ''; + } else { + res.text().then(text => alert(`Failed to send message: ${text}`)); + } + }) + .catch(e => alert(e.message)); + } +//// DELETE + + //tries to leave 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 leave the chat?"); + + const visorpk = route.visor + const serverpk = route.server + const roompk = route.room + + if (response) { + 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 != 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 leave chat:\n visor:\n${visorpk}\nserver:\n${serverpk}\nroom:\n${roompk}\nreason:\n${text}`)); + } + }) + + } + else{ + return; + } + } + + //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 +///////////////////////////////////////////////////////////// +//// Subscribe + + + 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) + 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") + await 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") + await this.getRoomByRoute(route).then(chat => { + if (this.chats == null){ + this.chats = [] + } + this._addChat(chat) + }) + break; + //NewMsgNotifType + case 3: + console.log("new message notification") + //Fetch data of chat with new message from HTTP + await this.getRoomByRoute(route).then(c => { + if (this.chats == null){ + this.chats = [] + this._addChat(c) + } + this._updateChat(c) + }) + break; + default: + console.log("unknown notification") + break; + } + } + socket.onerror = async(event) => { + console.error("EventSource failed:", event) + } + socket.onclose = async() => { + console.log("socket opened") + } + socket.onclose = async() => { + console.log("socket closed") + } + }; + +///////////////////////////////////////////////////////////// +//// 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/commands/static/p.png b/cmd/apps/skychat/internal/inputports/http/static/p.png similarity index 100% rename from cmd/apps/skychat/commands/static/p.png rename to cmd/apps/skychat/internal/inputports/http/static/p.png 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..de1c5dfa8 --- /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 new file mode 100644 index 000000000..01834be88 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/http/user/handler.go @@ -0,0 +1,291 @@ +// Package user is the http handler for inputports +package user + +import ( + "encoding/json" + "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 +type Handler struct { + userServices userservices.UserServices +} + +// NewHandler Constructor +func NewHandler(app userservices.UserServices) *Handler { + return &Handler{userServices: app} +} + +// AddPeerURLParam contains the parameter identifier to be parsed by the handler +const AddPeerURLParam = "addPeer" + +// 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 + } + + 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()) + } + + w.WriteHeader(http.StatusOK) +} + +// 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 { + fmt.Println("could not convert pubkey") + } + + peerDeleteCommand := commands.DeletePeerRequest{PK: pk} + + err = c.userServices.Commands.DeletePeerHandler.Handle(peerDeleteCommand) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + } + + w.WriteHeader(http.StatusOK) +} + +// SetInfoURLParam contains the parameter identifier to be parsed by the handler +const SetInfoURLParam = "setInfo" + +// 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.Fprint(w, err.Error()) + } + 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 = "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 +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.Fprint(w, err.Error()) + } else { + setSettingsCommand := commands.SetSettingsRequest{ + Blacklist: keys, + } + + err = c.userServices.Commands.SetSettingsHandler.Handle(setSettingsCommand) + if err != nil { + w.WriteHeader(http.StatusInternalServerError) + fmt.Fprint(w, err.Error()) + } + } + 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, _ *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, _ *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, _ *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/inputports/rpc/chat/handler.go b/cmd/apps/skychat/internal/inputports/rpc/chat/handler.go new file mode 100644 index 000000000..c2e564456 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/rpc/chat/handler.go @@ -0,0 +1,54 @@ +// Package chat contains code of the rpc handler for inputports +package chat + +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 chat request handler +type Handler struct { + chatServices chatservices.ChatServices +} + +// NewHandler Constructor returns *Handler +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 + ServerPk cipher.PubKey + RoomPk cipher.PubKey + Msg string +} + +// SendTextMessage sends a text message to the given route +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()) + + //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 { + 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/rpc/client.go b/cmd/apps/skychat/internal/inputports/rpc/client.go new file mode 100644 index 000000000..b0024317a --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/rpc/client.go @@ -0,0 +1,46 @@ +// 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 + rpcPort string +} + +// NewClient RPC Client constructor +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 { + + rpcClient, err := rpc.DialHTTP("tcp", c.rpcPort) + 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..8a1911af8 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/rpc/server.go @@ -0,0 +1,52 @@ +// Package rpc contains code of the rpc handler for inputports +package rpc + +import ( + "fmt" + "log" + "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" +) + +// Server represents the rpc server running for this service +type Server struct { + appServices app.Services + router *mux.Router + rpcPort string +} + +// NewServer RPC Server constructor +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() { + + api := chat.NewHandler(rpcServer.appServices.ChatServices) + err := rpc.Register(api) + if err != nil { + log.Fatal("error registering API", err) + } + + rpc.HandleHTTP() + + fmt.Println("Serving RPC on", rpcServer.rpcPort) + + srv := &http.Server{ + Addr: rpcServer.rpcPort, + ReadTimeout: 5 * time.Second, + WriteTimeout: 10 * time.Second, + } + + log.Fatal(srv.ListenAndServe()) +} diff --git a/cmd/apps/skychat/internal/inputports/services.go b/cmd/apps/skychat/internal/inputports/services.go new file mode 100644 index 000000000..0e3ef0411 --- /dev/null +++ b/cmd/apps/skychat/internal/inputports/services.go @@ -0,0 +1,27 @@ +// Package inputports contains Services struct +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" +) + +// InputportsServices holds the inputports services as variable +var InputportsServices Services + +// Services contains the ports services +type Services struct { + HTTPServer *http.Server + RPCServer *rpc.Server + RPCClient *rpc.Client +} + +// NewServices instantiates the services of input ports +func NewServices(appServices app.Services, httpPort string, rpcPort string) Services { + return Services{ + HTTPServer: http.NewServer(appServices, httpPort), + RPCServer: rpc.NewServer(appServices, rpcPort), + RPCClient: rpc.NewClient(appServices, rpcPort), + } +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/connectionhandler/netcon/messenger_service.go b/cmd/apps/skychat/internal/interfaceadapters/connectionhandler/netcon/messenger_service.go new file mode 100644 index 000000000..c7b61720d --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/connectionhandler/netcon/messenger_service.go @@ -0,0 +1,427 @@ +// Package netcon contains code of the messenger of interfaceadapters +package netcon + +import ( + "context" + "encoding/binary" + "encoding/json" + "fmt" + "io" + "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/message" + "github.com/skycoin/skywire/cmd/apps/skychat/internal/domain/util" + "github.com/skycoin/skywire/pkg/app/appnet" +) + +// ConnectionHandlerService provides a netcon implementation of the Service +type ConnectionHandlerService struct { + ctx context.Context + ns notification.Service + cliRepo client.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 + handledConns map[cipher.PubKey]net.Conn +} + +// 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.visorRepo = chR + + ms.msgrx = msgrx + + 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 ConnectionHandlerService) HandleConnection(pk cipher.PubKey) { + + 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 + } + + messageBytes, err := readNBytesFromConnection(*messageLength, connection) + if err != nil { + ms.errs <- err + continue + } + + receivedMessage, err := decodeReceivedBytesToMessage(messageBytes) + 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) + _, err := io.ReadFull(conn, prefixMessage) + if err != nil { + return nil, err + } + messageLength := binary.BigEndian.Uint32(prefixMessage) + fmt.Printf("readMessageLengthFromConnection - Message Length: %d \n", messageLength) + return &messageLength, nil +} + +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 { + 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) + + 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) + + return receivedBytes, 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 +} + +// DialPubKey dials the remote chat +func (ms ConnectionHandlerService) DialPubKey(pk cipher.PubKey) (net.Conn, error) { + + chatClient, err := ms.cliRepo.GetClient() + if err != nil { + return nil, err + } + + conn, err := chatClient.GetConnByPK(pk) + if err == nil { + return conn, nil + } + + addr := appnet.Addr{ + Net: chatClient.GetNetType(), + PubKey: pk, + Port: chatClient.GetPort(), + } + + 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 { + //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 + } + + return conn, nil +} + +func addP2PIfEmpty(v *chat.Visor) error { + if v.P2PIsEmpty() { + p2p := chat.NewDefaultP2PRoom(v.GetPK()) + err := v.AddP2P(p2p) + if err != nil { + return err + } + fmt.Printf("New P2P room added to visor %s\n", v.GetPK().String()) + } + return nil +} + +// SendMessage sends a message to the given route +// +// if addToDatabase is true the message will be saved locally, otherwise not. +// 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 { + return err + } + + m.FmtPrint(false) + + rm := message.NewRAWMessage(m) + + bytes, err := json.Marshal(rm) + if err != nil { + return fmt.Errorf("failed to marshal json: %v ", err) + } + + 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) + if err != nil { + 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 { + return fmt.Errorf("failed to write bytes: %v", err) + + } + + if addToDatabase { + v.AddMessage(pkroute, m) + err = ms.visorRepo.Set(*v) + if err != nil { + return err + } + } + return nil +} + +func (ms ConnectionHandlerService) 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 ConnectionHandlerService) 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 ConnectionHandlerService) visorExists(pkroute util.PKRoute) bool { + _, err := ms.visorRepo.GetByPK(pkroute.Visor) + return err == nil +} + +// Listen is used to listen for new incoming connections and pass them to the HandleConnection routine +func (ms ConnectionHandlerService) Listen() { + chatClient, err := ms.cliRepo.GetClient() + if err != nil { + fmt.Printf("error getting client from repository: %s", err) + } + + listener, err := chatClient.GetAppClient().Listen(chatClient.GetNetType(), chatClient.GetPort()) + if err != nil { + fmt.Printf("Error listening network %v on port %d: %v\n", chatClient.GetNetType(), chatClient.GetPort(), err) + return + } + + chatClient.SetAppPort(chatClient.GetAppClient(), chatClient.GetPort()) + + go func() { + if err := <-ms.errs; err != nil { + fmt.Printf("Error in go HandleConnection function: %s \n", err) + } + }() + + for { + fmt.Println("Accepting skychat conn...") + conn, err := listener.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) + + 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 *ConnectionHandlerService) 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 *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") + } + ms.conns[pk] = conn + return nil +} + +// DeleteConn removes the given net.Conn from the map +func (ms *ConnectionHandlerService) 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? +} + +// ConnectionToPkHandled returns if a connection to the given pk is handled in a go routine +func (ms *ConnectionHandlerService) 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 handled connections +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") + } + ms.conns[pk] = conn + return nil +} + +// DeleteConnFromHandled removes the given net.Conn from the handledConns map +func (ms *ConnectionHandlerService) 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/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/messenger_service_local_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_local_server.go new file mode 100644 index 000000000..cebdf6bb5 --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_local_server.go @@ -0,0 +1,836 @@ +package messengerimpl + +import ( + "encoding/json" + "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" + "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) { + fmt.Println("handleLocalServerMessage") + + pkroute := util.NewRoomRoute(m.GetDestinationVisor(), m.GetDestinationServer(), m.GetDestinationRoom()) + + //Check if visor exists + visor, err := ms.visorRepo.GetByPK(m.Dest.Visor) + if err != nil { + ms.errs <- err + return + } + + //Check if server exists + server, err := visor.GetServerByPK(m.Dest.Server) + if err != nil { + ms.errs <- err + return + } + + //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 { + ms.errs <- err + return + } + return + } + + //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 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 { + ms.errs <- fmt.Errorf("error sending reject message: %s", err) + return + } + 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 { + ms.errs <- err + return + } + return + } + + //Check if room exists + room, err := server.GetRoomByPK(pkroute.Room) + if err != nil { + ms.errs <- err + return + } + + //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 { + ms.errs <- fmt.Errorf("error sending reject message: %s", err) + return + } + 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 + switch m.GetMessageType() { + case message.InfoMsgType: + //add the message to the visor and update repository + visor.AddMessage(pkroute, m) + err = ms.visorRepo.Set(*visor) + if err != nil { + ms.errs <- err + return + } + //handle the message + err = ms.handleLocalServerInfoMsgType(visor, m) + if err != nil { + fmt.Println(err) + } + case message.TxtMsgType: + //add the message to the visor and update repository + visor.AddMessage(pkroute, m) + err = ms.visorRepo.Set(*visor) + if err != nil { + ms.errs <- err + return + } + //handle the message + err := ms.handleLocalRoomTextMsgType(visor, m) + if err != nil { + ms.errs <- err + return + } + default: + ms.errs <- fmt.Errorf("incorrect data received") + return + + } +} + +// 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) 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 + } + 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 + + 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 { + + //add request message to room + room.AddMessage(m) + + //send request message to peers + err = ms.sendMessageToPeers(visor, pkroute, m) + 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 server + err = server.AddMember(*dummyPeer) + if err != nil { + fmt.Println(err) + } + //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 + } + //update server inside visor + err = visor.SetServer(*server) + if err != nil { + return err + } + //update visorRepo + err = ms.visorRepo.Set(*visor) + if err != nil { + return err + } + + //notify about a new messages/infos inside a group chat + n := notification.NewGroupChatNotification(pkroute) + err = ms.ns.Notify(n) + if err != nil { + return err + } + + //send a chat-accept-message to the remote peer + err = ms.SendChatAcceptMessage(pkroute, root, dest) + if err != nil { + return err + } + + //send the rooms info to the remote peer + err = ms.sendLocalRouteInfoToPeer(pkroute, dest, room.GetInfo()) + if err != nil { + return err + } + + // 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 + 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") + } + 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 + } + //update server with updated room + err = server.SetRoom(*room) + if err != nil { + return err + } + + // 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) + err = server.DeleteMember(m.Origin) + if err != nil { + return err + } + + //TODO: for each room and the server: send new member-list to members (where the peer was a member) + } + //update visor and repository + 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") + + } + + return nil +} + +// 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 + } + + 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()) + + // setup room for repository + 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 = room.AddMember(*p) + if err != nil { + return err + } + + //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) + 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: + //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: really delete room from server and update visor in reposiory + //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 + 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 + } + + // 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) + 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 + } + + // 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) + 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.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") + } +} + +// 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) + } + 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 + 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(pkroute) + err = ms.ns.Notify(n) + if err != nil { + return err + } + + //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 + } + 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 +func (ms MessengerService) handleLocalRoomTextMsgType(visor *chat.Visor, m message.Message) error { + fmt.Println("handleLocalRoomTextMsgType") + + pkroute := util.NewRoomRoute(m.GetDestinationVisor(), m.GetDestinationServer(), m.GetDestinationRoom()) + + 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) + err = ms.ns.Notify(n) + if err != nil { + return err + } + + //check if muted in server + if _, ok := server.GetAllMuted()[m.Origin]; ok { + return nil + } + + //check if 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, pkroute, m) + if err != nil { + return err + } + + 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") + + server, err := v.GetServerByPK(pkroute.Server) + 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() + } + + if len(members) == 0 { + fmt.Printf("No members to send message to") + } + + 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.sendMessageAndDontSaveItToDatabase(pkroute, m) + if err != nil { + fmt.Printf("error sending group message to peer: %v", err) + continue + } + } + } + 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.sendMessageAndSaveItToDatabase(pkroute, m) + if err != nil { + return err + } + + //notify about sent text message + n := notification.NewMsgNotification(pkroute) + err = ms.ns.Notify(n) + if err != nil { + return err + } + + 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/messenger_service_p2p.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_p2p.go new file mode 100644 index 000000000..a61544f0d --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_p2p.go @@ -0,0 +1,325 @@ +package messengerimpl + +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 received as direct message +func (ms MessengerService) handleP2PMessage(m message.Message) { + 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 + if m.GetMessageType() == message.ConnMsgType { + err := ms.handleP2PConnMsgType(m) + if err != nil { + ms.errs <- err + return + } + 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 { + ms.errs <- err + return + } + + //the p2p route of the user + root := util.NewP2PRoute(usr.GetInfo().GetPK()) + //the p2p route of the peer + dest := pkroute + + if usr.GetSettings().InBlacklist(pkroute.Visor) { + err = ms.SendChatRejectMessage(root, dest) + if err != nil { + ms.errs <- err + return + } + 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 { + ms.errs <- err + return + } + + //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 + visor.AddMessage(pkroute, m) + err = ms.visorRepo.Set(*visor) + if err != nil { + ms.errs <- err + return + } + //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 + visor.AddMessage(pkroute, m) + err = ms.visorRepo.Set(*visor) + if err != nil { + ms.errs <- err + return + } + //handle the message + err := ms.handleP2PTextMsgType(m) + if err != nil { + ms.errs <- err + return + } + case message.CmdMsgType: + ms.errs <- fmt.Errorf("commands are not allowed on p2p chats") + return + default: + ms.errs <- fmt.Errorf("incorrect data received") + return + } + +} + +// 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 + } + + //the p2p route of the user + root := util.NewP2PRoute(usr.GetInfo().GetPK()) + //the p2p route of the peer + 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(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 { + //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 + } + + //check if p2p already exists in repository + 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) + 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.NewP2PChatNotification(pkroute.Visor) + err = ms.ns.Notify(n) + if err != nil { + return err + } + + //send a chat-accept-message to the remote peer + err = ms.SendChatAcceptMessage(pkroute, root, dest) + if err != nil { + return err + } + + //send the users info to the remote peer + err = ms.SendInfoMessage(pkroute, 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 + } + + // 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 + } + 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(pkroute) + 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(pkroute, root, dest, *usr.GetInfo()) + if err != nil { + return err + } + + 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) + err = ms.ns.Notify(n) + if err != nil { + return err + } + 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) + 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 { + 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 + err = v.SetRouteInfo(pkroute, i) + if err != nil { + return err + } + err = ms.visorRepo.Set(*v) + if err != nil { + return err + } + + //notify about new info message + n := notification.NewMsgNotification(pkroute) + 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(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(pkroute) + err := ms.ns.Notify(n) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_remote_server.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_remote_server.go new file mode 100644 index 000000000..5fd90bfa4 --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_remote_server.go @@ -0,0 +1,323 @@ +package messengerimpl + +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" +) + +// handleRemoteServerMessage handles all messages from a remote server/room +func (ms MessengerService) handleRemoteServerMessage(m message.Message) { + fmt.Println("handleRemoteServerMessage") + + pkroute := util.NewRoomRoute(m.GetRootVisor(), m.GetRootServer(), m.GetRootRoom()) + + //check if we are member of remote server -> if not ignore message + visor, err := ms.visorRepo.GetByPK(pkroute.Visor) + if err != nil { + ms.errs <- fmt.Errorf("message dumped: no member of remote, visor not even known") + return + } + 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 + visor.AddMessage(pkroute, m) + err = ms.visorRepo.Set(*visor) + if err != nil { + ms.errs <- err + return + } + //handle the message + err = ms.handleRemoteRoomConnMsgType(m) + if err != nil { + fmt.Println(err) + } + case message.InfoMsgType: + //add the message to the visor and update repository + visor.AddMessage(pkroute, m) + err = ms.visorRepo.Set(*visor) + if err != nil { + ms.errs <- err + return + } + //handle the message + err = ms.handleRemoteRoomInfoMsgType(visor, m) + if err != nil { + fmt.Println(err) + } + case message.TxtMsgType: + //add the message to the visor and update repository + visor.AddMessage(pkroute, m) + err = ms.visorRepo.Set(*visor) + if err != nil { + ms.errs <- err + return + } + //handle the message + err := ms.handleRemoteRoomTextMsgType(m) + if err != nil { + ms.errs <- err + return + } + case message.CmdMsgType: + ms.errs <- fmt.Errorf("commands are not allowed on p2p chats") + return + default: + ms.errs <- fmt.Errorf("incorrect data received") + return + + } +} + +// 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() + if err != nil { + return err + } + + //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 := pkroute + + switch m.MsgSubtype { + case message.ConnMsgTypeAccept: + //notify that we received an accept message + n := notification.NewMsgNotification(m.Root) + 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(pkroute, root, dest, *user.GetInfo()) + if err != nil { + return err + } + + case message.ConnMsgTypeReject: + //notify that we send a reject message + n := notification.NewMsgNotification(m.Root) + 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.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 + default: + return fmt.Errorf("incorrect data received") + } + return nil + +} + +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") + + pkroute := util.NewRoomRoute(m.GetRootVisor(), m.GetRootServer(), m.GetRootRoom()) + + switch m.MsgSubtype { + case message.InfoMsgTypeSingle: + + //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 + } + + //notify about new info message + n := notification.NewMsgNotification(pkroute) + 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 + } + + //TODO: make method instead of direct access of variable + 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) + err = ms.ns.Notify(n) + 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) + err = ms.ns.Notify(n) + if err != nil { + return err + } + } + return nil +} + +// 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()) + + fmt.Println("---------------------------------------------------------------------------------------------------") + fmt.Printf("TextMessage: \n") + fmt.Printf("Text: %s \n", m.Message) + fmt.Println("---------------------------------------------------------------------------------------------------") + + //notify about a new TextMessage + n := notification.NewMsgNotification(pkroute) + err := ms.ns.Notify(n) + if err != nil { + return err + } + + return nil +} diff --git a/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_send_messages.go b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_send_messages.go new file mode 100644 index 000000000..b3d721bea --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/messenger/messenger_service_send_messages.go @@ -0,0 +1,326 @@ +package messengerimpl + +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.sendMessageAndDontSaveItToDatabase(pkroute, m) + 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 new file mode 100644 index 000000000..fac283e30 --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/notification/http/notification_service.go @@ -0,0 +1,50 @@ +// Package channel contains code of the notification service of interfaceadapters +package channel + +import ( + "encoding/json" + "fmt" + + "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{} + + 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 + } + fmt.Printf("Notify: \n") + fmt.Printf("%s \n", jsonNotification) + ns.GetChannel() <- string(jsonNotification) + return nil +} + +// InitChannel inits the channel with make +func (ns *NotificationService) InitChannel() { + ns.notifCh = make(chan string) +} + +// GetChannel returns the channel of the notification service +func (ns *NotificationService) GetChannel() chan string { + return ns.notifCh +} + +// DeferChannel 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/services.go b/cmd/apps/skychat/internal/interfaceadapters/services.go new file mode 100644 index 000000000..7468b38f8 --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/services.go @@ -0,0 +1,72 @@ +// Package interfaceadapters contains the struct Services +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/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" +) + +// InterfaceAdapterServices holds the interface adapter services as variable +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 + ConnectionHandlerService connectionhandler.Service + NotificationService notification.Service +} + +// NewServices Instantiates the interface adapter services +func NewServices() Services { + cliRepo := memory.NewClientRepo() + cli, _ := cliRepo.GetClient() //nolint + usrRepo := boltdb.NewUserRepo(cli.GetAppClient().Config().VisorPK) + vsrRepo := boltdb.NewVisorRepo() + ns := channel.NewNotificationService() + + //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, + ConnectionHandlerService: ch, + 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..2ef3182e1 --- /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" +) + +// USERBUCKET defines the key for the users bucket +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 + + r.pk = pk + + err = 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/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() +} 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..48d99ca46 --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/client_repo.go @@ -0,0 +1,64 @@ +// Package memory contains code of the client repo of interfaceadapters +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 +} + +// NewClientRepo Constructor +func NewClientRepo() *ClientRepo { + r := ClientRepo{} + + r.client, _ = r.New() //nolint + + return &r +} + +// 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") + } + err := r.SetClient(*client.NewClient()) + if err != nil { + return client.Client{}, err + } + return r.client, nil + +} + +// GetClient Returns the client +func (r *ClientRepo) GetClient() (*client.Client, error) { + r.cliMu.Lock() + defer r.cliMu.Unlock() + + if r.client.IsEmpty() { + return nil, fmt.Errorf("client not found") + } + return &r.client, nil + +} + +// SetClient updates the provided client +func (r *ClientRepo) SetClient(client client.Client) error { + r.cliMu.Lock() + defer r.cliMu.Unlock() + + 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 new file mode 100644 index 000000000..929733893 --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/user_repo.go @@ -0,0 +1,59 @@ +// Package memory contains code of the user repo of interfaceadapters +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 +} + +// NewUserRepo Constructor +func NewUserRepo(pk cipher.PubKey) *UserRepo { + r := UserRepo{} + + err := r.NewUser() + r.user.GetInfo().SetPK(pk) + if err != nil { + fmt.Println(err) + } + + return &r +} + +// 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() error { + if !r.user.IsEmpty() { + return fmt.Errorf("user already defined") + } + err := r.SetUser(user.NewDefaultUser()) + if err != nil { + return err + } + return nil +} + +// GetUser returns the user +func (r *UserRepo) GetUser() (*user.User, error) { + if r.user.IsEmpty() { + return nil, fmt.Errorf("user not found") + } + return &r.user, nil +} + +// SetUser updates the provided user +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 new file mode 100644 index 000000000..47839d604 --- /dev/null +++ b/cmd/apps/skychat/internal/interfaceadapters/storage/memory/visor_repo.go @@ -0,0 +1,80 @@ +// 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() + + 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 { + return r.Set(visor) +} + +// 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 +} + +// 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 97cffd42e..44973e409 100644 --- a/cmd/apps/skychat/skychat.go +++ b/cmd/apps/skychat/skychat.go @@ -1,43 +1,10 @@ // Package main cmd/apps/skychat/skychat.go package main -import ( - cc "github.com/ivanpirog/coloredcobra" - "github.com/spf13/cobra" - - "github.com/skycoin/skywire/cmd/apps/skychat/commands" -) - -func init() { - var helpflag bool - commands.RootCmd.SetUsageTemplate(help) - commands.RootCmd.PersistentFlags().BoolVarP(&helpflag, "help", "h", false, "help menu") - commands.RootCmd.SetHelpCommand(&cobra.Command{Hidden: true}) - commands.RootCmd.PersistentFlags().MarkHidden("help") //nolint -} +import "github.com/skycoin/skywire/cmd/apps/skychat/cli" func main() { - cc.Init(&cc.Config{ - RootCmd: commands.RootCmd, - Headings: cc.HiBlue + cc.Bold, - Commands: cc.HiBlue + cc.Bold, - CmdShortDescr: cc.HiBlue, - Example: cc.HiBlue + cc.Italic, - ExecName: cc.HiBlue + cc.Bold, - Flags: cc.HiBlue + cc.Bold, - FlagsDescr: cc.HiBlue, - NoExtraNewlines: true, - NoBottomNewline: true, - }) - commands.Execute() -} + //cobra-cli + cli.Execute() -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/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 diff --git a/cmd/skywire-cli/README.md b/cmd/skywire-cli/README.md index 4ae5a12a3..463f876e5 100644 --- a/cmd/skywire-cli/README.md +++ b/cmd/skywire-cli/README.md @@ -389,7 +389,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 e411ae58b..2a33afb38 100644 --- a/cmd/skywire-cli/commands/config/gen.go +++ b/cmd/skywire-cli/commands/config/gen.go @@ -858,7 +858,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, @@ -1199,7 +1199,7 @@ const envfileLinux = `# #VERSION='' #-- Set app bin_path -#BINPATH='./apps' +#BINPATH='./build/apps' #-- Set server public key for proxy client to connect to #PROXYCLIENTPK='' @@ -1308,7 +1308,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/cmd/skywire-deployment/skywire.go b/cmd/skywire-deployment/skywire.go index 6f67fcd12..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/commands" + 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 49826e2d8..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/commands" + 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/go.mod b/go.mod index f5637f9ce..99313b706 100644 --- a/go.mod +++ b/go.mod @@ -10,6 +10,7 @@ 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/elazarl/goproxy v0.0.0-20231117061959-7cc037d33fb5 github.com/gen2brain/dlgs v0.0.0-20220603100644-40c77870fa8d @@ -17,6 +18,7 @@ require ( github.com/go-chi/chi/v5 v5.0.11 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 @@ -44,7 +46,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.0-20230223181233-21636207a675 @@ -96,6 +98,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 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()) diff --git a/pkg/skyenv/skyenv.go b/pkg/skyenv/skyenv.go index 544e0937e..39ec8fb6d 100644 --- a/pkg/skyenv/skyenv.go +++ b/pkg/skyenv/skyenv.go @@ -80,7 +80,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 a57b5fdfe..888c3c072 100644 --- a/pkg/skyenv/skyenv_linux.go +++ b/pkg/skyenv/skyenv_linux.go @@ -16,7 +16,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/config.go b/pkg/visor/visorconfig/config.go index d13fdfadd..dae171f1c 100644 --- a/pkg/visor/visorconfig/config.go +++ b/pkg/visor/visorconfig/config.go @@ -245,7 +245,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, diff --git a/pkg/visor/visorconfig/values_windows.go b/pkg/visor/visorconfig/values_windows.go index 6cc4cfb18..647437bcd 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", diff --git a/skywire.conf b/skywire.conf index ca79c8be7..83eabaac1 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") 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/gorilla/mux/AUTHORS b/vendor/github.com/gorilla/mux/AUTHORS new file mode 100644 index 000000000..b722392ee --- /dev/null +++ b/vendor/github.com/gorilla/mux/AUTHORS @@ -0,0 +1,8 @@ +# This is the official list of gorilla/mux authors for copyright purposes. +# +# Please keep the list sorted. + +Google LLC (https://opensource.google.com/) +Kamil Kisielk +Matt Silverlock +Rodrigo Moraes (https://github.com/moraes) diff --git a/vendor/github.com/gorilla/mux/LICENSE b/vendor/github.com/gorilla/mux/LICENSE new file mode 100644 index 000000000..6903df638 --- /dev/null +++ b/vendor/github.com/gorilla/mux/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2012-2018 The Gorilla Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/gorilla/mux/README.md b/vendor/github.com/gorilla/mux/README.md new file mode 100644 index 000000000..35eea9f10 --- /dev/null +++ b/vendor/github.com/gorilla/mux/README.md @@ -0,0 +1,805 @@ +# gorilla/mux + +[![GoDoc](https://godoc.org/github.com/gorilla/mux?status.svg)](https://godoc.org/github.com/gorilla/mux) +[![CircleCI](https://circleci.com/gh/gorilla/mux.svg?style=svg)](https://circleci.com/gh/gorilla/mux) +[![Sourcegraph](https://sourcegraph.com/github.com/gorilla/mux/-/badge.svg)](https://sourcegraph.com/github.com/gorilla/mux?badge) + +![Gorilla Logo](https://cloud-cdn.questionable.services/gorilla-icon-64.png) + +https://www.gorillatoolkit.org/pkg/mux + +Package `gorilla/mux` implements a request router and dispatcher for matching incoming requests to +their respective handler. + +The name mux stands for "HTTP request multiplexer". Like the standard `http.ServeMux`, `mux.Router` matches incoming requests against a list of registered routes and calls a handler for the route that matches the URL or other conditions. The main features are: + +* It implements the `http.Handler` interface so it is compatible with the standard `http.ServeMux`. +* Requests can be matched based on URL host, path, path prefix, schemes, header and query values, HTTP methods or using custom matchers. +* URL hosts, paths and query values can have variables with an optional regular expression. +* Registered URLs can be built, or "reversed", which helps maintaining references to resources. +* Routes can be used as subrouters: nested routes are only tested if the parent route matches. This is useful to define groups of routes that share common conditions like a host, a path prefix or other repeated attributes. As a bonus, this optimizes request matching. + +--- + +* [Install](#install) +* [Examples](#examples) +* [Matching Routes](#matching-routes) +* [Static Files](#static-files) +* [Serving Single Page Applications](#serving-single-page-applications) (e.g. React, Vue, Ember.js, etc.) +* [Registered URLs](#registered-urls) +* [Walking Routes](#walking-routes) +* [Graceful Shutdown](#graceful-shutdown) +* [Middleware](#middleware) +* [Handling CORS Requests](#handling-cors-requests) +* [Testing Handlers](#testing-handlers) +* [Full Example](#full-example) + +--- + +## Install + +With a [correctly configured](https://golang.org/doc/install#testing) Go toolchain: + +```sh +go get -u github.com/gorilla/mux +``` + +## Examples + +Let's start registering a couple of URL paths and handlers: + +```go +func main() { + r := mux.NewRouter() + r.HandleFunc("/", HomeHandler) + r.HandleFunc("/products", ProductsHandler) + r.HandleFunc("/articles", ArticlesHandler) + http.Handle("/", r) +} +``` + +Here we register three routes mapping URL paths to handlers. This is equivalent to how `http.HandleFunc()` works: if an incoming request URL matches one of the paths, the corresponding handler is called passing (`http.ResponseWriter`, `*http.Request`) as parameters. + +Paths can have variables. They are defined using the format `{name}` or `{name:pattern}`. If a regular expression pattern is not defined, the matched variable will be anything until the next slash. For example: + +```go +r := mux.NewRouter() +r.HandleFunc("/products/{key}", ProductHandler) +r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) +r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) +``` + +The names are used to create a map of route variables which can be retrieved calling `mux.Vars()`: + +```go +func ArticlesCategoryHandler(w http.ResponseWriter, r *http.Request) { + vars := mux.Vars(r) + w.WriteHeader(http.StatusOK) + fmt.Fprintf(w, "Category: %v\n", vars["category"]) +} +``` + +And this is all you need to know about the basic usage. More advanced options are explained below. + +### Matching Routes + +Routes can also be restricted to a domain or subdomain. Just define a host pattern to be matched. They can also have variables: + +```go +r := mux.NewRouter() +// Only matches if domain is "www.example.com". +r.Host("www.example.com") +// Matches a dynamic subdomain. +r.Host("{subdomain:[a-z]+}.example.com") +``` + +There are several other matchers that can be added. To match path prefixes: + +```go +r.PathPrefix("/products/") +``` + +...or HTTP methods: + +```go +r.Methods("GET", "POST") +``` + +...or URL schemes: + +```go +r.Schemes("https") +``` + +...or header values: + +```go +r.Headers("X-Requested-With", "XMLHttpRequest") +``` + +...or query values: + +```go +r.Queries("key", "value") +``` + +...or to use a custom matcher function: + +```go +r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { + return r.ProtoMajor == 0 +}) +``` + +...and finally, it is possible to combine several matchers in a single route: + +```go +r.HandleFunc("/products", ProductsHandler). + Host("www.example.com"). + Methods("GET"). + Schemes("http") +``` + +Routes are tested in the order they were added to the router. If two routes match, the first one wins: + +```go +r := mux.NewRouter() +r.HandleFunc("/specific", specificHandler) +r.PathPrefix("/").Handler(catchAllHandler) +``` + +Setting the same matching conditions again and again can be boring, so we have a way to group several routes that share the same requirements. We call it "subrouting". + +For example, let's say we have several URLs that should only match when the host is `www.example.com`. Create a route for that host and get a "subrouter" from it: + +```go +r := mux.NewRouter() +s := r.Host("www.example.com").Subrouter() +``` + +Then register routes in the subrouter: + +```go +s.HandleFunc("/products/", ProductsHandler) +s.HandleFunc("/products/{key}", ProductHandler) +s.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) +``` + +The three URL paths we registered above will only be tested if the domain is `www.example.com`, because the subrouter is tested first. This is not only convenient, but also optimizes request matching. You can create subrouters combining any attribute matchers accepted by a route. + +Subrouters can be used to create domain or path "namespaces": you define subrouters in a central place and then parts of the app can register its paths relatively to a given subrouter. + +There's one more thing about subroutes. When a subrouter has a path prefix, the inner routes use it as base for their paths: + +```go +r := mux.NewRouter() +s := r.PathPrefix("/products").Subrouter() +// "/products/" +s.HandleFunc("/", ProductsHandler) +// "/products/{key}/" +s.HandleFunc("/{key}/", ProductHandler) +// "/products/{key}/details" +s.HandleFunc("/{key}/details", ProductDetailsHandler) +``` + + +### Static Files + +Note that the path provided to `PathPrefix()` represents a "wildcard": calling +`PathPrefix("/static/").Handler(...)` means that the handler will be passed any +request that matches "/static/\*". This makes it easy to serve static files with mux: + +```go +func main() { + var dir string + + flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") + flag.Parse() + r := mux.NewRouter() + + // This will serve files under http://localhost:8000/static/ + r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) + + srv := &http.Server{ + Handler: r, + Addr: "127.0.0.1:8000", + // Good practice: enforce timeouts for servers you create! + WriteTimeout: 15 * time.Second, + ReadTimeout: 15 * time.Second, + } + + log.Fatal(srv.ListenAndServe()) +} +``` + +### Serving Single Page Applications + +Most of the time it makes sense to serve your SPA on a separate web server from your API, +but sometimes it's desirable to serve them both from one place. It's possible to write a simple +handler for serving your SPA (for use with React Router's [BrowserRouter](https://reacttraining.com/react-router/web/api/BrowserRouter) for example), and leverage +mux's powerful routing for your API endpoints. + +```go +package main + +import ( + "encoding/json" + "log" + "net/http" + "os" + "path/filepath" + "time" + + "github.com/gorilla/mux" +) + +// spaHandler implements the http.Handler interface, so we can use it +// to respond to HTTP requests. The path to the static directory and +// path to the index file within that static directory are used to +// serve the SPA in the given static directory. +type spaHandler struct { + staticPath string + indexPath string +} + +// ServeHTTP inspects the URL path to locate a file within the static dir +// on the SPA handler. If a file is found, it will be served. If not, the +// file located at the index path on the SPA handler will be served. This +// is suitable behavior for serving an SPA (single page application). +func (h spaHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { + // get the absolute path to prevent directory traversal + path, err := filepath.Abs(r.URL.Path) + if err != nil { + // if we failed to get the absolute path respond with a 400 bad request + // and stop + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + + // prepend the path with the path to the static directory + path = filepath.Join(h.staticPath, path) + + // check whether a file exists at the given path + _, err = os.Stat(path) + if os.IsNotExist(err) { + // file does not exist, serve index.html + http.ServeFile(w, r, filepath.Join(h.staticPath, h.indexPath)) + return + } else if err != nil { + // if we got an error (that wasn't that the file doesn't exist) stating the + // file, return a 500 internal server error and stop + http.Error(w, err.Error(), http.StatusInternalServerError) + return + } + + // otherwise, use http.FileServer to serve the static dir + http.FileServer(http.Dir(h.staticPath)).ServeHTTP(w, r) +} + +func main() { + router := mux.NewRouter() + + router.HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) { + // an example API handler + json.NewEncoder(w).Encode(map[string]bool{"ok": true}) + }) + + spa := spaHandler{staticPath: "build", indexPath: "index.html"} + router.PathPrefix("/").Handler(spa) + + srv := &http.Server{ + Handler: router, + Addr: "127.0.0.1:8000", + // Good practice: enforce timeouts for servers you create! + WriteTimeout: 15 * time.Second, + ReadTimeout: 15 * time.Second, + } + + log.Fatal(srv.ListenAndServe()) +} +``` + +### Registered URLs + +Now let's see how to build registered URLs. + +Routes can be named. All routes that define a name can have their URLs built, or "reversed". We define a name calling `Name()` on a route. For example: + +```go +r := mux.NewRouter() +r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). + Name("article") +``` + +To build a URL, get the route and call the `URL()` method, passing a sequence of key/value pairs for the route variables. For the previous route, we would do: + +```go +url, err := r.Get("article").URL("category", "technology", "id", "42") +``` + +...and the result will be a `url.URL` with the following path: + +``` +"/articles/technology/42" +``` + +This also works for host and query value variables: + +```go +r := mux.NewRouter() +r.Host("{subdomain}.example.com"). + Path("/articles/{category}/{id:[0-9]+}"). + Queries("filter", "{filter}"). + HandlerFunc(ArticleHandler). + Name("article") + +// url.String() will be "http://news.example.com/articles/technology/42?filter=gorilla" +url, err := r.Get("article").URL("subdomain", "news", + "category", "technology", + "id", "42", + "filter", "gorilla") +``` + +All variables defined in the route are required, and their values must conform to the corresponding patterns. These requirements guarantee that a generated URL will always match a registered route -- the only exception is for explicitly defined "build-only" routes which never match. + +Regex support also exists for matching Headers within a route. For example, we could do: + +```go +r.HeadersRegexp("Content-Type", "application/(text|json)") +``` + +...and the route will match both requests with a Content-Type of `application/json` as well as `application/text` + +There's also a way to build only the URL host or path for a route: use the methods `URLHost()` or `URLPath()` instead. For the previous route, we would do: + +```go +// "http://news.example.com/" +host, err := r.Get("article").URLHost("subdomain", "news") + +// "/articles/technology/42" +path, err := r.Get("article").URLPath("category", "technology", "id", "42") +``` + +And if you use subrouters, host and path defined separately can be built as well: + +```go +r := mux.NewRouter() +s := r.Host("{subdomain}.example.com").Subrouter() +s.Path("/articles/{category}/{id:[0-9]+}"). + HandlerFunc(ArticleHandler). + Name("article") + +// "http://news.example.com/articles/technology/42" +url, err := r.Get("article").URL("subdomain", "news", + "category", "technology", + "id", "42") +``` + +### Walking Routes + +The `Walk` function on `mux.Router` can be used to visit all of the routes that are registered on a router. For example, +the following prints all of the registered routes: + +```go +package main + +import ( + "fmt" + "net/http" + "strings" + + "github.com/gorilla/mux" +) + +func handler(w http.ResponseWriter, r *http.Request) { + return +} + +func main() { + r := mux.NewRouter() + r.HandleFunc("/", handler) + r.HandleFunc("/products", handler).Methods("POST") + r.HandleFunc("/articles", handler).Methods("GET") + r.HandleFunc("/articles/{id}", handler).Methods("GET", "PUT") + r.HandleFunc("/authors", handler).Queries("surname", "{surname}") + err := r.Walk(func(route *mux.Route, router *mux.Router, ancestors []*mux.Route) error { + pathTemplate, err := route.GetPathTemplate() + if err == nil { + fmt.Println("ROUTE:", pathTemplate) + } + pathRegexp, err := route.GetPathRegexp() + if err == nil { + fmt.Println("Path regexp:", pathRegexp) + } + queriesTemplates, err := route.GetQueriesTemplates() + if err == nil { + fmt.Println("Queries templates:", strings.Join(queriesTemplates, ",")) + } + queriesRegexps, err := route.GetQueriesRegexp() + if err == nil { + fmt.Println("Queries regexps:", strings.Join(queriesRegexps, ",")) + } + methods, err := route.GetMethods() + if err == nil { + fmt.Println("Methods:", strings.Join(methods, ",")) + } + fmt.Println() + return nil + }) + + if err != nil { + fmt.Println(err) + } + + http.Handle("/", r) +} +``` + +### Graceful Shutdown + +Go 1.8 introduced the ability to [gracefully shutdown](https://golang.org/doc/go1.8#http_shutdown) a `*http.Server`. Here's how to do that alongside `mux`: + +```go +package main + +import ( + "context" + "flag" + "log" + "net/http" + "os" + "os/signal" + "time" + + "github.com/gorilla/mux" +) + +func main() { + var wait time.Duration + flag.DurationVar(&wait, "graceful-timeout", time.Second * 15, "the duration for which the server gracefully wait for existing connections to finish - e.g. 15s or 1m") + flag.Parse() + + r := mux.NewRouter() + // Add your routes as needed + + srv := &http.Server{ + Addr: "0.0.0.0:8080", + // Good practice to set timeouts to avoid Slowloris attacks. + WriteTimeout: time.Second * 15, + ReadTimeout: time.Second * 15, + IdleTimeout: time.Second * 60, + Handler: r, // Pass our instance of gorilla/mux in. + } + + // Run our server in a goroutine so that it doesn't block. + go func() { + if err := srv.ListenAndServe(); err != nil { + log.Println(err) + } + }() + + c := make(chan os.Signal, 1) + // We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C) + // SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught. + signal.Notify(c, os.Interrupt) + + // Block until we receive our signal. + <-c + + // Create a deadline to wait for. + ctx, cancel := context.WithTimeout(context.Background(), wait) + defer cancel() + // Doesn't block if no connections, but will otherwise wait + // until the timeout deadline. + srv.Shutdown(ctx) + // Optionally, you could run srv.Shutdown in a goroutine and block on + // <-ctx.Done() if your application should wait for other services + // to finalize based on context cancellation. + log.Println("shutting down") + os.Exit(0) +} +``` + +### Middleware + +Mux supports the addition of middlewares to a [Router](https://godoc.org/github.com/gorilla/mux#Router), which are executed in the order they are added if a match is found, including its subrouters. +Middlewares are (typically) small pieces of code which take one request, do something with it, and pass it down to another middleware or the final handler. Some common use cases for middleware are request logging, header manipulation, or `ResponseWriter` hijacking. + +Mux middlewares are defined using the de facto standard type: + +```go +type MiddlewareFunc func(http.Handler) http.Handler +``` + +Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed to it, and then calls the handler passed as parameter to the MiddlewareFunc. This takes advantage of closures being able access variables from the context where they are created, while retaining the signature enforced by the receivers. + +A very basic middleware which logs the URI of the request being handled could be written as: + +```go +func loggingMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Do stuff here + log.Println(r.RequestURI) + // Call the next handler, which can be another middleware in the chain, or the final handler. + next.ServeHTTP(w, r) + }) +} +``` + +Middlewares can be added to a router using `Router.Use()`: + +```go +r := mux.NewRouter() +r.HandleFunc("/", handler) +r.Use(loggingMiddleware) +``` + +A more complex authentication middleware, which maps session token to users, could be written as: + +```go +// Define our struct +type authenticationMiddleware struct { + tokenUsers map[string]string +} + +// Initialize it somewhere +func (amw *authenticationMiddleware) Populate() { + amw.tokenUsers["00000000"] = "user0" + amw.tokenUsers["aaaaaaaa"] = "userA" + amw.tokenUsers["05f717e5"] = "randomUser" + amw.tokenUsers["deadbeef"] = "user0" +} + +// Middleware function, which will be called for each request +func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + token := r.Header.Get("X-Session-Token") + + if user, found := amw.tokenUsers[token]; found { + // We found the token in our map + log.Printf("Authenticated user %s\n", user) + // Pass down the request to the next middleware (or final handler) + next.ServeHTTP(w, r) + } else { + // Write an error and stop the handler chain + http.Error(w, "Forbidden", http.StatusForbidden) + } + }) +} +``` + +```go +r := mux.NewRouter() +r.HandleFunc("/", handler) + +amw := authenticationMiddleware{} +amw.Populate() + +r.Use(amw.Middleware) +``` + +Note: The handler chain will be stopped if your middleware doesn't call `next.ServeHTTP()` with the corresponding parameters. This can be used to abort a request if the middleware writer wants to. Middlewares _should_ write to `ResponseWriter` if they _are_ going to terminate the request, and they _should not_ write to `ResponseWriter` if they _are not_ going to terminate it. + +### Handling CORS Requests + +[CORSMethodMiddleware](https://godoc.org/github.com/gorilla/mux#CORSMethodMiddleware) intends to make it easier to strictly set the `Access-Control-Allow-Methods` response header. + +* You will still need to use your own CORS handler to set the other CORS headers such as `Access-Control-Allow-Origin` +* The middleware will set the `Access-Control-Allow-Methods` header to all the method matchers (e.g. `r.Methods(http.MethodGet, http.MethodPut, http.MethodOptions)` -> `Access-Control-Allow-Methods: GET,PUT,OPTIONS`) on a route +* If you do not specify any methods, then: +> _Important_: there must be an `OPTIONS` method matcher for the middleware to set the headers. + +Here is an example of using `CORSMethodMiddleware` along with a custom `OPTIONS` handler to set all the required CORS headers: + +```go +package main + +import ( + "net/http" + "github.com/gorilla/mux" +) + +func main() { + r := mux.NewRouter() + + // IMPORTANT: you must specify an OPTIONS method matcher for the middleware to set CORS headers + r.HandleFunc("/foo", fooHandler).Methods(http.MethodGet, http.MethodPut, http.MethodPatch, http.MethodOptions) + r.Use(mux.CORSMethodMiddleware(r)) + + http.ListenAndServe(":8080", r) +} + +func fooHandler(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Access-Control-Allow-Origin", "*") + if r.Method == http.MethodOptions { + return + } + + w.Write([]byte("foo")) +} +``` + +And an request to `/foo` using something like: + +```bash +curl localhost:8080/foo -v +``` + +Would look like: + +```bash +* Trying ::1... +* TCP_NODELAY set +* Connected to localhost (::1) port 8080 (#0) +> GET /foo HTTP/1.1 +> Host: localhost:8080 +> User-Agent: curl/7.59.0 +> Accept: */* +> +< HTTP/1.1 200 OK +< Access-Control-Allow-Methods: GET,PUT,PATCH,OPTIONS +< Access-Control-Allow-Origin: * +< Date: Fri, 28 Jun 2019 20:13:30 GMT +< Content-Length: 3 +< Content-Type: text/plain; charset=utf-8 +< +* Connection #0 to host localhost left intact +foo +``` + +### Testing Handlers + +Testing handlers in a Go web application is straightforward, and _mux_ doesn't complicate this any further. Given two files: `endpoints.go` and `endpoints_test.go`, here's how we'd test an application using _mux_. + +First, our simple HTTP handler: + +```go +// endpoints.go +package main + +func HealthCheckHandler(w http.ResponseWriter, r *http.Request) { + // A very simple health check. + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusOK) + + // In the future we could report back on the status of our DB, or our cache + // (e.g. Redis) by performing a simple PING, and include them in the response. + io.WriteString(w, `{"alive": true}`) +} + +func main() { + r := mux.NewRouter() + r.HandleFunc("/health", HealthCheckHandler) + + log.Fatal(http.ListenAndServe("localhost:8080", r)) +} +``` + +Our test code: + +```go +// endpoints_test.go +package main + +import ( + "net/http" + "net/http/httptest" + "testing" +) + +func TestHealthCheckHandler(t *testing.T) { + // Create a request to pass to our handler. We don't have any query parameters for now, so we'll + // pass 'nil' as the third parameter. + req, err := http.NewRequest("GET", "/health", nil) + if err != nil { + t.Fatal(err) + } + + // We create a ResponseRecorder (which satisfies http.ResponseWriter) to record the response. + rr := httptest.NewRecorder() + handler := http.HandlerFunc(HealthCheckHandler) + + // Our handlers satisfy http.Handler, so we can call their ServeHTTP method + // directly and pass in our Request and ResponseRecorder. + handler.ServeHTTP(rr, req) + + // Check the status code is what we expect. + if status := rr.Code; status != http.StatusOK { + t.Errorf("handler returned wrong status code: got %v want %v", + status, http.StatusOK) + } + + // Check the response body is what we expect. + expected := `{"alive": true}` + if rr.Body.String() != expected { + t.Errorf("handler returned unexpected body: got %v want %v", + rr.Body.String(), expected) + } +} +``` + +In the case that our routes have [variables](#examples), we can pass those in the request. We could write +[table-driven tests](https://dave.cheney.net/2013/06/09/writing-table-driven-tests-in-go) to test multiple +possible route variables as needed. + +```go +// endpoints.go +func main() { + r := mux.NewRouter() + // A route with a route variable: + r.HandleFunc("/metrics/{type}", MetricsHandler) + + log.Fatal(http.ListenAndServe("localhost:8080", r)) +} +``` + +Our test file, with a table-driven test of `routeVariables`: + +```go +// endpoints_test.go +func TestMetricsHandler(t *testing.T) { + tt := []struct{ + routeVariable string + shouldPass bool + }{ + {"goroutines", true}, + {"heap", true}, + {"counters", true}, + {"queries", true}, + {"adhadaeqm3k", false}, + } + + for _, tc := range tt { + path := fmt.Sprintf("/metrics/%s", tc.routeVariable) + req, err := http.NewRequest("GET", path, nil) + if err != nil { + t.Fatal(err) + } + + rr := httptest.NewRecorder() + + // Need to create a router that we can pass the request through so that the vars will be added to the context + router := mux.NewRouter() + router.HandleFunc("/metrics/{type}", MetricsHandler) + router.ServeHTTP(rr, req) + + // In this case, our MetricsHandler returns a non-200 response + // for a route variable it doesn't know about. + if rr.Code == http.StatusOK && !tc.shouldPass { + t.Errorf("handler should have failed on routeVariable %s: got %v want %v", + tc.routeVariable, rr.Code, http.StatusOK) + } + } +} +``` + +## Full Example + +Here's a complete, runnable example of a small `mux` based server: + +```go +package main + +import ( + "net/http" + "log" + "github.com/gorilla/mux" +) + +func YourHandler(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("Gorilla!\n")) +} + +func main() { + r := mux.NewRouter() + // Routes consist of a path and a handler function. + r.HandleFunc("/", YourHandler) + + // Bind to a port and pass our router in + log.Fatal(http.ListenAndServe(":8000", r)) +} +``` + +## License + +BSD licensed. See the LICENSE file for details. diff --git a/vendor/github.com/gorilla/mux/doc.go b/vendor/github.com/gorilla/mux/doc.go new file mode 100644 index 000000000..bd5a38b55 --- /dev/null +++ b/vendor/github.com/gorilla/mux/doc.go @@ -0,0 +1,306 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +/* +Package mux implements a request router and dispatcher. + +The name mux stands for "HTTP request multiplexer". Like the standard +http.ServeMux, mux.Router matches incoming requests against a list of +registered routes and calls a handler for the route that matches the URL +or other conditions. The main features are: + + * Requests can be matched based on URL host, path, path prefix, schemes, + header and query values, HTTP methods or using custom matchers. + * URL hosts, paths and query values can have variables with an optional + regular expression. + * Registered URLs can be built, or "reversed", which helps maintaining + references to resources. + * Routes can be used as subrouters: nested routes are only tested if the + parent route matches. This is useful to define groups of routes that + share common conditions like a host, a path prefix or other repeated + attributes. As a bonus, this optimizes request matching. + * It implements the http.Handler interface so it is compatible with the + standard http.ServeMux. + +Let's start registering a couple of URL paths and handlers: + + func main() { + r := mux.NewRouter() + r.HandleFunc("/", HomeHandler) + r.HandleFunc("/products", ProductsHandler) + r.HandleFunc("/articles", ArticlesHandler) + http.Handle("/", r) + } + +Here we register three routes mapping URL paths to handlers. This is +equivalent to how http.HandleFunc() works: if an incoming request URL matches +one of the paths, the corresponding handler is called passing +(http.ResponseWriter, *http.Request) as parameters. + +Paths can have variables. They are defined using the format {name} or +{name:pattern}. If a regular expression pattern is not defined, the matched +variable will be anything until the next slash. For example: + + r := mux.NewRouter() + r.HandleFunc("/products/{key}", ProductHandler) + r.HandleFunc("/articles/{category}/", ArticlesCategoryHandler) + r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler) + +Groups can be used inside patterns, as long as they are non-capturing (?:re). For example: + + r.HandleFunc("/articles/{category}/{sort:(?:asc|desc|new)}", ArticlesCategoryHandler) + +The names are used to create a map of route variables which can be retrieved +calling mux.Vars(): + + vars := mux.Vars(request) + category := vars["category"] + +Note that if any capturing groups are present, mux will panic() during parsing. To prevent +this, convert any capturing groups to non-capturing, e.g. change "/{sort:(asc|desc)}" to +"/{sort:(?:asc|desc)}". This is a change from prior versions which behaved unpredictably +when capturing groups were present. + +And this is all you need to know about the basic usage. More advanced options +are explained below. + +Routes can also be restricted to a domain or subdomain. Just define a host +pattern to be matched. They can also have variables: + + r := mux.NewRouter() + // Only matches if domain is "www.example.com". + r.Host("www.example.com") + // Matches a dynamic subdomain. + r.Host("{subdomain:[a-z]+}.domain.com") + +There are several other matchers that can be added. To match path prefixes: + + r.PathPrefix("/products/") + +...or HTTP methods: + + r.Methods("GET", "POST") + +...or URL schemes: + + r.Schemes("https") + +...or header values: + + r.Headers("X-Requested-With", "XMLHttpRequest") + +...or query values: + + r.Queries("key", "value") + +...or to use a custom matcher function: + + r.MatcherFunc(func(r *http.Request, rm *RouteMatch) bool { + return r.ProtoMajor == 0 + }) + +...and finally, it is possible to combine several matchers in a single route: + + r.HandleFunc("/products", ProductsHandler). + Host("www.example.com"). + Methods("GET"). + Schemes("http") + +Setting the same matching conditions again and again can be boring, so we have +a way to group several routes that share the same requirements. +We call it "subrouting". + +For example, let's say we have several URLs that should only match when the +host is "www.example.com". Create a route for that host and get a "subrouter" +from it: + + r := mux.NewRouter() + s := r.Host("www.example.com").Subrouter() + +Then register routes in the subrouter: + + s.HandleFunc("/products/", ProductsHandler) + s.HandleFunc("/products/{key}", ProductHandler) + s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) + +The three URL paths we registered above will only be tested if the domain is +"www.example.com", because the subrouter is tested first. This is not +only convenient, but also optimizes request matching. You can create +subrouters combining any attribute matchers accepted by a route. + +Subrouters can be used to create domain or path "namespaces": you define +subrouters in a central place and then parts of the app can register its +paths relatively to a given subrouter. + +There's one more thing about subroutes. When a subrouter has a path prefix, +the inner routes use it as base for their paths: + + r := mux.NewRouter() + s := r.PathPrefix("/products").Subrouter() + // "/products/" + s.HandleFunc("/", ProductsHandler) + // "/products/{key}/" + s.HandleFunc("/{key}/", ProductHandler) + // "/products/{key}/details" + s.HandleFunc("/{key}/details", ProductDetailsHandler) + +Note that the path provided to PathPrefix() represents a "wildcard": calling +PathPrefix("/static/").Handler(...) means that the handler will be passed any +request that matches "/static/*". This makes it easy to serve static files with mux: + + func main() { + var dir string + + flag.StringVar(&dir, "dir", ".", "the directory to serve files from. Defaults to the current dir") + flag.Parse() + r := mux.NewRouter() + + // This will serve files under http://localhost:8000/static/ + r.PathPrefix("/static/").Handler(http.StripPrefix("/static/", http.FileServer(http.Dir(dir)))) + + srv := &http.Server{ + Handler: r, + Addr: "127.0.0.1:8000", + // Good practice: enforce timeouts for servers you create! + WriteTimeout: 15 * time.Second, + ReadTimeout: 15 * time.Second, + } + + log.Fatal(srv.ListenAndServe()) + } + +Now let's see how to build registered URLs. + +Routes can be named. All routes that define a name can have their URLs built, +or "reversed". We define a name calling Name() on a route. For example: + + r := mux.NewRouter() + r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). + Name("article") + +To build a URL, get the route and call the URL() method, passing a sequence of +key/value pairs for the route variables. For the previous route, we would do: + + url, err := r.Get("article").URL("category", "technology", "id", "42") + +...and the result will be a url.URL with the following path: + + "/articles/technology/42" + +This also works for host and query value variables: + + r := mux.NewRouter() + r.Host("{subdomain}.domain.com"). + Path("/articles/{category}/{id:[0-9]+}"). + Queries("filter", "{filter}"). + HandlerFunc(ArticleHandler). + Name("article") + + // url.String() will be "http://news.domain.com/articles/technology/42?filter=gorilla" + url, err := r.Get("article").URL("subdomain", "news", + "category", "technology", + "id", "42", + "filter", "gorilla") + +All variables defined in the route are required, and their values must +conform to the corresponding patterns. These requirements guarantee that a +generated URL will always match a registered route -- the only exception is +for explicitly defined "build-only" routes which never match. + +Regex support also exists for matching Headers within a route. For example, we could do: + + r.HeadersRegexp("Content-Type", "application/(text|json)") + +...and the route will match both requests with a Content-Type of `application/json` as well as +`application/text` + +There's also a way to build only the URL host or path for a route: +use the methods URLHost() or URLPath() instead. For the previous route, +we would do: + + // "http://news.domain.com/" + host, err := r.Get("article").URLHost("subdomain", "news") + + // "/articles/technology/42" + path, err := r.Get("article").URLPath("category", "technology", "id", "42") + +And if you use subrouters, host and path defined separately can be built +as well: + + r := mux.NewRouter() + s := r.Host("{subdomain}.domain.com").Subrouter() + s.Path("/articles/{category}/{id:[0-9]+}"). + HandlerFunc(ArticleHandler). + Name("article") + + // "http://news.domain.com/articles/technology/42" + url, err := r.Get("article").URL("subdomain", "news", + "category", "technology", + "id", "42") + +Mux supports the addition of middlewares to a Router, which are executed in the order they are added if a match is found, including its subrouters. Middlewares are (typically) small pieces of code which take one request, do something with it, and pass it down to another middleware or the final handler. Some common use cases for middleware are request logging, header manipulation, or ResponseWriter hijacking. + + type MiddlewareFunc func(http.Handler) http.Handler + +Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed to it, and then calls the handler passed as parameter to the MiddlewareFunc (closures can access variables from the context where they are created). + +A very basic middleware which logs the URI of the request being handled could be written as: + + func simpleMw(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Do stuff here + log.Println(r.RequestURI) + // Call the next handler, which can be another middleware in the chain, or the final handler. + next.ServeHTTP(w, r) + }) + } + +Middlewares can be added to a router using `Router.Use()`: + + r := mux.NewRouter() + r.HandleFunc("/", handler) + r.Use(simpleMw) + +A more complex authentication middleware, which maps session token to users, could be written as: + + // Define our struct + type authenticationMiddleware struct { + tokenUsers map[string]string + } + + // Initialize it somewhere + func (amw *authenticationMiddleware) Populate() { + amw.tokenUsers["00000000"] = "user0" + amw.tokenUsers["aaaaaaaa"] = "userA" + amw.tokenUsers["05f717e5"] = "randomUser" + amw.tokenUsers["deadbeef"] = "user0" + } + + // Middleware function, which will be called for each request + func (amw *authenticationMiddleware) Middleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + token := r.Header.Get("X-Session-Token") + + if user, found := amw.tokenUsers[token]; found { + // We found the token in our map + log.Printf("Authenticated user %s\n", user) + next.ServeHTTP(w, r) + } else { + http.Error(w, "Forbidden", http.StatusForbidden) + } + }) + } + + r := mux.NewRouter() + r.HandleFunc("/", handler) + + amw := authenticationMiddleware{tokenUsers: make(map[string]string)} + amw.Populate() + + r.Use(amw.Middleware) + +Note: The handler chain will be stopped if your middleware doesn't call `next.ServeHTTP()` with the corresponding parameters. This can be used to abort a request if the middleware writer wants to. + +*/ +package mux diff --git a/vendor/github.com/gorilla/mux/middleware.go b/vendor/github.com/gorilla/mux/middleware.go new file mode 100644 index 000000000..cb51c565e --- /dev/null +++ b/vendor/github.com/gorilla/mux/middleware.go @@ -0,0 +1,74 @@ +package mux + +import ( + "net/http" + "strings" +) + +// MiddlewareFunc is a function which receives an http.Handler and returns another http.Handler. +// Typically, the returned handler is a closure which does something with the http.ResponseWriter and http.Request passed +// to it, and then calls the handler passed as parameter to the MiddlewareFunc. +type MiddlewareFunc func(http.Handler) http.Handler + +// middleware interface is anything which implements a MiddlewareFunc named Middleware. +type middleware interface { + Middleware(handler http.Handler) http.Handler +} + +// Middleware allows MiddlewareFunc to implement the middleware interface. +func (mw MiddlewareFunc) Middleware(handler http.Handler) http.Handler { + return mw(handler) +} + +// Use appends a MiddlewareFunc to the chain. Middleware can be used to intercept or otherwise modify requests and/or responses, and are executed in the order that they are applied to the Router. +func (r *Router) Use(mwf ...MiddlewareFunc) { + for _, fn := range mwf { + r.middlewares = append(r.middlewares, fn) + } +} + +// useInterface appends a middleware to the chain. Middleware can be used to intercept or otherwise modify requests and/or responses, and are executed in the order that they are applied to the Router. +func (r *Router) useInterface(mw middleware) { + r.middlewares = append(r.middlewares, mw) +} + +// CORSMethodMiddleware automatically sets the Access-Control-Allow-Methods response header +// on requests for routes that have an OPTIONS method matcher to all the method matchers on +// the route. Routes that do not explicitly handle OPTIONS requests will not be processed +// by the middleware. See examples for usage. +func CORSMethodMiddleware(r *Router) MiddlewareFunc { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + allMethods, err := getAllMethodsForRoute(r, req) + if err == nil { + for _, v := range allMethods { + if v == http.MethodOptions { + w.Header().Set("Access-Control-Allow-Methods", strings.Join(allMethods, ",")) + } + } + } + + next.ServeHTTP(w, req) + }) + } +} + +// getAllMethodsForRoute returns all the methods from method matchers matching a given +// request. +func getAllMethodsForRoute(r *Router, req *http.Request) ([]string, error) { + var allMethods []string + + for _, route := range r.routes { + var match RouteMatch + if route.Match(req, &match) || match.MatchErr == ErrMethodMismatch { + methods, err := route.GetMethods() + if err != nil { + return nil, err + } + + allMethods = append(allMethods, methods...) + } + } + + return allMethods, nil +} diff --git a/vendor/github.com/gorilla/mux/mux.go b/vendor/github.com/gorilla/mux/mux.go new file mode 100644 index 000000000..782a34b22 --- /dev/null +++ b/vendor/github.com/gorilla/mux/mux.go @@ -0,0 +1,606 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mux + +import ( + "context" + "errors" + "fmt" + "net/http" + "path" + "regexp" +) + +var ( + // ErrMethodMismatch is returned when the method in the request does not match + // the method defined against the route. + ErrMethodMismatch = errors.New("method is not allowed") + // ErrNotFound is returned when no route match is found. + ErrNotFound = errors.New("no matching route was found") +) + +// NewRouter returns a new router instance. +func NewRouter() *Router { + return &Router{namedRoutes: make(map[string]*Route)} +} + +// Router registers routes to be matched and dispatches a handler. +// +// It implements the http.Handler interface, so it can be registered to serve +// requests: +// +// var router = mux.NewRouter() +// +// func main() { +// http.Handle("/", router) +// } +// +// Or, for Google App Engine, register it in a init() function: +// +// func init() { +// http.Handle("/", router) +// } +// +// This will send all incoming requests to the router. +type Router struct { + // Configurable Handler to be used when no route matches. + NotFoundHandler http.Handler + + // Configurable Handler to be used when the request method does not match the route. + MethodNotAllowedHandler http.Handler + + // Routes to be matched, in order. + routes []*Route + + // Routes by name for URL building. + namedRoutes map[string]*Route + + // If true, do not clear the request context after handling the request. + // + // Deprecated: No effect, since the context is stored on the request itself. + KeepContext bool + + // Slice of middlewares to be called after a match is found + middlewares []middleware + + // configuration shared with `Route` + routeConf +} + +// common route configuration shared between `Router` and `Route` +type routeConf struct { + // If true, "/path/foo%2Fbar/to" will match the path "/path/{var}/to" + useEncodedPath bool + + // If true, when the path pattern is "/path/", accessing "/path" will + // redirect to the former and vice versa. + strictSlash bool + + // If true, when the path pattern is "/path//to", accessing "/path//to" + // will not redirect + skipClean bool + + // Manager for the variables from host and path. + regexp routeRegexpGroup + + // List of matchers. + matchers []matcher + + // The scheme used when building URLs. + buildScheme string + + buildVarsFunc BuildVarsFunc +} + +// returns an effective deep copy of `routeConf` +func copyRouteConf(r routeConf) routeConf { + c := r + + if r.regexp.path != nil { + c.regexp.path = copyRouteRegexp(r.regexp.path) + } + + if r.regexp.host != nil { + c.regexp.host = copyRouteRegexp(r.regexp.host) + } + + c.regexp.queries = make([]*routeRegexp, 0, len(r.regexp.queries)) + for _, q := range r.regexp.queries { + c.regexp.queries = append(c.regexp.queries, copyRouteRegexp(q)) + } + + c.matchers = make([]matcher, len(r.matchers)) + copy(c.matchers, r.matchers) + + return c +} + +func copyRouteRegexp(r *routeRegexp) *routeRegexp { + c := *r + return &c +} + +// Match attempts to match the given request against the router's registered routes. +// +// If the request matches a route of this router or one of its subrouters the Route, +// Handler, and Vars fields of the the match argument are filled and this function +// returns true. +// +// If the request does not match any of this router's or its subrouters' routes +// then this function returns false. If available, a reason for the match failure +// will be filled in the match argument's MatchErr field. If the match failure type +// (eg: not found) has a registered handler, the handler is assigned to the Handler +// field of the match argument. +func (r *Router) Match(req *http.Request, match *RouteMatch) bool { + for _, route := range r.routes { + if route.Match(req, match) { + // Build middleware chain if no error was found + if match.MatchErr == nil { + for i := len(r.middlewares) - 1; i >= 0; i-- { + match.Handler = r.middlewares[i].Middleware(match.Handler) + } + } + return true + } + } + + if match.MatchErr == ErrMethodMismatch { + if r.MethodNotAllowedHandler != nil { + match.Handler = r.MethodNotAllowedHandler + return true + } + + return false + } + + // Closest match for a router (includes sub-routers) + if r.NotFoundHandler != nil { + match.Handler = r.NotFoundHandler + match.MatchErr = ErrNotFound + return true + } + + match.MatchErr = ErrNotFound + return false +} + +// ServeHTTP dispatches the handler registered in the matched route. +// +// When there is a match, the route variables can be retrieved calling +// mux.Vars(request). +func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) { + if !r.skipClean { + path := req.URL.Path + if r.useEncodedPath { + path = req.URL.EscapedPath() + } + // Clean path to canonical form and redirect. + if p := cleanPath(path); p != path { + + // Added 3 lines (Philip Schlump) - It was dropping the query string and #whatever from query. + // This matches with fix in go 1.2 r.c. 4 for same problem. Go Issue: + // http://code.google.com/p/go/issues/detail?id=5252 + url := *req.URL + url.Path = p + p = url.String() + + w.Header().Set("Location", p) + w.WriteHeader(http.StatusMovedPermanently) + return + } + } + var match RouteMatch + var handler http.Handler + if r.Match(req, &match) { + handler = match.Handler + req = requestWithVars(req, match.Vars) + req = requestWithRoute(req, match.Route) + } + + if handler == nil && match.MatchErr == ErrMethodMismatch { + handler = methodNotAllowedHandler() + } + + if handler == nil { + handler = http.NotFoundHandler() + } + + handler.ServeHTTP(w, req) +} + +// Get returns a route registered with the given name. +func (r *Router) Get(name string) *Route { + return r.namedRoutes[name] +} + +// GetRoute returns a route registered with the given name. This method +// was renamed to Get() and remains here for backwards compatibility. +func (r *Router) GetRoute(name string) *Route { + return r.namedRoutes[name] +} + +// StrictSlash defines the trailing slash behavior for new routes. The initial +// value is false. +// +// When true, if the route path is "/path/", accessing "/path" will perform a redirect +// to the former and vice versa. In other words, your application will always +// see the path as specified in the route. +// +// When false, if the route path is "/path", accessing "/path/" will not match +// this route and vice versa. +// +// The re-direct is a HTTP 301 (Moved Permanently). Note that when this is set for +// routes with a non-idempotent method (e.g. POST, PUT), the subsequent re-directed +// request will be made as a GET by most clients. Use middleware or client settings +// to modify this behaviour as needed. +// +// Special case: when a route sets a path prefix using the PathPrefix() method, +// strict slash is ignored for that route because the redirect behavior can't +// be determined from a prefix alone. However, any subrouters created from that +// route inherit the original StrictSlash setting. +func (r *Router) StrictSlash(value bool) *Router { + r.strictSlash = value + return r +} + +// SkipClean defines the path cleaning behaviour for new routes. The initial +// value is false. Users should be careful about which routes are not cleaned +// +// When true, if the route path is "/path//to", it will remain with the double +// slash. This is helpful if you have a route like: /fetch/http://xkcd.com/534/ +// +// When false, the path will be cleaned, so /fetch/http://xkcd.com/534/ will +// become /fetch/http/xkcd.com/534 +func (r *Router) SkipClean(value bool) *Router { + r.skipClean = value + return r +} + +// UseEncodedPath tells the router to match the encoded original path +// to the routes. +// For eg. "/path/foo%2Fbar/to" will match the path "/path/{var}/to". +// +// If not called, the router will match the unencoded path to the routes. +// For eg. "/path/foo%2Fbar/to" will match the path "/path/foo/bar/to" +func (r *Router) UseEncodedPath() *Router { + r.useEncodedPath = true + return r +} + +// ---------------------------------------------------------------------------- +// Route factories +// ---------------------------------------------------------------------------- + +// NewRoute registers an empty route. +func (r *Router) NewRoute() *Route { + // initialize a route with a copy of the parent router's configuration + route := &Route{routeConf: copyRouteConf(r.routeConf), namedRoutes: r.namedRoutes} + r.routes = append(r.routes, route) + return route +} + +// Name registers a new route with a name. +// See Route.Name(). +func (r *Router) Name(name string) *Route { + return r.NewRoute().Name(name) +} + +// Handle registers a new route with a matcher for the URL path. +// See Route.Path() and Route.Handler(). +func (r *Router) Handle(path string, handler http.Handler) *Route { + return r.NewRoute().Path(path).Handler(handler) +} + +// HandleFunc registers a new route with a matcher for the URL path. +// See Route.Path() and Route.HandlerFunc(). +func (r *Router) HandleFunc(path string, f func(http.ResponseWriter, + *http.Request)) *Route { + return r.NewRoute().Path(path).HandlerFunc(f) +} + +// Headers registers a new route with a matcher for request header values. +// See Route.Headers(). +func (r *Router) Headers(pairs ...string) *Route { + return r.NewRoute().Headers(pairs...) +} + +// Host registers a new route with a matcher for the URL host. +// See Route.Host(). +func (r *Router) Host(tpl string) *Route { + return r.NewRoute().Host(tpl) +} + +// MatcherFunc registers a new route with a custom matcher function. +// See Route.MatcherFunc(). +func (r *Router) MatcherFunc(f MatcherFunc) *Route { + return r.NewRoute().MatcherFunc(f) +} + +// Methods registers a new route with a matcher for HTTP methods. +// See Route.Methods(). +func (r *Router) Methods(methods ...string) *Route { + return r.NewRoute().Methods(methods...) +} + +// Path registers a new route with a matcher for the URL path. +// See Route.Path(). +func (r *Router) Path(tpl string) *Route { + return r.NewRoute().Path(tpl) +} + +// PathPrefix registers a new route with a matcher for the URL path prefix. +// See Route.PathPrefix(). +func (r *Router) PathPrefix(tpl string) *Route { + return r.NewRoute().PathPrefix(tpl) +} + +// Queries registers a new route with a matcher for URL query values. +// See Route.Queries(). +func (r *Router) Queries(pairs ...string) *Route { + return r.NewRoute().Queries(pairs...) +} + +// Schemes registers a new route with a matcher for URL schemes. +// See Route.Schemes(). +func (r *Router) Schemes(schemes ...string) *Route { + return r.NewRoute().Schemes(schemes...) +} + +// BuildVarsFunc registers a new route with a custom function for modifying +// route variables before building a URL. +func (r *Router) BuildVarsFunc(f BuildVarsFunc) *Route { + return r.NewRoute().BuildVarsFunc(f) +} + +// Walk walks the router and all its sub-routers, calling walkFn for each route +// in the tree. The routes are walked in the order they were added. Sub-routers +// are explored depth-first. +func (r *Router) Walk(walkFn WalkFunc) error { + return r.walk(walkFn, []*Route{}) +} + +// SkipRouter is used as a return value from WalkFuncs to indicate that the +// router that walk is about to descend down to should be skipped. +var SkipRouter = errors.New("skip this router") + +// WalkFunc is the type of the function called for each route visited by Walk. +// At every invocation, it is given the current route, and the current router, +// and a list of ancestor routes that lead to the current route. +type WalkFunc func(route *Route, router *Router, ancestors []*Route) error + +func (r *Router) walk(walkFn WalkFunc, ancestors []*Route) error { + for _, t := range r.routes { + err := walkFn(t, r, ancestors) + if err == SkipRouter { + continue + } + if err != nil { + return err + } + for _, sr := range t.matchers { + if h, ok := sr.(*Router); ok { + ancestors = append(ancestors, t) + err := h.walk(walkFn, ancestors) + if err != nil { + return err + } + ancestors = ancestors[:len(ancestors)-1] + } + } + if h, ok := t.handler.(*Router); ok { + ancestors = append(ancestors, t) + err := h.walk(walkFn, ancestors) + if err != nil { + return err + } + ancestors = ancestors[:len(ancestors)-1] + } + } + return nil +} + +// ---------------------------------------------------------------------------- +// Context +// ---------------------------------------------------------------------------- + +// RouteMatch stores information about a matched route. +type RouteMatch struct { + Route *Route + Handler http.Handler + Vars map[string]string + + // MatchErr is set to appropriate matching error + // It is set to ErrMethodMismatch if there is a mismatch in + // the request method and route method + MatchErr error +} + +type contextKey int + +const ( + varsKey contextKey = iota + routeKey +) + +// Vars returns the route variables for the current request, if any. +func Vars(r *http.Request) map[string]string { + if rv := r.Context().Value(varsKey); rv != nil { + return rv.(map[string]string) + } + return nil +} + +// CurrentRoute returns the matched route for the current request, if any. +// This only works when called inside the handler of the matched route +// because the matched route is stored in the request context which is cleared +// after the handler returns. +func CurrentRoute(r *http.Request) *Route { + if rv := r.Context().Value(routeKey); rv != nil { + return rv.(*Route) + } + return nil +} + +func requestWithVars(r *http.Request, vars map[string]string) *http.Request { + ctx := context.WithValue(r.Context(), varsKey, vars) + return r.WithContext(ctx) +} + +func requestWithRoute(r *http.Request, route *Route) *http.Request { + ctx := context.WithValue(r.Context(), routeKey, route) + return r.WithContext(ctx) +} + +// ---------------------------------------------------------------------------- +// Helpers +// ---------------------------------------------------------------------------- + +// cleanPath returns the canonical path for p, eliminating . and .. elements. +// Borrowed from the net/http package. +func cleanPath(p string) string { + if p == "" { + return "/" + } + if p[0] != '/' { + p = "/" + p + } + np := path.Clean(p) + // path.Clean removes trailing slash except for root; + // put the trailing slash back if necessary. + if p[len(p)-1] == '/' && np != "/" { + np += "/" + } + + return np +} + +// uniqueVars returns an error if two slices contain duplicated strings. +func uniqueVars(s1, s2 []string) error { + for _, v1 := range s1 { + for _, v2 := range s2 { + if v1 == v2 { + return fmt.Errorf("mux: duplicated route variable %q", v2) + } + } + } + return nil +} + +// checkPairs returns the count of strings passed in, and an error if +// the count is not an even number. +func checkPairs(pairs ...string) (int, error) { + length := len(pairs) + if length%2 != 0 { + return length, fmt.Errorf( + "mux: number of parameters must be multiple of 2, got %v", pairs) + } + return length, nil +} + +// mapFromPairsToString converts variadic string parameters to a +// string to string map. +func mapFromPairsToString(pairs ...string) (map[string]string, error) { + length, err := checkPairs(pairs...) + if err != nil { + return nil, err + } + m := make(map[string]string, length/2) + for i := 0; i < length; i += 2 { + m[pairs[i]] = pairs[i+1] + } + return m, nil +} + +// mapFromPairsToRegex converts variadic string parameters to a +// string to regex map. +func mapFromPairsToRegex(pairs ...string) (map[string]*regexp.Regexp, error) { + length, err := checkPairs(pairs...) + if err != nil { + return nil, err + } + m := make(map[string]*regexp.Regexp, length/2) + for i := 0; i < length; i += 2 { + regex, err := regexp.Compile(pairs[i+1]) + if err != nil { + return nil, err + } + m[pairs[i]] = regex + } + return m, nil +} + +// matchInArray returns true if the given string value is in the array. +func matchInArray(arr []string, value string) bool { + for _, v := range arr { + if v == value { + return true + } + } + return false +} + +// matchMapWithString returns true if the given key/value pairs exist in a given map. +func matchMapWithString(toCheck map[string]string, toMatch map[string][]string, canonicalKey bool) bool { + for k, v := range toCheck { + // Check if key exists. + if canonicalKey { + k = http.CanonicalHeaderKey(k) + } + if values := toMatch[k]; values == nil { + return false + } else if v != "" { + // If value was defined as an empty string we only check that the + // key exists. Otherwise we also check for equality. + valueExists := false + for _, value := range values { + if v == value { + valueExists = true + break + } + } + if !valueExists { + return false + } + } + } + return true +} + +// matchMapWithRegex returns true if the given key/value pairs exist in a given map compiled against +// the given regex +func matchMapWithRegex(toCheck map[string]*regexp.Regexp, toMatch map[string][]string, canonicalKey bool) bool { + for k, v := range toCheck { + // Check if key exists. + if canonicalKey { + k = http.CanonicalHeaderKey(k) + } + if values := toMatch[k]; values == nil { + return false + } else if v != nil { + // If value was defined as an empty string we only check that the + // key exists. Otherwise we also check for equality. + valueExists := false + for _, value := range values { + if v.MatchString(value) { + valueExists = true + break + } + } + if !valueExists { + return false + } + } + } + return true +} + +// methodNotAllowed replies to the request with an HTTP status code 405. +func methodNotAllowed(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(http.StatusMethodNotAllowed) +} + +// methodNotAllowedHandler returns a simple request handler +// that replies to each request with a status code 405. +func methodNotAllowedHandler() http.Handler { return http.HandlerFunc(methodNotAllowed) } diff --git a/vendor/github.com/gorilla/mux/regexp.go b/vendor/github.com/gorilla/mux/regexp.go new file mode 100644 index 000000000..0144842bb --- /dev/null +++ b/vendor/github.com/gorilla/mux/regexp.go @@ -0,0 +1,388 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mux + +import ( + "bytes" + "fmt" + "net/http" + "net/url" + "regexp" + "strconv" + "strings" +) + +type routeRegexpOptions struct { + strictSlash bool + useEncodedPath bool +} + +type regexpType int + +const ( + regexpTypePath regexpType = 0 + regexpTypeHost regexpType = 1 + regexpTypePrefix regexpType = 2 + regexpTypeQuery regexpType = 3 +) + +// newRouteRegexp parses a route template and returns a routeRegexp, +// used to match a host, a path or a query string. +// +// It will extract named variables, assemble a regexp to be matched, create +// a "reverse" template to build URLs and compile regexps to validate variable +// values used in URL building. +// +// Previously we accepted only Python-like identifiers for variable +// names ([a-zA-Z_][a-zA-Z0-9_]*), but currently the only restriction is that +// name and pattern can't be empty, and names can't contain a colon. +func newRouteRegexp(tpl string, typ regexpType, options routeRegexpOptions) (*routeRegexp, error) { + // Check if it is well-formed. + idxs, errBraces := braceIndices(tpl) + if errBraces != nil { + return nil, errBraces + } + // Backup the original. + template := tpl + // Now let's parse it. + defaultPattern := "[^/]+" + if typ == regexpTypeQuery { + defaultPattern = ".*" + } else if typ == regexpTypeHost { + defaultPattern = "[^.]+" + } + // Only match strict slash if not matching + if typ != regexpTypePath { + options.strictSlash = false + } + // Set a flag for strictSlash. + endSlash := false + if options.strictSlash && strings.HasSuffix(tpl, "/") { + tpl = tpl[:len(tpl)-1] + endSlash = true + } + varsN := make([]string, len(idxs)/2) + varsR := make([]*regexp.Regexp, len(idxs)/2) + pattern := bytes.NewBufferString("") + pattern.WriteByte('^') + reverse := bytes.NewBufferString("") + var end int + var err error + for i := 0; i < len(idxs); i += 2 { + // Set all values we are interested in. + raw := tpl[end:idxs[i]] + end = idxs[i+1] + parts := strings.SplitN(tpl[idxs[i]+1:end-1], ":", 2) + name := parts[0] + patt := defaultPattern + if len(parts) == 2 { + patt = parts[1] + } + // Name or pattern can't be empty. + if name == "" || patt == "" { + return nil, fmt.Errorf("mux: missing name or pattern in %q", + tpl[idxs[i]:end]) + } + // Build the regexp pattern. + fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(i/2), patt) + + // Build the reverse template. + fmt.Fprintf(reverse, "%s%%s", raw) + + // Append variable name and compiled pattern. + varsN[i/2] = name + varsR[i/2], err = regexp.Compile(fmt.Sprintf("^%s$", patt)) + if err != nil { + return nil, err + } + } + // Add the remaining. + raw := tpl[end:] + pattern.WriteString(regexp.QuoteMeta(raw)) + if options.strictSlash { + pattern.WriteString("[/]?") + } + if typ == regexpTypeQuery { + // Add the default pattern if the query value is empty + if queryVal := strings.SplitN(template, "=", 2)[1]; queryVal == "" { + pattern.WriteString(defaultPattern) + } + } + if typ != regexpTypePrefix { + pattern.WriteByte('$') + } + + var wildcardHostPort bool + if typ == regexpTypeHost { + if !strings.Contains(pattern.String(), ":") { + wildcardHostPort = true + } + } + reverse.WriteString(raw) + if endSlash { + reverse.WriteByte('/') + } + // Compile full regexp. + reg, errCompile := regexp.Compile(pattern.String()) + if errCompile != nil { + return nil, errCompile + } + + // Check for capturing groups which used to work in older versions + if reg.NumSubexp() != len(idxs)/2 { + panic(fmt.Sprintf("route %s contains capture groups in its regexp. ", template) + + "Only non-capturing groups are accepted: e.g. (?:pattern) instead of (pattern)") + } + + // Done! + return &routeRegexp{ + template: template, + regexpType: typ, + options: options, + regexp: reg, + reverse: reverse.String(), + varsN: varsN, + varsR: varsR, + wildcardHostPort: wildcardHostPort, + }, nil +} + +// routeRegexp stores a regexp to match a host or path and information to +// collect and validate route variables. +type routeRegexp struct { + // The unmodified template. + template string + // The type of match + regexpType regexpType + // Options for matching + options routeRegexpOptions + // Expanded regexp. + regexp *regexp.Regexp + // Reverse template. + reverse string + // Variable names. + varsN []string + // Variable regexps (validators). + varsR []*regexp.Regexp + // Wildcard host-port (no strict port match in hostname) + wildcardHostPort bool +} + +// Match matches the regexp against the URL host or path. +func (r *routeRegexp) Match(req *http.Request, match *RouteMatch) bool { + if r.regexpType == regexpTypeHost { + host := getHost(req) + if r.wildcardHostPort { + // Don't be strict on the port match + if i := strings.Index(host, ":"); i != -1 { + host = host[:i] + } + } + return r.regexp.MatchString(host) + } + + if r.regexpType == regexpTypeQuery { + return r.matchQueryString(req) + } + path := req.URL.Path + if r.options.useEncodedPath { + path = req.URL.EscapedPath() + } + return r.regexp.MatchString(path) +} + +// url builds a URL part using the given values. +func (r *routeRegexp) url(values map[string]string) (string, error) { + urlValues := make([]interface{}, len(r.varsN), len(r.varsN)) + for k, v := range r.varsN { + value, ok := values[v] + if !ok { + return "", fmt.Errorf("mux: missing route variable %q", v) + } + if r.regexpType == regexpTypeQuery { + value = url.QueryEscape(value) + } + urlValues[k] = value + } + rv := fmt.Sprintf(r.reverse, urlValues...) + if !r.regexp.MatchString(rv) { + // The URL is checked against the full regexp, instead of checking + // individual variables. This is faster but to provide a good error + // message, we check individual regexps if the URL doesn't match. + for k, v := range r.varsN { + if !r.varsR[k].MatchString(values[v]) { + return "", fmt.Errorf( + "mux: variable %q doesn't match, expected %q", values[v], + r.varsR[k].String()) + } + } + } + return rv, nil +} + +// getURLQuery returns a single query parameter from a request URL. +// For a URL with foo=bar&baz=ding, we return only the relevant key +// value pair for the routeRegexp. +func (r *routeRegexp) getURLQuery(req *http.Request) string { + if r.regexpType != regexpTypeQuery { + return "" + } + templateKey := strings.SplitN(r.template, "=", 2)[0] + val, ok := findFirstQueryKey(req.URL.RawQuery, templateKey) + if ok { + return templateKey + "=" + val + } + return "" +} + +// findFirstQueryKey returns the same result as (*url.URL).Query()[key][0]. +// If key was not found, empty string and false is returned. +func findFirstQueryKey(rawQuery, key string) (value string, ok bool) { + query := []byte(rawQuery) + for len(query) > 0 { + foundKey := query + if i := bytes.IndexAny(foundKey, "&;"); i >= 0 { + foundKey, query = foundKey[:i], foundKey[i+1:] + } else { + query = query[:0] + } + if len(foundKey) == 0 { + continue + } + var value []byte + if i := bytes.IndexByte(foundKey, '='); i >= 0 { + foundKey, value = foundKey[:i], foundKey[i+1:] + } + if len(foundKey) < len(key) { + // Cannot possibly be key. + continue + } + keyString, err := url.QueryUnescape(string(foundKey)) + if err != nil { + continue + } + if keyString != key { + continue + } + valueString, err := url.QueryUnescape(string(value)) + if err != nil { + continue + } + return valueString, true + } + return "", false +} + +func (r *routeRegexp) matchQueryString(req *http.Request) bool { + return r.regexp.MatchString(r.getURLQuery(req)) +} + +// braceIndices returns the first level curly brace indices from a string. +// It returns an error in case of unbalanced braces. +func braceIndices(s string) ([]int, error) { + var level, idx int + var idxs []int + for i := 0; i < len(s); i++ { + switch s[i] { + case '{': + if level++; level == 1 { + idx = i + } + case '}': + if level--; level == 0 { + idxs = append(idxs, idx, i+1) + } else if level < 0 { + return nil, fmt.Errorf("mux: unbalanced braces in %q", s) + } + } + } + if level != 0 { + return nil, fmt.Errorf("mux: unbalanced braces in %q", s) + } + return idxs, nil +} + +// varGroupName builds a capturing group name for the indexed variable. +func varGroupName(idx int) string { + return "v" + strconv.Itoa(idx) +} + +// ---------------------------------------------------------------------------- +// routeRegexpGroup +// ---------------------------------------------------------------------------- + +// routeRegexpGroup groups the route matchers that carry variables. +type routeRegexpGroup struct { + host *routeRegexp + path *routeRegexp + queries []*routeRegexp +} + +// setMatch extracts the variables from the URL once a route matches. +func (v routeRegexpGroup) setMatch(req *http.Request, m *RouteMatch, r *Route) { + // Store host variables. + if v.host != nil { + host := getHost(req) + if v.host.wildcardHostPort { + // Don't be strict on the port match + if i := strings.Index(host, ":"); i != -1 { + host = host[:i] + } + } + matches := v.host.regexp.FindStringSubmatchIndex(host) + if len(matches) > 0 { + extractVars(host, matches, v.host.varsN, m.Vars) + } + } + path := req.URL.Path + if r.useEncodedPath { + path = req.URL.EscapedPath() + } + // Store path variables. + if v.path != nil { + matches := v.path.regexp.FindStringSubmatchIndex(path) + if len(matches) > 0 { + extractVars(path, matches, v.path.varsN, m.Vars) + // Check if we should redirect. + if v.path.options.strictSlash { + p1 := strings.HasSuffix(path, "/") + p2 := strings.HasSuffix(v.path.template, "/") + if p1 != p2 { + u, _ := url.Parse(req.URL.String()) + if p1 { + u.Path = u.Path[:len(u.Path)-1] + } else { + u.Path += "/" + } + m.Handler = http.RedirectHandler(u.String(), http.StatusMovedPermanently) + } + } + } + } + // Store query string variables. + for _, q := range v.queries { + queryURL := q.getURLQuery(req) + matches := q.regexp.FindStringSubmatchIndex(queryURL) + if len(matches) > 0 { + extractVars(queryURL, matches, q.varsN, m.Vars) + } + } +} + +// getHost tries its best to return the request host. +// According to section 14.23 of RFC 2616 the Host header +// can include the port number if the default value of 80 is not used. +func getHost(r *http.Request) string { + if r.URL.IsAbs() { + return r.URL.Host + } + return r.Host +} + +func extractVars(input string, matches []int, names []string, output map[string]string) { + for i, name := range names { + output[name] = input[matches[2*i+2]:matches[2*i+3]] + } +} diff --git a/vendor/github.com/gorilla/mux/route.go b/vendor/github.com/gorilla/mux/route.go new file mode 100644 index 000000000..750afe570 --- /dev/null +++ b/vendor/github.com/gorilla/mux/route.go @@ -0,0 +1,736 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mux + +import ( + "errors" + "fmt" + "net/http" + "net/url" + "regexp" + "strings" +) + +// Route stores information to match a request and build URLs. +type Route struct { + // Request handler for the route. + handler http.Handler + // If true, this route never matches: it is only used to build URLs. + buildOnly bool + // The name used to build URLs. + name string + // Error resulted from building a route. + err error + + // "global" reference to all named routes + namedRoutes map[string]*Route + + // config possibly passed in from `Router` + routeConf +} + +// SkipClean reports whether path cleaning is enabled for this route via +// Router.SkipClean. +func (r *Route) SkipClean() bool { + return r.skipClean +} + +// Match matches the route against the request. +func (r *Route) Match(req *http.Request, match *RouteMatch) bool { + if r.buildOnly || r.err != nil { + return false + } + + var matchErr error + + // Match everything. + for _, m := range r.matchers { + if matched := m.Match(req, match); !matched { + if _, ok := m.(methodMatcher); ok { + matchErr = ErrMethodMismatch + continue + } + + // Ignore ErrNotFound errors. These errors arise from match call + // to Subrouters. + // + // This prevents subsequent matching subrouters from failing to + // run middleware. If not ignored, the middleware would see a + // non-nil MatchErr and be skipped, even when there was a + // matching route. + if match.MatchErr == ErrNotFound { + match.MatchErr = nil + } + + matchErr = nil + return false + } + } + + if matchErr != nil { + match.MatchErr = matchErr + return false + } + + if match.MatchErr == ErrMethodMismatch && r.handler != nil { + // We found a route which matches request method, clear MatchErr + match.MatchErr = nil + // Then override the mis-matched handler + match.Handler = r.handler + } + + // Yay, we have a match. Let's collect some info about it. + if match.Route == nil { + match.Route = r + } + if match.Handler == nil { + match.Handler = r.handler + } + if match.Vars == nil { + match.Vars = make(map[string]string) + } + + // Set variables. + r.regexp.setMatch(req, match, r) + return true +} + +// ---------------------------------------------------------------------------- +// Route attributes +// ---------------------------------------------------------------------------- + +// GetError returns an error resulted from building the route, if any. +func (r *Route) GetError() error { + return r.err +} + +// BuildOnly sets the route to never match: it is only used to build URLs. +func (r *Route) BuildOnly() *Route { + r.buildOnly = true + return r +} + +// Handler -------------------------------------------------------------------- + +// Handler sets a handler for the route. +func (r *Route) Handler(handler http.Handler) *Route { + if r.err == nil { + r.handler = handler + } + return r +} + +// HandlerFunc sets a handler function for the route. +func (r *Route) HandlerFunc(f func(http.ResponseWriter, *http.Request)) *Route { + return r.Handler(http.HandlerFunc(f)) +} + +// GetHandler returns the handler for the route, if any. +func (r *Route) GetHandler() http.Handler { + return r.handler +} + +// Name ----------------------------------------------------------------------- + +// Name sets the name for the route, used to build URLs. +// It is an error to call Name more than once on a route. +func (r *Route) Name(name string) *Route { + if r.name != "" { + r.err = fmt.Errorf("mux: route already has name %q, can't set %q", + r.name, name) + } + if r.err == nil { + r.name = name + r.namedRoutes[name] = r + } + return r +} + +// GetName returns the name for the route, if any. +func (r *Route) GetName() string { + return r.name +} + +// ---------------------------------------------------------------------------- +// Matchers +// ---------------------------------------------------------------------------- + +// matcher types try to match a request. +type matcher interface { + Match(*http.Request, *RouteMatch) bool +} + +// addMatcher adds a matcher to the route. +func (r *Route) addMatcher(m matcher) *Route { + if r.err == nil { + r.matchers = append(r.matchers, m) + } + return r +} + +// addRegexpMatcher adds a host or path matcher and builder to a route. +func (r *Route) addRegexpMatcher(tpl string, typ regexpType) error { + if r.err != nil { + return r.err + } + if typ == regexpTypePath || typ == regexpTypePrefix { + if len(tpl) > 0 && tpl[0] != '/' { + return fmt.Errorf("mux: path must start with a slash, got %q", tpl) + } + if r.regexp.path != nil { + tpl = strings.TrimRight(r.regexp.path.template, "/") + tpl + } + } + rr, err := newRouteRegexp(tpl, typ, routeRegexpOptions{ + strictSlash: r.strictSlash, + useEncodedPath: r.useEncodedPath, + }) + if err != nil { + return err + } + for _, q := range r.regexp.queries { + if err = uniqueVars(rr.varsN, q.varsN); err != nil { + return err + } + } + if typ == regexpTypeHost { + if r.regexp.path != nil { + if err = uniqueVars(rr.varsN, r.regexp.path.varsN); err != nil { + return err + } + } + r.regexp.host = rr + } else { + if r.regexp.host != nil { + if err = uniqueVars(rr.varsN, r.regexp.host.varsN); err != nil { + return err + } + } + if typ == regexpTypeQuery { + r.regexp.queries = append(r.regexp.queries, rr) + } else { + r.regexp.path = rr + } + } + r.addMatcher(rr) + return nil +} + +// Headers -------------------------------------------------------------------- + +// headerMatcher matches the request against header values. +type headerMatcher map[string]string + +func (m headerMatcher) Match(r *http.Request, match *RouteMatch) bool { + return matchMapWithString(m, r.Header, true) +} + +// Headers adds a matcher for request header values. +// It accepts a sequence of key/value pairs to be matched. For example: +// +// r := mux.NewRouter() +// r.Headers("Content-Type", "application/json", +// "X-Requested-With", "XMLHttpRequest") +// +// The above route will only match if both request header values match. +// If the value is an empty string, it will match any value if the key is set. +func (r *Route) Headers(pairs ...string) *Route { + if r.err == nil { + var headers map[string]string + headers, r.err = mapFromPairsToString(pairs...) + return r.addMatcher(headerMatcher(headers)) + } + return r +} + +// headerRegexMatcher matches the request against the route given a regex for the header +type headerRegexMatcher map[string]*regexp.Regexp + +func (m headerRegexMatcher) Match(r *http.Request, match *RouteMatch) bool { + return matchMapWithRegex(m, r.Header, true) +} + +// HeadersRegexp accepts a sequence of key/value pairs, where the value has regex +// support. For example: +// +// r := mux.NewRouter() +// r.HeadersRegexp("Content-Type", "application/(text|json)", +// "X-Requested-With", "XMLHttpRequest") +// +// The above route will only match if both the request header matches both regular expressions. +// If the value is an empty string, it will match any value if the key is set. +// Use the start and end of string anchors (^ and $) to match an exact value. +func (r *Route) HeadersRegexp(pairs ...string) *Route { + if r.err == nil { + var headers map[string]*regexp.Regexp + headers, r.err = mapFromPairsToRegex(pairs...) + return r.addMatcher(headerRegexMatcher(headers)) + } + return r +} + +// Host ----------------------------------------------------------------------- + +// Host adds a matcher for the URL host. +// It accepts a template with zero or more URL variables enclosed by {}. +// Variables can define an optional regexp pattern to be matched: +// +// - {name} matches anything until the next dot. +// +// - {name:pattern} matches the given regexp pattern. +// +// For example: +// +// r := mux.NewRouter() +// r.Host("www.example.com") +// r.Host("{subdomain}.domain.com") +// r.Host("{subdomain:[a-z]+}.domain.com") +// +// Variable names must be unique in a given route. They can be retrieved +// calling mux.Vars(request). +func (r *Route) Host(tpl string) *Route { + r.err = r.addRegexpMatcher(tpl, regexpTypeHost) + return r +} + +// MatcherFunc ---------------------------------------------------------------- + +// MatcherFunc is the function signature used by custom matchers. +type MatcherFunc func(*http.Request, *RouteMatch) bool + +// Match returns the match for a given request. +func (m MatcherFunc) Match(r *http.Request, match *RouteMatch) bool { + return m(r, match) +} + +// MatcherFunc adds a custom function to be used as request matcher. +func (r *Route) MatcherFunc(f MatcherFunc) *Route { + return r.addMatcher(f) +} + +// Methods -------------------------------------------------------------------- + +// methodMatcher matches the request against HTTP methods. +type methodMatcher []string + +func (m methodMatcher) Match(r *http.Request, match *RouteMatch) bool { + return matchInArray(m, r.Method) +} + +// Methods adds a matcher for HTTP methods. +// It accepts a sequence of one or more methods to be matched, e.g.: +// "GET", "POST", "PUT". +func (r *Route) Methods(methods ...string) *Route { + for k, v := range methods { + methods[k] = strings.ToUpper(v) + } + return r.addMatcher(methodMatcher(methods)) +} + +// Path ----------------------------------------------------------------------- + +// Path adds a matcher for the URL path. +// It accepts a template with zero or more URL variables enclosed by {}. The +// template must start with a "/". +// Variables can define an optional regexp pattern to be matched: +// +// - {name} matches anything until the next slash. +// +// - {name:pattern} matches the given regexp pattern. +// +// For example: +// +// r := mux.NewRouter() +// r.Path("/products/").Handler(ProductsHandler) +// r.Path("/products/{key}").Handler(ProductsHandler) +// r.Path("/articles/{category}/{id:[0-9]+}"). +// Handler(ArticleHandler) +// +// Variable names must be unique in a given route. They can be retrieved +// calling mux.Vars(request). +func (r *Route) Path(tpl string) *Route { + r.err = r.addRegexpMatcher(tpl, regexpTypePath) + return r +} + +// PathPrefix ----------------------------------------------------------------- + +// PathPrefix adds a matcher for the URL path prefix. This matches if the given +// template is a prefix of the full URL path. See Route.Path() for details on +// the tpl argument. +// +// Note that it does not treat slashes specially ("/foobar/" will be matched by +// the prefix "/foo") so you may want to use a trailing slash here. +// +// Also note that the setting of Router.StrictSlash() has no effect on routes +// with a PathPrefix matcher. +func (r *Route) PathPrefix(tpl string) *Route { + r.err = r.addRegexpMatcher(tpl, regexpTypePrefix) + return r +} + +// Query ---------------------------------------------------------------------- + +// Queries adds a matcher for URL query values. +// It accepts a sequence of key/value pairs. Values may define variables. +// For example: +// +// r := mux.NewRouter() +// r.Queries("foo", "bar", "id", "{id:[0-9]+}") +// +// The above route will only match if the URL contains the defined queries +// values, e.g.: ?foo=bar&id=42. +// +// If the value is an empty string, it will match any value if the key is set. +// +// Variables can define an optional regexp pattern to be matched: +// +// - {name} matches anything until the next slash. +// +// - {name:pattern} matches the given regexp pattern. +func (r *Route) Queries(pairs ...string) *Route { + length := len(pairs) + if length%2 != 0 { + r.err = fmt.Errorf( + "mux: number of parameters must be multiple of 2, got %v", pairs) + return nil + } + for i := 0; i < length; i += 2 { + if r.err = r.addRegexpMatcher(pairs[i]+"="+pairs[i+1], regexpTypeQuery); r.err != nil { + return r + } + } + + return r +} + +// Schemes -------------------------------------------------------------------- + +// schemeMatcher matches the request against URL schemes. +type schemeMatcher []string + +func (m schemeMatcher) Match(r *http.Request, match *RouteMatch) bool { + scheme := r.URL.Scheme + // https://golang.org/pkg/net/http/#Request + // "For [most] server requests, fields other than Path and RawQuery will be + // empty." + // Since we're an http muxer, the scheme is either going to be http or https + // though, so we can just set it based on the tls termination state. + if scheme == "" { + if r.TLS == nil { + scheme = "http" + } else { + scheme = "https" + } + } + return matchInArray(m, scheme) +} + +// Schemes adds a matcher for URL schemes. +// It accepts a sequence of schemes to be matched, e.g.: "http", "https". +// If the request's URL has a scheme set, it will be matched against. +// Generally, the URL scheme will only be set if a previous handler set it, +// such as the ProxyHeaders handler from gorilla/handlers. +// If unset, the scheme will be determined based on the request's TLS +// termination state. +// The first argument to Schemes will be used when constructing a route URL. +func (r *Route) Schemes(schemes ...string) *Route { + for k, v := range schemes { + schemes[k] = strings.ToLower(v) + } + if len(schemes) > 0 { + r.buildScheme = schemes[0] + } + return r.addMatcher(schemeMatcher(schemes)) +} + +// BuildVarsFunc -------------------------------------------------------------- + +// BuildVarsFunc is the function signature used by custom build variable +// functions (which can modify route variables before a route's URL is built). +type BuildVarsFunc func(map[string]string) map[string]string + +// BuildVarsFunc adds a custom function to be used to modify build variables +// before a route's URL is built. +func (r *Route) BuildVarsFunc(f BuildVarsFunc) *Route { + if r.buildVarsFunc != nil { + // compose the old and new functions + old := r.buildVarsFunc + r.buildVarsFunc = func(m map[string]string) map[string]string { + return f(old(m)) + } + } else { + r.buildVarsFunc = f + } + return r +} + +// Subrouter ------------------------------------------------------------------ + +// Subrouter creates a subrouter for the route. +// +// It will test the inner routes only if the parent route matched. For example: +// +// r := mux.NewRouter() +// s := r.Host("www.example.com").Subrouter() +// s.HandleFunc("/products/", ProductsHandler) +// s.HandleFunc("/products/{key}", ProductHandler) +// s.HandleFunc("/articles/{category}/{id:[0-9]+}"), ArticleHandler) +// +// Here, the routes registered in the subrouter won't be tested if the host +// doesn't match. +func (r *Route) Subrouter() *Router { + // initialize a subrouter with a copy of the parent route's configuration + router := &Router{routeConf: copyRouteConf(r.routeConf), namedRoutes: r.namedRoutes} + r.addMatcher(router) + return router +} + +// ---------------------------------------------------------------------------- +// URL building +// ---------------------------------------------------------------------------- + +// URL builds a URL for the route. +// +// It accepts a sequence of key/value pairs for the route variables. For +// example, given this route: +// +// r := mux.NewRouter() +// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). +// Name("article") +// +// ...a URL for it can be built using: +// +// url, err := r.Get("article").URL("category", "technology", "id", "42") +// +// ...which will return an url.URL with the following path: +// +// "/articles/technology/42" +// +// This also works for host variables: +// +// r := mux.NewRouter() +// r.HandleFunc("/articles/{category}/{id:[0-9]+}", ArticleHandler). +// Host("{subdomain}.domain.com"). +// Name("article") +// +// // url.String() will be "http://news.domain.com/articles/technology/42" +// url, err := r.Get("article").URL("subdomain", "news", +// "category", "technology", +// "id", "42") +// +// The scheme of the resulting url will be the first argument that was passed to Schemes: +// +// // url.String() will be "https://example.com" +// r := mux.NewRouter() +// url, err := r.Host("example.com") +// .Schemes("https", "http").URL() +// +// All variables defined in the route are required, and their values must +// conform to the corresponding patterns. +func (r *Route) URL(pairs ...string) (*url.URL, error) { + if r.err != nil { + return nil, r.err + } + values, err := r.prepareVars(pairs...) + if err != nil { + return nil, err + } + var scheme, host, path string + queries := make([]string, 0, len(r.regexp.queries)) + if r.regexp.host != nil { + if host, err = r.regexp.host.url(values); err != nil { + return nil, err + } + scheme = "http" + if r.buildScheme != "" { + scheme = r.buildScheme + } + } + if r.regexp.path != nil { + if path, err = r.regexp.path.url(values); err != nil { + return nil, err + } + } + for _, q := range r.regexp.queries { + var query string + if query, err = q.url(values); err != nil { + return nil, err + } + queries = append(queries, query) + } + return &url.URL{ + Scheme: scheme, + Host: host, + Path: path, + RawQuery: strings.Join(queries, "&"), + }, nil +} + +// URLHost builds the host part of the URL for a route. See Route.URL(). +// +// The route must have a host defined. +func (r *Route) URLHost(pairs ...string) (*url.URL, error) { + if r.err != nil { + return nil, r.err + } + if r.regexp.host == nil { + return nil, errors.New("mux: route doesn't have a host") + } + values, err := r.prepareVars(pairs...) + if err != nil { + return nil, err + } + host, err := r.regexp.host.url(values) + if err != nil { + return nil, err + } + u := &url.URL{ + Scheme: "http", + Host: host, + } + if r.buildScheme != "" { + u.Scheme = r.buildScheme + } + return u, nil +} + +// URLPath builds the path part of the URL for a route. See Route.URL(). +// +// The route must have a path defined. +func (r *Route) URLPath(pairs ...string) (*url.URL, error) { + if r.err != nil { + return nil, r.err + } + if r.regexp.path == nil { + return nil, errors.New("mux: route doesn't have a path") + } + values, err := r.prepareVars(pairs...) + if err != nil { + return nil, err + } + path, err := r.regexp.path.url(values) + if err != nil { + return nil, err + } + return &url.URL{ + Path: path, + }, nil +} + +// GetPathTemplate returns the template used to build the +// route match. +// This is useful for building simple REST API documentation and for instrumentation +// against third-party services. +// An error will be returned if the route does not define a path. +func (r *Route) GetPathTemplate() (string, error) { + if r.err != nil { + return "", r.err + } + if r.regexp.path == nil { + return "", errors.New("mux: route doesn't have a path") + } + return r.regexp.path.template, nil +} + +// GetPathRegexp returns the expanded regular expression used to match route path. +// This is useful for building simple REST API documentation and for instrumentation +// against third-party services. +// An error will be returned if the route does not define a path. +func (r *Route) GetPathRegexp() (string, error) { + if r.err != nil { + return "", r.err + } + if r.regexp.path == nil { + return "", errors.New("mux: route does not have a path") + } + return r.regexp.path.regexp.String(), nil +} + +// GetQueriesRegexp returns the expanded regular expressions used to match the +// route queries. +// This is useful for building simple REST API documentation and for instrumentation +// against third-party services. +// An error will be returned if the route does not have queries. +func (r *Route) GetQueriesRegexp() ([]string, error) { + if r.err != nil { + return nil, r.err + } + if r.regexp.queries == nil { + return nil, errors.New("mux: route doesn't have queries") + } + queries := make([]string, 0, len(r.regexp.queries)) + for _, query := range r.regexp.queries { + queries = append(queries, query.regexp.String()) + } + return queries, nil +} + +// GetQueriesTemplates returns the templates used to build the +// query matching. +// This is useful for building simple REST API documentation and for instrumentation +// against third-party services. +// An error will be returned if the route does not define queries. +func (r *Route) GetQueriesTemplates() ([]string, error) { + if r.err != nil { + return nil, r.err + } + if r.regexp.queries == nil { + return nil, errors.New("mux: route doesn't have queries") + } + queries := make([]string, 0, len(r.regexp.queries)) + for _, query := range r.regexp.queries { + queries = append(queries, query.template) + } + return queries, nil +} + +// GetMethods returns the methods the route matches against +// This is useful for building simple REST API documentation and for instrumentation +// against third-party services. +// An error will be returned if route does not have methods. +func (r *Route) GetMethods() ([]string, error) { + if r.err != nil { + return nil, r.err + } + for _, m := range r.matchers { + if methods, ok := m.(methodMatcher); ok { + return []string(methods), nil + } + } + return nil, errors.New("mux: route doesn't have methods") +} + +// GetHostTemplate returns the template used to build the +// route match. +// This is useful for building simple REST API documentation and for instrumentation +// against third-party services. +// An error will be returned if the route does not define a host. +func (r *Route) GetHostTemplate() (string, error) { + if r.err != nil { + return "", r.err + } + if r.regexp.host == nil { + return "", errors.New("mux: route doesn't have a host") + } + return r.regexp.host.template, nil +} + +// prepareVars converts the route variable pairs into a map. If the route has a +// BuildVarsFunc, it is invoked. +func (r *Route) prepareVars(pairs ...string) (map[string]string, error) { + m, err := mapFromPairsToString(pairs...) + if err != nil { + return nil, err + } + return r.buildVars(m), nil +} + +func (r *Route) buildVars(m map[string]string) map[string]string { + if r.buildVarsFunc != nil { + m = r.buildVarsFunc(m) + } + return m +} diff --git a/vendor/github.com/gorilla/mux/test_helpers.go b/vendor/github.com/gorilla/mux/test_helpers.go new file mode 100644 index 000000000..5f5c496de --- /dev/null +++ b/vendor/github.com/gorilla/mux/test_helpers.go @@ -0,0 +1,19 @@ +// Copyright 2012 The Gorilla Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package mux + +import "net/http" + +// SetURLVars sets the URL variables for the given request, to be accessed via +// mux.Vars for testing route behaviour. Arguments are not modified, a shallow +// copy is returned. +// +// This API should only be used for testing purposes; it provides a way to +// inject variables into the request context. Alternatively, URL variables +// can be set by making a route that captures the required variables, +// starting a server and sending the request to that server. +func SetURLVars(r *http.Request, val map[string]string) *http.Request { + return requestWithVars(r, val) +} 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