1
0
mirror of https://github.com/hybridgroup/gobot.git synced 2025-04-27 13:48:56 +08:00

394 lines
13 KiB
Go
Raw Normal View History

2014-04-29 13:20:32 -07:00
package api
2013-11-23 10:36:08 -08:00
2013-11-23 16:19:11 -08:00
import (
"encoding/json"
"errors"
2014-08-01 21:37:16 -07:00
"fmt"
2014-04-22 20:48:08 -07:00
"log"
2013-11-23 16:19:11 -08:00
"net/http"
2014-10-29 13:18:54 -07:00
"net/http/httptest"
2014-07-01 23:10:12 -07:00
"strings"
2014-07-10 11:35:00 -07:00
"github.com/bmizerany/pat"
"github.com/hybridgroup/gobot"
"github.com/hybridgroup/gobot/api/robeaux"
2013-11-23 16:19:11 -08:00
)
2013-11-23 10:36:08 -08:00
// API represents an API server
type API struct {
2014-04-29 13:20:32 -07:00
gobot *gobot.Gobot
2014-07-23 13:37:05 -07:00
router *pat.PatternServeMux
2014-04-29 13:20:32 -07:00
Host string
Port string
Cert string
Key string
2014-07-21 22:19:04 -07:00
handlers []func(http.ResponseWriter, *http.Request)
start func(*API)
}
// NewAPI returns a new api instance
func NewAPI(g *gobot.Gobot) *API {
return &API{
2014-07-23 13:50:46 -07:00
gobot: g,
router: pat.New(),
Port: "3000",
start: func(a *API) {
2014-07-21 21:14:00 -07:00
log.Println("Initializing API on " + a.Host + ":" + a.Port + "...")
2014-07-23 13:37:05 -07:00
http.Handle("/", a)
2014-07-01 23:10:12 -07:00
2014-04-29 13:20:32 -07:00
go func() {
2014-07-21 21:14:00 -07:00
if a.Cert != "" && a.Key != "" {
http.ListenAndServeTLS(a.Host+":"+a.Port, a.Cert, a.Key, nil)
2014-04-29 13:20:32 -07:00
} else {
2014-07-21 21:14:00 -07:00
log.Println("WARNING: API using insecure connection. " +
"We recommend using an SSL certificate with Gobot.")
http.ListenAndServe(a.Host+":"+a.Port, nil)
2014-04-29 13:20:32 -07:00
}
}()
},
}
2014-04-26 10:13:33 -06:00
}
2014-10-15 12:57:07 -05:00
// ServeHTTP calls api handlers and then serves request using api router
func (a *API) ServeHTTP(res http.ResponseWriter, req *http.Request) {
2014-07-23 13:37:05 -07:00
for _, handler := range a.handlers {
2014-10-29 13:18:54 -07:00
rec := httptest.NewRecorder()
handler(rec, req)
for k, v := range rec.Header() {
res.Header()[k] = v
}
if rec.Code == http.StatusUnauthorized {
http.Error(res, "Not Authorized", http.StatusUnauthorized)
return
}
2014-07-23 13:37:05 -07:00
}
a.router.ServeHTTP(res, req)
}
2014-10-15 12:57:07 -05:00
// Post wraps api router Post call
func (a *API) Post(path string, f func(http.ResponseWriter, *http.Request)) {
2014-07-23 13:37:05 -07:00
a.router.Post(path, http.HandlerFunc(f))
}
2014-10-15 12:57:07 -05:00
// Put wraps api router Put call
func (a *API) Put(path string, f func(http.ResponseWriter, *http.Request)) {
2014-07-23 13:37:05 -07:00
a.router.Put(path, http.HandlerFunc(f))
}
2014-10-15 12:57:07 -05:00
// Delete wraps api router Delete call
func (a *API) Delete(path string, f func(http.ResponseWriter, *http.Request)) {
2014-07-23 13:37:05 -07:00
a.router.Del(path, http.HandlerFunc(f))
}
2014-10-15 12:57:07 -05:00
// Options wraps api router Options call
func (a *API) Options(path string, f func(http.ResponseWriter, *http.Request)) {
2014-07-23 13:37:05 -07:00
a.router.Options(path, http.HandlerFunc(f))
}
2014-10-15 12:57:07 -05:00
// Get wraps api router Get call
func (a *API) Get(path string, f func(http.ResponseWriter, *http.Request)) {
2014-07-23 13:37:05 -07:00
a.router.Get(path, http.HandlerFunc(f))
}
2014-10-15 12:57:07 -05:00
// Head wraps api router Head call
func (a *API) Head(path string, f func(http.ResponseWriter, *http.Request)) {
2014-07-23 13:37:05 -07:00
a.router.Head(path, http.HandlerFunc(f))
}
2014-10-15 12:57:07 -05:00
// AddHandler appends handler to api handlers
func (a *API) AddHandler(f func(http.ResponseWriter, *http.Request)) {
2014-07-21 22:19:04 -07:00
a.handlers = append(a.handlers, f)
}
2014-10-15 12:57:07 -05:00
// Start initializes the api by setting up c3pio routes and robeaux
func (a *API) Start() {
2014-07-24 16:39:27 -07:00
mcpCommandRoute := "/api/commands/:command"
2015-03-16 09:53:05 -06:00
robotDeviceCommandRoute := "/api/robots/:robot/devices/:device/commands/:command"
2014-07-24 16:39:27 -07:00
robotCommandRoute := "/api/robots/:robot/commands/:command"
a.Get("/api/commands", a.mcpCommands)
2014-07-23 13:37:05 -07:00
a.Get(mcpCommandRoute, a.executeMcpCommand)
a.Post(mcpCommandRoute, a.executeMcpCommand)
2014-07-24 16:39:27 -07:00
a.Get("/api/robots", a.robots)
a.Get("/api/robots/:robot", a.robot)
a.Get("/api/robots/:robot/commands", a.robotCommands)
2014-07-23 13:37:05 -07:00
a.Get(robotCommandRoute, a.executeRobotCommand)
a.Post(robotCommandRoute, a.executeRobotCommand)
2014-07-24 16:39:27 -07:00
a.Get("/api/robots/:robot/devices", a.robotDevices)
a.Get("/api/robots/:robot/devices/:device", a.robotDevice)
2014-08-01 21:37:16 -07:00
a.Get("/api/robots/:robot/devices/:device/events/:event", a.robotDeviceEvent)
2014-07-24 16:39:27 -07:00
a.Get("/api/robots/:robot/devices/:device/commands", a.robotDeviceCommands)
2015-03-16 09:53:05 -06:00
a.Get(robotDeviceCommandRoute, a.executeRobotDeviceCommand)
a.Post(robotDeviceCommandRoute, a.executeRobotDeviceCommand)
2014-07-24 16:39:27 -07:00
a.Get("/api/robots/:robot/connections", a.robotConnections)
a.Get("/api/robots/:robot/connections/:connection", a.robotConnection)
a.Get("/api/", a.mcp)
a.Get("/", func(res http.ResponseWriter, req *http.Request) {
http.Redirect(res, req, "/index.html", http.StatusMovedPermanently)
})
2014-07-23 13:37:05 -07:00
a.Get("/index.html", a.robeaux)
a.Get("/images/:a", a.robeaux)
a.Get("/js/:a", a.robeaux)
a.Get("/js/:a/", a.robeaux)
a.Get("/js/:a/:b", a.robeaux)
a.Get("/css/:a", a.robeaux)
a.Get("/css/:a/", a.robeaux)
a.Get("/css/:a/:b", a.robeaux)
a.Get("/partials/:a", a.robeaux)
2013-11-23 16:19:11 -08:00
a.start(a)
}
2014-04-18 22:44:50 -07:00
2014-10-15 12:57:07 -05:00
// robeaux returns handler for robeaux routes.
// Writes asset in response and sets correct header
func (a *API) robeaux(res http.ResponseWriter, req *http.Request) {
2014-07-01 23:10:12 -07:00
path := req.URL.Path
2014-07-10 11:35:00 -07:00
buf, err := robeaux.Asset(path[1:])
2014-07-01 23:10:12 -07:00
if err != nil {
2014-07-21 21:14:00 -07:00
http.Error(res, err.Error(), http.StatusNotFound)
2014-07-01 23:10:12 -07:00
return
}
t := strings.Split(path, ".")
if t[len(t)-1] == "js" {
res.Header().Set("Content-Type", "text/javascript; charset=utf-8")
} else if t[len(t)-1] == "css" {
res.Header().Set("Content-Type", "text/css; charset=utf-8")
} else if t[len(t)-1] == "html" {
res.Header().Set("Content-Type", "text/html; charset=utf-8")
2014-07-01 23:10:12 -07:00
}
res.Write(buf)
}
2014-10-15 12:57:07 -05:00
// mcp returns MCP route handler.
// Writes JSON with gobot representation
func (a *API) mcp(res http.ResponseWriter, req *http.Request) {
a.writeJSON(map[string]interface{}{"MCP": gobot.NewJSONGobot(a.gobot)}, res)
2014-06-12 20:58:54 -07:00
}
2014-10-15 12:57:07 -05:00
// mcpCommands returns commands route handler.
// Writes JSON with global commands representation
func (a *API) mcpCommands(res http.ResponseWriter, req *http.Request) {
a.writeJSON(map[string]interface{}{"commands": gobot.NewJSONGobot(a.gobot).Commands}, res)
2014-06-12 20:58:54 -07:00
}
2014-10-15 12:57:07 -05:00
// robots returns route handler.
// Writes JSON with robots representation
func (a *API) robots(res http.ResponseWriter, req *http.Request) {
2014-06-10 15:16:11 -07:00
jsonRobots := []*gobot.JSONRobot{}
2014-07-02 18:08:44 -07:00
a.gobot.Robots().Each(func(r *gobot.Robot) {
jsonRobots = append(jsonRobots, gobot.NewJSONRobot(r))
2014-07-02 18:08:44 -07:00
})
2014-07-24 16:39:27 -07:00
a.writeJSON(map[string]interface{}{"robots": jsonRobots}, res)
2014-04-15 17:59:44 -07:00
}
2014-10-15 12:57:07 -05:00
// robot returns route handler.
// Writes JSON with robot representation
func (a *API) robot(res http.ResponseWriter, req *http.Request) {
if robot, err := a.jsonRobotFor(req.URL.Query().Get(":robot")); err != nil {
a.writeJSON(map[string]interface{}{"error": err.Error()}, res)
} else {
a.writeJSON(map[string]interface{}{"robot": robot}, res)
}
2014-04-15 17:59:44 -07:00
}
2014-10-15 12:57:07 -05:00
// robotCommands returns commands route handler
// Writes JSON with robot commands representation
func (a *API) robotCommands(res http.ResponseWriter, req *http.Request) {
if robot, err := a.jsonRobotFor(req.URL.Query().Get(":robot")); err != nil {
a.writeJSON(map[string]interface{}{"error": err.Error()}, res)
} else {
a.writeJSON(map[string]interface{}{"commands": robot.Commands}, res)
}
2014-04-15 17:59:44 -07:00
}
2014-10-15 12:57:07 -05:00
// robotDevices returns devices route handler.
// Writes JSON with robot devices representation
func (a *API) robotDevices(res http.ResponseWriter, req *http.Request) {
if robot := a.gobot.Robot(req.URL.Query().Get(":robot")); robot != nil {
jsonDevices := []*gobot.JSONDevice{}
robot.Devices().Each(func(d gobot.Device) {
jsonDevices = append(jsonDevices, gobot.NewJSONDevice(d))
})
a.writeJSON(map[string]interface{}{"devices": jsonDevices}, res)
} else {
a.writeJSON(map[string]interface{}{"error": "No Robot found with the name " + req.URL.Query().Get(":robot")}, res)
}
2014-04-15 17:59:44 -07:00
}
2014-10-15 12:57:07 -05:00
// robotDevice returns device route handler.
// Writes JSON with robot device representation
func (a *API) robotDevice(res http.ResponseWriter, req *http.Request) {
if device, err := a.jsonDeviceFor(req.URL.Query().Get(":robot"), req.URL.Query().Get(":device")); err != nil {
a.writeJSON(map[string]interface{}{"error": err.Error()}, res)
} else {
a.writeJSON(map[string]interface{}{"device": device}, res)
}
2014-04-15 17:59:44 -07:00
}
func (a *API) robotDeviceEvent(res http.ResponseWriter, req *http.Request) {
2014-08-01 21:37:16 -07:00
f, _ := res.(http.Flusher)
c, _ := res.(http.CloseNotifier)
dataChan := make(chan string)
2014-08-01 21:37:16 -07:00
closer := c.CloseNotify()
res.Header().Set("Content-Type", "text/event-stream")
res.Header().Set("Cache-Control", "no-cache")
res.Header().Set("Connection", "keep-alive")
if event := a.gobot.Robot(req.URL.Query().Get(":robot")).
Device(req.URL.Query().Get(":device")).(gobot.Eventer).
Event(req.URL.Query().Get(":event")); event != nil {
gobot.On(event, func(data interface{}) {
2014-08-01 21:37:16 -07:00
d, _ := json.Marshal(data)
dataChan <- string(d)
2014-08-01 21:37:16 -07:00
})
for {
select {
case data := <-dataChan:
fmt.Fprintf(res, "data: %v\n\n", data)
f.Flush()
case <-closer:
log.Println("Closing connection")
return
}
2014-08-01 21:37:16 -07:00
}
} else {
a.writeJSON(map[string]interface{}{
"error": "No Event found with the name " + req.URL.Query().Get(":event"),
}, res)
2014-08-01 21:37:16 -07:00
}
}
2014-10-15 12:57:07 -05:00
// robotDeviceCommands returns device commands route handler
// writes JSON with robot device commands representation
func (a *API) robotDeviceCommands(res http.ResponseWriter, req *http.Request) {
if device, err := a.jsonDeviceFor(req.URL.Query().Get(":robot"), req.URL.Query().Get(":device")); err != nil {
a.writeJSON(map[string]interface{}{"error": err.Error()}, res)
} else {
a.writeJSON(map[string]interface{}{"commands": device.Commands}, res)
}
2013-11-23 10:36:08 -08:00
}
2013-11-24 15:47:48 -08:00
2014-10-15 12:57:07 -05:00
// robotConnections returns connections route handler
// writes JSON with robot connections representation
func (a *API) robotConnections(res http.ResponseWriter, req *http.Request) {
2014-06-10 15:16:11 -07:00
jsonConnections := []*gobot.JSONConnection{}
if robot := a.gobot.Robot(req.URL.Query().Get(":robot")); robot != nil {
robot.Connections().Each(func(c gobot.Connection) {
jsonConnections = append(jsonConnections, gobot.NewJSONConnection(c))
})
a.writeJSON(map[string]interface{}{"connections": jsonConnections}, res)
} else {
a.writeJSON(map[string]interface{}{"error": "No Robot found with the name " + req.URL.Query().Get(":robot")}, res)
}
2014-04-18 22:44:50 -07:00
}
2014-10-15 12:57:07 -05:00
// robotConnection returns connection route handler
// writes JSON with robot connection representation
func (a *API) robotConnection(res http.ResponseWriter, req *http.Request) {
if conn, err := a.jsonConnectionFor(req.URL.Query().Get(":robot"), req.URL.Query().Get(":connection")); err != nil {
a.writeJSON(map[string]interface{}{"error": err.Error()}, res)
} else {
a.writeJSON(map[string]interface{}{"connection": conn}, res)
}
2014-04-18 22:44:50 -07:00
}
2014-10-15 12:57:07 -05:00
// executeMcpCommand calls a global command asociated to requested route
func (a *API) executeMcpCommand(res http.ResponseWriter, req *http.Request) {
2014-07-23 11:24:41 -07:00
a.executeCommand(a.gobot.Command(req.URL.Query().Get(":command")),
res,
req,
)
2014-06-12 20:58:54 -07:00
}
2015-03-16 09:53:05 -06:00
// executeRobotDeviceCommand calls a device command asociated to requested route
func (a *API) executeRobotDeviceCommand(res http.ResponseWriter, req *http.Request) {
if _, err := a.jsonDeviceFor(req.URL.Query().Get(":robot"),
req.URL.Query().Get(":device")); err != nil {
a.writeJSON(map[string]interface{}{"error": err.Error()}, res)
} else {
a.executeCommand(
a.gobot.Robot(req.URL.Query().Get(":robot")).
Device(req.URL.Query().Get(":device")).(gobot.Commander).
Command(req.URL.Query().Get(":command")),
res,
req,
)
}
2013-11-24 15:47:48 -08:00
}
2013-11-27 20:05:45 -08:00
2014-10-15 12:57:07 -05:00
// executeRobotCommand calls a robot command asociated to requested route
func (a *API) executeRobotCommand(res http.ResponseWriter, req *http.Request) {
if _, err := a.jsonRobotFor(req.URL.Query().Get(":robot")); err != nil {
a.writeJSON(map[string]interface{}{"error": err.Error()}, res)
} else {
a.executeCommand(
a.gobot.Robot(req.URL.Query().Get(":robot")).
Command(req.URL.Query().Get(":command")),
res,
req,
)
}
2014-07-23 11:24:41 -07:00
}
2014-07-21 21:14:00 -07:00
2014-10-15 12:57:07 -05:00
// executeCommand writes JSON response with `f` returned value.
func (a *API) executeCommand(f func(map[string]interface{}) interface{},
2014-07-23 11:24:41 -07:00
res http.ResponseWriter,
req *http.Request,
) {
2014-07-21 22:19:04 -07:00
body := make(map[string]interface{})
2014-07-21 21:14:00 -07:00
json.NewDecoder(req.Body).Decode(&body)
2014-06-11 16:44:23 -07:00
if f != nil {
2014-07-24 16:39:27 -07:00
a.writeJSON(map[string]interface{}{"result": f(body)}, res)
2014-04-15 19:19:14 -07:00
} else {
a.writeJSON(map[string]interface{}{"error": "Unknown Command"}, res)
2013-11-27 20:05:45 -08:00
}
2014-07-21 21:14:00 -07:00
}
2014-07-23 11:24:41 -07:00
2014-10-15 12:57:07 -05:00
// writeJSON writes `j` as JSON in response
func (a *API) writeJSON(j interface{}, res http.ResponseWriter) {
2014-07-23 11:24:41 -07:00
data, _ := json.Marshal(j)
res.Header().Set("Content-Type", "application/json; charset=utf-8")
res.Write(data)
}
2014-10-15 12:57:07 -05:00
// Debug add handler to api that prints each request
func (a *API) Debug() {
a.AddHandler(func(res http.ResponseWriter, req *http.Request) {
log.Println(req)
})
}
func (a *API) jsonRobotFor(name string) (jrobot *gobot.JSONRobot, err error) {
if robot := a.gobot.Robot(name); robot != nil {
jrobot = gobot.NewJSONRobot(robot)
} else {
err = errors.New("No Robot found with the name " + name)
}
return
}
func (a *API) jsonDeviceFor(robot string, name string) (jdevice *gobot.JSONDevice, err error) {
if device := a.gobot.Robot(robot).Device(name); device != nil {
jdevice = gobot.NewJSONDevice(device)
} else {
err = errors.New("No Device found with the name " + name)
}
return
}
func (a *API) jsonConnectionFor(robot string, name string) (jconnection *gobot.JSONConnection, err error) {
if connection := a.gobot.Robot(robot).Connection(name); connection != nil {
jconnection = gobot.NewJSONConnection(connection)
} else {
err = errors.New("No Connection found with the name " + name)
}
return
}