diff --git a/cmd/preview.go b/cmd/preview.go new file mode 100644 index 0000000..2775859 --- /dev/null +++ b/cmd/preview.go @@ -0,0 +1,63 @@ +package cmd + +import ( + "github.com/spf13/cobra" + + "fmt" + "net/url" + "os/exec" + "runtime" + "time" +) + +const previewURL = "http://www.paperboy.email/preview/connect" + +var previewCmd = &cobra.Command{ + Use: "preview", + Short: "Preview campaign in browser", + Long: `A longer description...`, + // Uncomment the following line if your bare application + // has an action associated with it: + RunE: func(cmd *cobra.Command, args []string) error { + if err := loadConfig(); err != nil { + return err + } + + if len(args) != 2 { + return newUserError("Invalid arguments") + } + + go func() { + runtime.Gosched() + time.Sleep(100 * time.Millisecond) + openPreview(args[0], args[1]) + }() + + return startAPIServer() + }, +} + +func openPreview(content, list string) { + q := url.Values{} + q.Set("uri", "http://localhost:8080/graphql") + q.Set("content", content) + q.Set("list", list) + + url := previewURL + "?" + q.Encode() + var err error + + switch runtime.GOOS { + case "darwin": + err = exec.Command("open", url).Start() + case "linux": + err = exec.Command("xdg-open", url).Start() + case "windows": + err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start() + default: + err = fmt.Errorf("Unsupported platform") + } + + if err != nil { + fmt.Printf("\nPlease open the browser to the following URL:\n%s\n\n", url) + } +} diff --git a/cmd/root.go b/cmd/root.go index d86a20b..4ee1403 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -30,6 +30,7 @@ func Execute() { RootCmd.AddCommand(sendCmd) RootCmd.AddCommand(serverCmd) RootCmd.AddCommand(versionCmd) + RootCmd.AddCommand(previewCmd) if err := RootCmd.Execute(); err != nil { fmt.Println(err) diff --git a/cmd/server.go b/cmd/server.go index 1db84ac..82f46e8 100644 --- a/cmd/server.go +++ b/cmd/server.go @@ -16,9 +16,12 @@ var serverCmd = &cobra.Command{ if err := loadConfig(); err != nil { return err } - - fmt.Println("API server listening at :8080 ... ") - http.Handle("/graphql", server.GraphQLHandler()) - return http.ListenAndServe(":8080", nil) + return startAPIServer() }, } + +func startAPIServer() error { + fmt.Println("API server listening at :8080 ... ") + http.Handle("/graphql", server.GraphQLHandler()) + return http.ListenAndServe(":8080", nil) +}