|
| 1 | +package webserver |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "github.com/bartekpacia/fhome/api" |
| 7 | + "net/http" |
| 8 | + "strconv" |
| 9 | +) |
| 10 | + |
| 11 | +type Api struct { |
| 12 | + fhomeClient *api.Client |
| 13 | +} |
| 14 | + |
| 15 | +func NewApi(fhomeClient *api.Client) *Api { |
| 16 | + return &Api{ |
| 17 | + fhomeClient: fhomeClient, |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +func (a *Api) Mux() http.Handler { |
| 22 | + mux := http.NewServeMux() |
| 23 | + |
| 24 | + mux.HandleFunc("GET /devices", a.getDevices) |
| 25 | + mux.HandleFunc("POST /devices/{id}", a.toggleDevice) |
| 26 | + |
| 27 | + authMux := withPassphrase(mux, "my-passphrase") |
| 28 | + return authMux |
| 29 | +} |
| 30 | + |
| 31 | +func (a *Api) getDevices(w http.ResponseWriter, r *http.Request) { |
| 32 | + userConfig, err := a.fhomeClient.GetUserConfig(r.Context()) |
| 33 | + if err != nil { |
| 34 | + http.Error(w, "failed to get user config"+err.Error(), http.StatusInternalServerError) |
| 35 | + return |
| 36 | + } |
| 37 | + |
| 38 | + response := make([]device, 0) |
| 39 | + |
| 40 | + for _, cell := range userConfig.Cells { |
| 41 | + response = append(response, device{ |
| 42 | + Name: cell.Name, |
| 43 | + ID: cell.ObjectID, |
| 44 | + }) |
| 45 | + } |
| 46 | + |
| 47 | + w.Header().Set("Content-Type", "application/json") |
| 48 | + err = json.NewEncoder(w).Encode(response) |
| 49 | + if err != nil { |
| 50 | + http.Error(w, "failed to encode user into json"+err.Error(), http.StatusInternalServerError) |
| 51 | + return |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +func (a *Api) toggleDevice(w http.ResponseWriter, r *http.Request) { |
| 56 | + objectID, err := strconv.ParseInt(r.PathValue("id"), 10, 64) |
| 57 | + if err != nil { |
| 58 | + http.Error(w, err.Error(), http.StatusBadRequest) |
| 59 | + return |
| 60 | + } |
| 61 | + |
| 62 | + err = a.fhomeClient.SendEvent(r.Context(), int(objectID), api.ValueToggle) |
| 63 | + if err != nil { |
| 64 | + msg := fmt.Sprintf("failed to send event to object with %d: %v\n", objectID, err) |
| 65 | + http.Error(w, msg, http.StatusInternalServerError) |
| 66 | + return |
| 67 | + } |
| 68 | +} |
| 69 | + |
| 70 | +func withPassphrase(next http.Handler, passphrase string) http.Handler { |
| 71 | + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 72 | + if r.Header.Get("Authorization") != "Passphrase: "+passphrase { |
| 73 | + http.Error(w, "Unauthorized", http.StatusUnauthorized) |
| 74 | + return |
| 75 | + } |
| 76 | + |
| 77 | + next.ServeHTTP(w, r) |
| 78 | + }) |
| 79 | +} |
| 80 | + |
| 81 | +type device struct { |
| 82 | + Name string |
| 83 | + ID int |
| 84 | +} |
0 commit comments