1package commands
2
3import (
4 "context"
5 "fmt"
6 "log"
7 "net"
8 "net/http"
9 "net/url"
10 "os"
11 "os/signal"
12 "strconv"
13 "time"
14
15 "github.com/99designs/gqlgen/graphql/playground"
16 "github.com/gorilla/mux"
17 "github.com/phayes/freeport"
18 "github.com/skratchdot/open-golang/open"
19 "github.com/spf13/cobra"
20
21 "github.com/MichaelMure/git-bug/api/auth"
22 "github.com/MichaelMure/git-bug/api/graphql"
23 httpapi "github.com/MichaelMure/git-bug/api/http"
24 "github.com/MichaelMure/git-bug/cache"
25 "github.com/MichaelMure/git-bug/identity"
26 "github.com/MichaelMure/git-bug/repository"
27 "github.com/MichaelMure/git-bug/webui"
28)
29
30const webUIOpenConfigKey = "git-bug.webui.open"
31
32type webUIOptions struct {
33 host string
34 port int
35 open bool
36 noOpen bool
37 readOnly bool
38 query string
39}
40
41func newWebUICommand() *cobra.Command {
42 env := newEnv()
43 options := webUIOptions{}
44
45 cmd := &cobra.Command{
46 Use: "webui",
47 Short: "Launch the web UI.",
48 Long: `Launch the web UI.
49
50Available git config:
51 git-bug.webui.open [bool]: control the automatic opening of the web UI in the default browser
52`,
53 PreRunE: loadRepo(env),
54 RunE: func(cmd *cobra.Command, args []string) error {
55 return runWebUI(env, options, args)
56 },
57 }
58
59 flags := cmd.Flags()
60 flags.SortFlags = false
61
62 flags.StringVar(&options.host, "host", "127.0.0.1", "Network address or hostname to listen to (default to 127.0.0.1)")
63 flags.BoolVar(&options.open, "open", false, "Automatically open the web UI in the default browser")
64 flags.BoolVar(&options.noOpen, "no-open", false, "Prevent the automatic opening of the web UI in the default browser")
65 flags.IntVarP(&options.port, "port", "p", 0, "Port to listen to (default to random available port)")
66 flags.BoolVar(&options.readOnly, "read-only", false, "Whether to run the web UI in read-only mode")
67 flags.StringVar(&options.query, "query", "", "Set a custom query")
68
69 return cmd
70}
71
72func runWebUI(env *Env, opts webUIOptions, args []string) error {
73 if opts.port == 0 {
74 var err error
75 opts.port, err = freeport.GetFreePort()
76 if err != nil {
77 return err
78 }
79 }
80
81 addr := net.JoinHostPort(opts.host, strconv.Itoa(opts.port))
82 webUiAddr := fmt.Sprintf("http://%s", addr)
83
84 if len(opts.query) > 0 {
85 // Explicitly set the query parameter instead of going with a default one.
86 webUiAddr = fmt.Sprintf("%s/?q=%s", webUiAddr, url.QueryEscape(opts.query))
87 }
88
89 router := mux.NewRouter()
90
91 // If the webUI is not read-only, use an authentication middleware with a
92 // fixed identity: the default user of the repo
93 // TODO: support dynamic authentication with OAuth
94 if !opts.readOnly {
95 author, err := identity.GetUserIdentity(env.repo)
96 if err != nil {
97 return err
98 }
99 router.Use(auth.Middleware(author.Id()))
100 }
101
102 mrc := cache.NewMultiRepoCache()
103 _, err := mrc.RegisterDefaultRepository(env.repo)
104 if err != nil {
105 return err
106 }
107
108 graphqlHandler := graphql.NewHandler(mrc)
109
110 // Routes
111 router.Path("/playground").Handler(playground.Handler("git-bug", "/graphql"))
112 router.Path("/graphql").Handler(graphqlHandler)
113 router.Path("/gitfile/{repo}/{hash}").Handler(httpapi.NewGitFileHandler(mrc))
114 router.Path("/upload/{repo}").Methods("POST").Handler(httpapi.NewGitUploadFileHandler(mrc))
115 router.PathPrefix("/").Handler(webui.NewHandler())
116
117 srv := &http.Server{
118 Addr: addr,
119 Handler: router,
120 }
121
122 done := make(chan bool)
123 quit := make(chan os.Signal, 1)
124
125 // register as handler of the interrupt signal to trigger the teardown
126 signal.Notify(quit, os.Interrupt)
127
128 go func() {
129 <-quit
130 env.out.Println("WebUI is shutting down...")
131
132 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
133 defer cancel()
134
135 srv.SetKeepAlivesEnabled(false)
136 if err := srv.Shutdown(ctx); err != nil {
137 log.Fatalf("Could not gracefully shutdown the WebUI: %v\n", err)
138 }
139
140 // Teardown
141 err := graphqlHandler.Close()
142 if err != nil {
143 env.out.Println(err)
144 }
145
146 close(done)
147 }()
148
149 env.out.Printf("Web UI: %s\n", webUiAddr)
150 env.out.Printf("Graphql API: http://%s/graphql\n", addr)
151 env.out.Printf("Graphql Playground: http://%s/playground\n", addr)
152 env.out.Println("Press Ctrl+c to quit")
153
154 configOpen, err := env.repo.AnyConfig().ReadBool(webUIOpenConfigKey)
155 if err == repository.ErrNoConfigEntry {
156 // default to true
157 configOpen = true
158 } else if err != nil {
159 return err
160 }
161
162 shouldOpen := (configOpen && !opts.noOpen) || opts.open
163
164 if shouldOpen {
165 err = open.Run(webUiAddr)
166 if err != nil {
167 env.out.Println(err)
168 }
169 }
170
171 err = srv.ListenAndServe()
172 if err != nil && err != http.ErrServerClosed {
173 return err
174 }
175
176 <-done
177
178 env.out.Println("WebUI stopped")
179 return nil
180}