1package commands
2
3import (
4 "bytes"
5 "context"
6 "encoding/json"
7 "fmt"
8 "io/ioutil"
9 "log"
10 "net/http"
11 "os"
12 "os/signal"
13 "time"
14
15 "github.com/MichaelMure/git-bug/graphql"
16 "github.com/MichaelMure/git-bug/repository"
17 "github.com/MichaelMure/git-bug/util/git"
18 "github.com/MichaelMure/git-bug/webui"
19 "github.com/gorilla/mux"
20 "github.com/phayes/freeport"
21 "github.com/skratchdot/open-golang/open"
22 "github.com/spf13/cobra"
23 "github.com/vektah/gqlgen/handler"
24)
25
26var port int
27
28func runWebUI(cmd *cobra.Command, args []string) error {
29 if port == 0 {
30 var err error
31 port, err = freeport.GetFreePort()
32 if err != nil {
33 return err
34 }
35 }
36
37 addr := fmt.Sprintf("127.0.0.1:%d", port)
38 webUiAddr := fmt.Sprintf("http://%s", addr)
39
40 router := mux.NewRouter()
41
42 graphqlHandler, err := graphql.NewHandler(repo)
43 if err != nil {
44 return err
45 }
46
47 // Routes
48 router.Path("/playground").Handler(handler.Playground("git-bug", "/graphql"))
49 router.Path("/graphql").Handler(graphqlHandler)
50 router.Path("/gitfile/{hash}").Handler(newGitFileHandler(repo))
51 router.Path("/upload").Methods("POST").Handler(newGitUploadFileHandler(repo))
52 router.PathPrefix("/").Handler(http.FileServer(webui.WebUIAssets))
53
54 srv := &http.Server{
55 Addr: addr,
56 Handler: router,
57 }
58
59 done := make(chan bool)
60 quit := make(chan os.Signal, 1)
61
62 // register as handler of the interrupt signal to trigger the teardown
63 signal.Notify(quit, os.Interrupt)
64
65 go func() {
66 <-quit
67 fmt.Println("WebUI is shutting down...")
68
69 ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
70 defer cancel()
71
72 srv.SetKeepAlivesEnabled(false)
73 if err := srv.Shutdown(ctx); err != nil {
74 log.Fatalf("Could not gracefully shutdown the WebUI: %v\n", err)
75 }
76
77 // Teardown
78 err := graphqlHandler.Close()
79 if err != nil {
80 fmt.Println(err)
81 }
82
83 close(done)
84 }()
85
86 fmt.Printf("Web UI: %s\n", webUiAddr)
87 fmt.Printf("Graphql API: http://%s/graphql\n", addr)
88 fmt.Printf("Graphql Playground: http://%s/playground\n", addr)
89
90 err = open.Run(webUiAddr)
91 if err != nil {
92 fmt.Println(err)
93 }
94
95 err = srv.ListenAndServe()
96 if err != nil && err != http.ErrServerClosed {
97 return err
98 }
99
100 <-done
101
102 fmt.Println("WebUI stopped")
103 return nil
104}
105
106type gitFileHandler struct {
107 repo repository.Repo
108}
109
110func newGitFileHandler(repo repository.Repo) http.Handler {
111 return &gitFileHandler{
112 repo: repo,
113 }
114}
115
116func (gfh *gitFileHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
117 hash := git.Hash(mux.Vars(r)["hash"])
118
119 if !hash.IsValid() {
120 http.Error(rw, "invalid git hash", http.StatusBadRequest)
121 return
122 }
123
124 // TODO: this mean that the whole file will he buffered in memory
125 // This can be a problem for big files. There might be a way around
126 // that by implementing a io.ReadSeeker that would read and discard
127 // data when a seek is called.
128 data, err := gfh.repo.ReadData(git.Hash(hash))
129 if err != nil {
130 http.Error(rw, err.Error(), http.StatusInternalServerError)
131 return
132 }
133
134 http.ServeContent(rw, r, "", time.Now(), bytes.NewReader(data))
135}
136
137type gitUploadFileHandler struct {
138 repo repository.Repo
139}
140
141func newGitUploadFileHandler(repo repository.Repo) http.Handler {
142 return &gitUploadFileHandler{
143 repo: repo,
144 }
145}
146
147func (gufh *gitUploadFileHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
148 // 100MB (github limit)
149 var maxUploadSize int64 = 100 * 1000 * 1000
150 r.Body = http.MaxBytesReader(rw, r.Body, maxUploadSize)
151 if err := r.ParseMultipartForm(maxUploadSize); err != nil {
152 http.Error(rw, "file too big (100MB max)", http.StatusBadRequest)
153 return
154 }
155
156 file, _, err := r.FormFile("uploadfile")
157 if err != nil {
158 http.Error(rw, "invalid file", http.StatusBadRequest)
159 return
160 }
161 defer file.Close()
162 fileBytes, err := ioutil.ReadAll(file)
163 if err != nil {
164 http.Error(rw, "invalid file", http.StatusBadRequest)
165 return
166 }
167
168 filetype := http.DetectContentType(fileBytes)
169 if filetype != "image/jpeg" && filetype != "image/jpg" &&
170 filetype != "image/gif" && filetype != "image/png" {
171 http.Error(rw, "invalid file type", http.StatusBadRequest)
172 return
173 }
174
175 hash, err := gufh.repo.StoreData(fileBytes)
176 if err != nil {
177 http.Error(rw, err.Error(), http.StatusInternalServerError)
178 return
179 }
180
181 type response struct {
182 Hash string `json:"hash"`
183 }
184
185 resp := response{Hash: string(hash)}
186
187 js, err := json.Marshal(resp)
188 if err != nil {
189 http.Error(rw, err.Error(), http.StatusInternalServerError)
190 return
191 }
192
193 rw.Header().Set("Content-Type", "application/json")
194 _, err = rw.Write(js)
195 if err != nil {
196 http.Error(rw, err.Error(), http.StatusInternalServerError)
197 return
198 }
199}
200
201var webUICmd = &cobra.Command{
202 Use: "webui",
203 Short: "Launch the web UI",
204 RunE: runWebUI,
205}
206
207func init() {
208 RootCmd.AddCommand(webUICmd)
209
210 webUICmd.Flags().SortFlags = false
211
212 webUICmd.Flags().IntVarP(&port, "port", "p", 0, "Port to listen to")
213}