Initial API setup: GET and POST handlers and base permission checks.

This commit is contained in:
Jesse Malotaux 2025-03-23 15:30:08 +01:00
parent 535cf06237
commit 8b8a84aa67
15 changed files with 538 additions and 18 deletions

67
be/app/api.go Normal file
View file

@ -0,0 +1,67 @@
package app
import (
"be/app/helper"
"log"
"mime"
"net/http"
"path/filepath"
"strings"
)
func ApiCORS(w http.ResponseWriter, r *http.Request) (http.ResponseWriter, *http.Request) {
origin := r.Header.Get("Origin")
w.Header().Set("Access-Control-Allow-Origin", "http://localhost:5173")
if strings.HasPrefix(r.Host, "192.168.") {
log.Println("lan device")
w.Header().Set("Access-Control-Allow-Origin", origin)
}
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Accept, Accept-Language, Accept-Encoding")
return w, r
}
func ApiGet(w http.ResponseWriter, r *http.Request) {
file := "" // base directory
if r.URL.Path != "/" {
file = "../public" + r.URL.Path // request
}
contentType := mime.TypeByExtension(filepath.Ext(file)) // get content type
if contentType != "" {
w.Header().Set("Content-Type", contentType) // set content type header
}
if contentType == "" {
file = "../public/index.html" // default
}
// log.Println("GET:", file)
http.ServeFile(w, r, file) // serve file
}
func ApiPost(w http.ResponseWriter, r *http.Request) {
if !helper.EndpointAccess(w, r) {
return
}
switch r.URL.Path {
case "/macro/record":
SaveMacro(w, r)
case "/macro/list":
ListMacros(w, r)
case "/macro/delete":
DeleteMacro(w, r)
case "/macro/play":
PlayMacro(w, r)
case "/device/list":
DeviceList(w, r)
}
}

69
be/app/device.go Normal file
View file

@ -0,0 +1,69 @@
package app
import (
"be/app/structs"
"encoding/json"
"log"
"net/http"
"os"
"path/filepath"
"strings"
)
func DeviceList(w http.ResponseWriter, r *http.Request) {
log.Println("device list")
dir := "devices"
files, err := os.ReadDir(dir)
if err != nil {
log.Fatal(err)
}
devices := make(map[string]map[string]interface{})
for _, file := range files {
filePath := dir + "/" + file.Name()
ext := filepath.Ext(filePath)
device := strings.TrimSuffix(file.Name(), ext)
log.Println(device, ext)
if _, ok := devices[device]; !ok {
devices[device] = make(map[string]interface{})
}
if ext == ".json" {
devices[device]["settings"] = readDeviceSettings(filePath)
}
if ext == ".pem" {
devices[device]["key"] = true
}
}
result := map[string]interface{}{
"devices": devices,
}
json.NewEncoder(w).Encode(result)
}
func readDeviceSettings(filepath string) (settings structs.Settings) {
data, err := os.ReadFile(filepath)
if err != nil {
log.Println(err)
}
err = json.Unmarshal(data, &settings)
if err != nil {
log.Println(err)
}
log.Println(settings)
return settings
}
func DeviceAccess(w http.ResponseWriter, r *http.Request) bool {
return true
}
func DeviceAuth(w http.ResponseWriter, r *http.Request) bool {
return true
}

View file

@ -0,0 +1,74 @@
package helper
import (
"log"
"net"
"net/http"
"strings"
. "be/app/structs"
)
func EndpointAccess(w http.ResponseWriter, r *http.Request) bool {
log.Println("endpoint access")
ip, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
log.Fatal(err)
}
if (isLocal(ip) && isEndpointAllowed("Local", r.URL.Path)) ||
(isLanRemote(ip) && isEndpointAllowed("Remote", r.URL.Path)) {
log.Println("accessible")
return true
} else if isLanRemote(ip) && isEndpointAllowed("auth", r.URL.Path) && isDeviceAuthorized() {
log.Println("authorized")
}
log.Println(r.URL.Path, "not authorized or accessible")
return false
}
func isLocal(ip string) bool {
return ip == "127.0.0.1" || ip == "::1"
}
func isLanRemote(ip string) bool {
return strings.HasPrefix(ip, "192.168.")
}
func isEndpointAllowed(source string, endpoint string) bool {
var endpoints, err = getAllowedEndpoints(source)
if err != "" {
log.Println(err)
}
if (endpoints != nil) && (len(endpoints) > 0) {
for _, e := range endpoints {
if e == endpoint {
return true
}
}
}
return false
}
func getAllowedEndpoints(source string) (endpoints []string, err string) {
if source == "Local" {
return Endpoints.Local, ""
}
if source == "Remote" {
return Endpoints.Remote, ""
}
if source == "Auth" {
return Endpoints.Auth, ""
}
return []string{}, "No allowed endpoints"
}
func isDeviceAuthorized() bool {
return false
}

View file

@ -0,0 +1,23 @@
package helper
import (
"os/exec"
"runtime"
)
func OpenBrowser(url string) bool {
var args []string
switch runtime.GOOS {
case "darwin":
args = []string{"open"}
case "windows":
args = []string{"cmd", "/c", "start"}
default:
args = []string{"xdg-open"}
}
cmd := exec.Command(args[0], append(args[1:], url)...)
return cmd.Start() == nil
}

View file

@ -0,0 +1,64 @@
package helper
import (
"encoding/json"
"log"
"os"
"regexp"
"strings"
"time"
"be/app/structs"
"github.com/go-vgo/robotgo"
)
func FormatMacroFileName(s string) string {
// Remove invalid characters
re := regexp.MustCompile(`[\/\?\*\>\<\:\\"\|\n]`)
s = re.ReplaceAllString(s, "")
// Replace spaces with underscores
s = strings.ReplaceAll(s, " ", "_")
// Remove special characters
re = regexp.MustCompile(`[!@#$%^&\(\)\[\]\{\}\~]`)
s = re.ReplaceAllString(s, "")
// Truncate the string
if len(s) > 255 {
s = s[:255]
}
return s
}
func ReadMacroFile(filename string) (steps []structs.Step, err error) {
log.Println(filename)
content, err := os.ReadFile(filename)
if err != nil {
log.Fatal("Error when opening file: ", err)
}
err = json.Unmarshal(content, &steps)
return steps, err
}
func RunMacroSteps(steps []structs.Step) {
for _, step := range steps {
// log.Println(step)
switch step.Type {
case "key":
robotgo.KeyToggle(step.Key, step.Direction)
// log.Println("Toggling", step.Key, "to", step.Direction)
case "delay":
time.Sleep(time.Duration(step.Location) * time.Millisecond)
// log.Println("Sleeping for", step.Value, "milliseconds")
default:
log.Println("Unknown step type:", step.Type)
}
}
}

88
be/app/macro.go Normal file
View file

@ -0,0 +1,88 @@
package app
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"be/app/helper"
"be/app/structs"
)
func SaveMacro(w http.ResponseWriter, r *http.Request) {
var newMacro structs.NewMacro
body, err := io.ReadAll(r.Body)
if err != nil {
panic(err)
}
log.Println(string(body))
err = json.Unmarshal(body, &newMacro)
if err != nil {
panic(err)
}
stepsJSON, err := json.Marshal(newMacro.Steps)
if err != nil {
panic(err)
}
err = os.WriteFile("../macros/"+helper.FormatMacroFileName(newMacro.Name)+".json", stepsJSON, 0644)
if err != nil {
panic(err)
}
}
func ListMacros(w http.ResponseWriter, r *http.Request) {
log.Println("listing macros")
dir := "../macros"
files, err := os.ReadDir(dir)
if err != nil {
log.Fatal(err)
}
var fileNames []string
for _, file := range files {
filename := filepath.Base(file.Name())
filename = strings.TrimSuffix(filename, filepath.Ext(filename))
filename = strings.Replace(filename, "_", " ", -1)
fileNames = append(fileNames, filename)
}
json.NewEncoder(w).Encode(fileNames)
}
func DeleteMacro(w http.ResponseWriter, r *http.Request) {}
func PlayMacro(w http.ResponseWriter, r *http.Request) {
var req structs.MacroRequest
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
macro := req.Macro
var filename = helper.FormatMacroFileName(macro)
var filepath = fmt.Sprintf("../macros/%s.json", filename)
macroFile, err := helper.ReadMacroFile(filepath)
if err != nil {
fmt.Println(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
helper.RunMacroSteps(macroFile)
}

View file

@ -0,0 +1,25 @@
package structs
type Allowed struct {
Local []string
Remote []string
Auth []string
}
var Endpoints = Allowed{
Local: []string{
"/macro/record",
"/macro/list",
"/macro/delete",
"/macro/play",
"/device/list",
},
Remote: []string{
"/macro/list",
"/device/access",
"/device/auth",
},
Auth: []string{
"/macro/play",
},
}

View file

@ -0,0 +1,6 @@
package structs
type Settings struct {
Name string `json:"name"`
Type string `json:"type"`
}

View file

@ -0,0 +1,19 @@
package structs
type MacroRequest struct {
Macro string `json:"macro"`
}
type Step struct {
Type string `json:"type"`
Key string `json:"key"`
Code string `json:"code"`
Location int `json:"location"`
Direction string `json:"direction"`
Value int `json:"value"`
}
type NewMacro struct {
Name string `json:"name"`
Steps []Step `json:"steps"`
}

View file

@ -0,0 +1 @@
{ "name": "moto g84 5G", "type": "phone" }

View file

View file

@ -0,0 +1 @@
{ "name": "Samsung Galaxy A-tab 8\"", "type": "tablet" }

View file

@ -1,3 +1,32 @@
module example.com/m
module be
go 1.24.0
require (
github.com/dblohm7/wingoes v0.0.0-20240820181039-f2b84150679e // indirect
github.com/ebitengine/purego v0.8.2 // indirect
github.com/gen2brain/shm v0.1.1 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-vgo/robotgo v0.110.6 // indirect
github.com/godbus/dbus/v5 v5.1.0 // indirect
github.com/jezek/xgb v1.1.1 // indirect
github.com/kbinani/screenshot v0.0.0-20250118074034-a3924b7bbc8c // indirect
github.com/lufia/plan9stats v0.0.0-20240909124753-873cd0166683 // indirect
github.com/lxn/win v0.0.0-20210218163916-a377121e959e // indirect
github.com/otiai10/gosseract v2.2.1+incompatible // indirect
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect
github.com/robotn/xgb v0.10.0 // indirect
github.com/robotn/xgbutil v0.10.0 // indirect
github.com/shirou/gopsutil/v4 v4.25.1 // indirect
github.com/tailscale/win v0.0.0-20250213223159-5992cb43ca35 // indirect
github.com/tklauser/go-sysconf v0.3.14 // indirect
github.com/tklauser/numcpus v0.9.0 // indirect
github.com/vcaesar/gops v0.40.0 // indirect
github.com/vcaesar/imgo v0.40.2 // indirect
github.com/vcaesar/keycode v0.10.1 // indirect
github.com/vcaesar/tt v0.20.1 // indirect
github.com/yusufpapurcu/wmi v1.2.4 // indirect
golang.org/x/exp v0.0.0-20250215185904-eff6e970281f // indirect
golang.org/x/image v0.24.0 // indirect
golang.org/x/sys v0.30.0 // indirect
)

61
be/go.sum Normal file
View file

@ -0,0 +1,61 @@
github.com/BurntSushi/freetype-go v0.0.0-20160129220410-b763ddbfe298/go.mod h1:D+QujdIlUNfa0igpNMk6UIvlb6C252URs4yupRUV4lQ=
github.com/BurntSushi/graphics-go v0.0.0-20160129215708-b43f31a4a966/go.mod h1:Mid70uvE93zn9wgF92A/r5ixgnvX8Lh68fxp9KQBaI0=
github.com/dblohm7/wingoes v0.0.0-20240820181039-f2b84150679e h1:L+XrFvD0vBIBm+Wf9sFN6aU395t7JROoai0qXZraA4U=
github.com/dblohm7/wingoes v0.0.0-20240820181039-f2b84150679e/go.mod h1:SUxUaAK/0UG5lYyZR1L1nC4AaYYvSSYTWQSH3FPcxKU=
github.com/ebitengine/purego v0.8.2 h1:jPPGWs2sZ1UgOSgD2bClL0MJIqu58nOmIcBuXr62z1I=
github.com/ebitengine/purego v0.8.2/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=
github.com/gen2brain/shm v0.1.1 h1:1cTVA5qcsUFixnDHl14TmRoxgfWEEZlTezpUj1vm5uQ=
github.com/gen2brain/shm v0.1.1/go.mod h1:UgIcVtvmOu+aCJpqJX7GOtiN7X2ct+TKLg4RTxwPIUA=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE=
github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78=
github.com/go-vgo/robotgo v0.110.6 h1:1tOxlmTXYg6F3Xs8IT++331MxY2nZ+Q3B6eW312llbo=
github.com/go-vgo/robotgo v0.110.6/go.mod h1:eBUjTHY1HYjzdi1+UWJUbxB+b9gE+l4Ei7vQU/9SnLw=
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/jezek/xgb v1.1.1 h1:bE/r8ZZtSv7l9gk6nU0mYx51aXrvnyb44892TwSaqS4=
github.com/jezek/xgb v1.1.1/go.mod h1:nrhwO0FX/enq75I7Y7G8iN1ubpSGZEiA3v9e9GyRFlk=
github.com/kbinani/screenshot v0.0.0-20250118074034-a3924b7bbc8c h1:1IlzDla/ZATV/FsRn1ETf7ir91PHS2mrd4VMunEtd9k=
github.com/kbinani/screenshot v0.0.0-20250118074034-a3924b7bbc8c/go.mod h1:Pmpz2BLf55auQZ67u3rvyI2vAQvNetkK/4zYUmpauZQ=
github.com/lufia/plan9stats v0.0.0-20240909124753-873cd0166683 h1:7UMa6KCCMjZEMDtTVdcGu0B1GmmC7QJKiCCjyTAWQy0=
github.com/lufia/plan9stats v0.0.0-20240909124753-873cd0166683/go.mod h1:ilwx/Dta8jXAgpFYFvSWEMwxmbWXyiUHkd5FwyKhb5k=
github.com/lxn/win v0.0.0-20210218163916-a377121e959e h1:H+t6A/QJMbhCSEH5rAuRxh+CtW96g0Or0Fxa9IKr4uc=
github.com/lxn/win v0.0.0-20210218163916-a377121e959e/go.mod h1:KxxjdtRkfNoYDCUP5ryK7XJJNTnpC8atvtmTheChOtk=
github.com/otiai10/gosseract v2.2.1+incompatible h1:Ry5ltVdpdp4LAa2bMjsSJH34XHVOV7XMi41HtzL8X2I=
github.com/otiai10/gosseract v2.2.1+incompatible/go.mod h1:XrzWItCzCpFRZ35n3YtVTgq5bLAhFIkascoRo8G32QE=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=
github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=
github.com/robotn/xgb v0.0.0-20190912153532-2cb92d044934/go.mod h1:SxQhJskUJ4rleVU44YvnrdvxQr0tKy5SRSigBrCgyyQ=
github.com/robotn/xgb v0.10.0 h1:O3kFbIwtwZ3pgLbp1h5slCQ4OpY8BdwugJLrUe6GPIM=
github.com/robotn/xgb v0.10.0/go.mod h1:SxQhJskUJ4rleVU44YvnrdvxQr0tKy5SRSigBrCgyyQ=
github.com/robotn/xgbutil v0.10.0 h1:gvf7mGQqCWQ68aHRtCxgdewRk+/KAJui6l3MJQQRCKw=
github.com/robotn/xgbutil v0.10.0/go.mod h1:svkDXUDQjUiWzLrA0OZgHc4lbOts3C+uRfP6/yjwYnU=
github.com/shirou/gopsutil/v4 v4.25.1 h1:QSWkTc+fu9LTAWfkZwZ6j8MSUk4A2LV7rbH0ZqmLjXs=
github.com/shirou/gopsutil/v4 v4.25.1/go.mod h1:RoUCUpndaJFtT+2zsZzzmhvbfGoDCJ7nFXKJf8GqJbI=
github.com/tailscale/win v0.0.0-20250213223159-5992cb43ca35 h1:wAZbkTZkqDzWsqxPh2qkBd3KvFU7tcxV0BP0Rnhkxog=
github.com/tailscale/win v0.0.0-20250213223159-5992cb43ca35/go.mod h1:aMd4yDHLjbOuYP6fMxj1d9ACDQlSWwYztcpybGHCQc8=
github.com/tklauser/go-sysconf v0.3.14 h1:g5vzr9iPFFz24v2KZXs/pvpvh8/V9Fw6vQK5ZZb78yU=
github.com/tklauser/go-sysconf v0.3.14/go.mod h1:1ym4lWMLUOhuBOPGtRcJm7tEGX4SCYNEEEtghGG/8uY=
github.com/tklauser/numcpus v0.9.0 h1:lmyCHtANi8aRUgkckBgoDk1nHCux3n2cgkJLXdQGPDo=
github.com/tklauser/numcpus v0.9.0/go.mod h1:SN6Nq1O3VychhC1npsWostA+oW+VOQTxZrS604NSRyI=
github.com/vcaesar/gops v0.40.0 h1:I+1RCGiV+LkZJUYNzAd373xs0uM2UyeFdZBmow8HfCM=
github.com/vcaesar/gops v0.40.0/go.mod h1:3u/USW7JovqUK6i13VOD3qWfvXXd2TIIKE4PYIv4TOM=
github.com/vcaesar/imgo v0.40.2 h1:5GWScRLdBCMtO1v2I1bs+ZmDLZFINxYSMZ+mtUw5qPM=
github.com/vcaesar/imgo v0.40.2/go.mod h1:MVCl+FxHI2gTgmiHoi0n5xNCbYcfv9SVtdEOUC92+eo=
github.com/vcaesar/keycode v0.10.1 h1:0DesGmMAPWpYTCYddOFiCMKCDKgNnwiQa2QXindVUHw=
github.com/vcaesar/keycode v0.10.1/go.mod h1:JNlY7xbKsh+LAGfY2j4M3znVrGEm5W1R8s/Uv6BJcfQ=
github.com/vcaesar/tt v0.20.1 h1:D/jUeeVCNbq3ad8M7hhtB3J9x5RZ6I1n1eZ0BJp7M+4=
github.com/vcaesar/tt v0.20.1/go.mod h1:cH2+AwGAJm19Wa6xvEa+0r+sXDJBT0QgNQey6mwqLeU=
github.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=
github.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=
golang.org/x/exp v0.0.0-20250215185904-eff6e970281f h1:oFMYAjX0867ZD2jcNiLBrI9BdpmEkvPyi5YrBGXbamg=
golang.org/x/exp v0.0.0-20250215185904-eff6e970281f/go.mod h1:BHOTPb3L19zxehTsLoJXVaTktb06DFgmdW6Wb9s8jqk=
golang.org/x/image v0.24.0 h1:AN7zRgVsbvmTfNyqIbbOraYL8mSwcKncEj8ofjgzcMQ=
golang.org/x/image v0.24.0/go.mod h1:4b/ITuLfqYq1hqZcjofwctIhi7sZh2WaCjvsBNjjya8=
golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201018230417-eeed37f84f13/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.30.0 h1:QjkSwP/36a20jFYWkSue1YwXzLmsV5Gfq7Eiy72C1uc=
golang.org/x/sys v0.30.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=

View file

@ -2,33 +2,26 @@ package main
import (
"log"
"mime"
"net/http"
"path/filepath"
"be/app"
"be/app/helper"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
file := "../public" // base directory
app.ApiCORS(w, r)
if r.URL.Path == "/" {
file = file + "/index.html" // default
} else {
file = file + r.URL.Path // request
if r.Method == "GET" {
app.ApiGet(w, r)
} else if r.Method == "POST" {
app.ApiPost(w, r)
}
contentType := mime.TypeByExtension(filepath.Ext(file)) // get content type
if contentType != "" {
w.Header().Set("Content-Type", contentType) // set content type header
}
log.Println(file)
log.Println("-------------")
http.ServeFile(w, r, file) // serve file
})
helper.OpenBrowser("http://localhost:6970")
log.Fatal(http.ListenAndServe(":6970", nil))
}