92 lines
2.7 KiB
Go
92 lines
2.7 KiB
Go
package app
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
)
|
|
|
|
// ---------------------------------------------------------------------
|
|
// routes timer
|
|
// ---------------------------------------------------------------------
|
|
|
|
// старый toggle (используем из GUI, если что)
|
|
func handleRoutesTimerToggle(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodPost {
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
enabled := isTimerEnabled()
|
|
res := runRoutesTimerSet(!enabled)
|
|
writeJSON(w, http.StatusOK, res)
|
|
}
|
|
|
|
// новый API: GET → {enabled:bool}, POST {enabled:bool}
|
|
// ---------------------------------------------------------------------
|
|
// EN: `handleRoutesTimer` is an HTTP handler for routes timer.
|
|
// RU: `handleRoutesTimer` - HTTP-обработчик для routes timer.
|
|
// ---------------------------------------------------------------------
|
|
func handleRoutesTimer(w http.ResponseWriter, r *http.Request) {
|
|
switch r.Method {
|
|
case http.MethodGet:
|
|
enabled := isTimerEnabled()
|
|
writeJSON(w, http.StatusOK, map[string]any{
|
|
"enabled": enabled,
|
|
})
|
|
case http.MethodPost:
|
|
var body struct {
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
if r.Body != nil {
|
|
defer r.Body.Close()
|
|
_ = json.NewDecoder(io.LimitReader(r.Body, 1<<20)).Decode(&body)
|
|
}
|
|
res := runRoutesTimerSet(body.Enabled)
|
|
writeJSON(w, http.StatusOK, res)
|
|
default:
|
|
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------
|
|
// EN: `isTimerEnabled` checks whether timer enabled is true.
|
|
// RU: `isTimerEnabled` - проверяет, является ли timer enabled истинным условием.
|
|
// ---------------------------------------------------------------------
|
|
func isTimerEnabled() bool {
|
|
unit := routesTimerUnitName()
|
|
if unit == "" {
|
|
return false
|
|
}
|
|
_, _, code, _ := runCommand("systemctl", "is-enabled", unit)
|
|
return code == 0
|
|
}
|
|
|
|
func runRoutesTimerSet(enabled bool) cmdResult {
|
|
unit := routesTimerUnitName()
|
|
if unit == "" {
|
|
return cmdResult{
|
|
OK: false,
|
|
Message: "routes timer unit unresolved: set preferred iface or SELECTIVE_VPN_ROUTES_TIMER",
|
|
}
|
|
}
|
|
cmd := []string{"systemctl", "disable", "--now", unit}
|
|
msg := "routes timer disabled"
|
|
if enabled {
|
|
cmd = []string{"systemctl", "enable", "--now", unit}
|
|
msg = "routes timer enabled"
|
|
}
|
|
stdout, stderr, exitCode, err := runCommand(cmd[0], cmd[1:]...)
|
|
res := cmdResult{
|
|
OK: err == nil && exitCode == 0,
|
|
Message: fmt.Sprintf("%s (%s)", msg, unit),
|
|
ExitCode: exitCode,
|
|
Stdout: stdout,
|
|
Stderr: stderr,
|
|
}
|
|
if err != nil {
|
|
res.Message = fmt.Sprintf("%s (%s): %v", msg, unit, err)
|
|
}
|
|
return res
|
|
}
|