ussd/cmd/africastalking/main.go

226 lines
5.4 KiB
Go
Raw Permalink Normal View History

2024-09-12 14:56:57 +02:00
package main
import (
2024-11-07 14:46:12 +01:00
"bytes"
2024-09-12 14:56:57 +02:00
"context"
2024-11-07 14:46:12 +01:00
"encoding/json"
2024-09-12 14:56:57 +02:00
"flag"
"fmt"
2024-11-07 14:46:12 +01:00
"io"
"log"
2024-09-12 14:56:57 +02:00
"net/http"
"os"
"os/signal"
"path"
"strconv"
"strings"
"syscall"
"git.defalsify.org/vise.git/engine"
"git.defalsify.org/vise.git/logging"
"git.defalsify.org/vise.git/resource"
2024-10-15 22:41:16 +02:00
"git.grassecon.net/urdt/ussd/config"
"git.grassecon.net/urdt/ussd/initializers"
2024-09-12 14:56:57 +02:00
"git.grassecon.net/urdt/ussd/internal/handlers"
httpserver "git.grassecon.net/urdt/ussd/internal/http"
2024-09-19 15:15:29 +02:00
"git.grassecon.net/urdt/ussd/internal/storage"
2024-10-30 14:09:15 +01:00
"git.grassecon.net/urdt/ussd/remote"
2024-09-12 14:56:57 +02:00
)
var (
logg = logging.NewVanilla()
scriptDir = path.Join("services", "registration")
InfoLogger *log.Logger
ErrorLogger *log.Logger
2024-09-12 14:56:57 +02:00
)
2024-10-15 22:41:16 +02:00
func init() {
initializers.LoadEnvVariables()
2024-11-07 14:46:12 +01:00
logFile := "urdt-ussd-africastalking.log"
file, err := os.OpenFile(logFile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
log.Fatal(err)
}
InfoLogger = log.New(file, "INFO: ", log.Ldate|log.Ltime|log.Lshortfile)
ErrorLogger = log.New(file, "ERROR: ", log.Ldate|log.Ltime|log.Lshortfile)
// Inject into remote package
remote.InfoLogger = InfoLogger
remote.ErrorLogger = ErrorLogger
2024-10-15 22:41:16 +02:00
}
2024-09-19 15:15:29 +02:00
type atRequestParser struct{}
2024-09-12 14:56:57 +02:00
2024-09-19 15:15:29 +02:00
func (arp *atRequestParser) GetSessionId(rq any) (string, error) {
2024-09-12 14:56:57 +02:00
rqv, ok := rq.(*http.Request)
if !ok {
2024-11-07 14:46:12 +01:00
ErrorLogger.Println("got an invalid request:", rq)
2024-09-12 14:56:57 +02:00
return "", handlers.ErrInvalidRequest
}
2024-11-07 14:46:12 +01:00
// Capture body (if any) for logging
body, err := io.ReadAll(rqv.Body)
if err != nil {
ErrorLogger.Println("failed to read request body:", err)
return "", fmt.Errorf("failed to read request body: %v", err)
}
// Reset the body for further reading
rqv.Body = io.NopCloser(bytes.NewReader(body))
// Log the body as JSON
bodyLog := map[string]string{"body": string(body)}
logBytes, err := json.Marshal(bodyLog)
if err != nil {
ErrorLogger.Println("failed to marshal request body:", err)
} else {
InfoLogger.Println("Received request:", string(logBytes))
}
2024-09-12 14:56:57 +02:00
if err := rqv.ParseForm(); err != nil {
2024-11-07 14:46:12 +01:00
ErrorLogger.Println("failed to parse form data: %v", err)
2024-09-12 14:56:57 +02:00
return "", fmt.Errorf("failed to parse form data: %v", err)
}
phoneNumber := rqv.FormValue("phoneNumber")
if phoneNumber == "" {
return "", fmt.Errorf("no phone number found")
}
return phoneNumber, nil
}
2024-09-19 15:15:29 +02:00
func (arp *atRequestParser) GetInput(rq any) ([]byte, error) {
2024-09-12 14:56:57 +02:00
rqv, ok := rq.(*http.Request)
if !ok {
return nil, handlers.ErrInvalidRequest
}
if err := rqv.ParseForm(); err != nil {
return nil, fmt.Errorf("failed to parse form data: %v", err)
}
text := rqv.FormValue("text")
parts := strings.Split(text, "*")
if len(parts) == 0 {
return nil, fmt.Errorf("no input found")
}
return []byte(parts[len(parts)-1]), nil
}
func main() {
2024-10-15 22:41:16 +02:00
config.LoadConfig()
2024-09-12 14:56:57 +02:00
var dbDir string
var resourceDir string
var size uint
var database string
2024-09-12 14:56:57 +02:00
var engineDebug bool
var host string
var port uint
flag.StringVar(&dbDir, "dbdir", ".state", "database dir to read from")
flag.StringVar(&resourceDir, "resourcedir", path.Join("services", "registration"), "resource dir")
flag.StringVar(&database, "db", "gdbm", "database to be used")
2024-09-24 15:11:22 +02:00
flag.BoolVar(&engineDebug, "d", false, "use engine debug output")
2024-09-12 14:56:57 +02:00
flag.UintVar(&size, "s", 160, "max size of output")
2024-10-15 22:41:16 +02:00
flag.StringVar(&host, "h", initializers.GetEnv("HOST", "127.0.0.1"), "http host")
flag.UintVar(&port, "p", initializers.GetEnvUint("PORT", 7123), "http port")
2024-09-12 14:56:57 +02:00
flag.Parse()
2024-09-19 15:15:29 +02:00
logg.Infof("start command", "dbdir", dbDir, "resourcedir", resourceDir, "outputsize", size)
2024-09-12 14:56:57 +02:00
ctx := context.Background()
ctx = context.WithValue(ctx, "Database", database)
2024-09-12 14:56:57 +02:00
pfp := path.Join(scriptDir, "pp.csv")
cfg := engine.Config{
Root: "root",
OutputSize: uint32(size),
2024-10-15 12:59:49 +02:00
FlagCount: uint32(128),
2024-09-12 14:56:57 +02:00
}
2024-09-24 15:11:22 +02:00
2024-09-12 14:56:57 +02:00
if engineDebug {
cfg.EngineDebug = true
}
menuStorageService := storage.NewMenuStorageService(dbDir, resourceDir)
rs, err := menuStorageService.GetResource(ctx)
2024-09-12 14:56:57 +02:00
if err != nil {
fmt.Fprintf(os.Stderr, err.Error())
os.Exit(1)
}
err = menuStorageService.EnsureDbDir()
2024-09-12 14:56:57 +02:00
if err != nil {
fmt.Fprintf(os.Stderr, err.Error())
os.Exit(1)
}
2024-09-22 03:33:11 +02:00
userdataStore, err := menuStorageService.GetUserdataDb(ctx)
2024-09-12 14:56:57 +02:00
if err != nil {
fmt.Fprintf(os.Stderr, err.Error())
os.Exit(1)
}
defer userdataStore.Close()
dbResource, ok := rs.(*resource.DbResource)
if !ok {
os.Exit(1)
}
2024-09-19 20:04:09 +02:00
2024-10-31 18:59:11 +01:00
lhs, err := handlers.NewLocalHandlerService(ctx, pfp, true, dbResource, cfg, rs)
2024-09-22 03:33:11 +02:00
lhs.SetDataStore(&userdataStore)
2024-09-19 15:15:29 +02:00
if err != nil {
fmt.Fprintf(os.Stderr, err.Error())
os.Exit(1)
}
2024-09-12 14:56:57 +02:00
2024-10-30 14:09:15 +01:00
accountService := remote.AccountService{}
2024-10-17 11:54:11 +02:00
hl, err := lhs.GetHandler(&accountService)
2024-09-12 14:56:57 +02:00
if err != nil {
fmt.Fprintf(os.Stderr, err.Error())
os.Exit(1)
}
stateStore, err := menuStorageService.GetStateStore(ctx)
2024-09-12 14:56:57 +02:00
if err != nil {
fmt.Fprintf(os.Stderr, err.Error())
os.Exit(1)
}
defer stateStore.Close()
rp := &atRequestParser{}
bsh := handlers.NewBaseSessionHandler(cfg, rs, stateStore, userdataStore, rp, hl)
2024-09-14 14:55:45 +02:00
sh := httpserver.NewATSessionHandler(bsh)
mux := http.NewServeMux()
mux.Handle(initializers.GetEnv("AT_ENDPOINT", "/"), sh)
2024-09-12 14:56:57 +02:00
s := &http.Server{
2024-09-19 15:15:29 +02:00
Addr: fmt.Sprintf("%s:%s", host, strconv.Itoa(int(port))),
Handler: mux,
2024-09-12 14:56:57 +02:00
}
s.RegisterOnShutdown(sh.Shutdown)
cint := make(chan os.Signal)
cterm := make(chan os.Signal)
signal.Notify(cint, os.Interrupt, syscall.SIGINT)
signal.Notify(cterm, os.Interrupt, syscall.SIGTERM)
go func() {
select {
case _ = <-cint:
case _ = <-cterm:
}
s.Shutdown(ctx)
}()
err = s.ListenAndServe()
if err != nil {
logg.Infof("Server closed with error", "err", err)
}
}