2024-03-19 00:31:35 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"log"
|
|
|
|
"os"
|
|
|
|
"os/signal"
|
|
|
|
"sync"
|
|
|
|
"syscall"
|
|
|
|
|
|
|
|
"github.com/urfave/cli/v2"
|
|
|
|
"go.uber.org/zap"
|
|
|
|
)
|
|
|
|
|
|
|
|
func serve(cCtx *cli.Context) error {
|
|
|
|
ctx, cancel := context.WithCancel(cCtx.Context)
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
sig := make(chan os.Signal, 1)
|
|
|
|
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
|
|
|
|
<-sig
|
|
|
|
cancel()
|
|
|
|
}()
|
|
|
|
|
|
|
|
rawLogger, err := zap.NewDevelopment()
|
|
|
|
if err != nil {
|
|
|
|
log.Fatalf("Error initializing logger: %v", err)
|
|
|
|
}
|
|
|
|
logger = rawLogger.Sugar()
|
|
|
|
|
|
|
|
logger.Info("Running serve command, flags passed:")
|
|
|
|
for _, flag := range ServeFlags {
|
|
|
|
logger.Infof("-%s %v", flag.Names()[0], cCtx.Value(flag.Names()[0]))
|
|
|
|
}
|
|
|
|
|
|
|
|
name := cCtx.String(NameFlag)
|
|
|
|
port := cCtx.Int(PortFlag)
|
2024-04-09 15:44:43 +00:00
|
|
|
apiModules := cCtx.String(APIModulesFlag)
|
2024-05-22 22:01:54 +00:00
|
|
|
telemetryUrl := cCtx.String(TelemetryServerURLFlag)
|
2024-03-19 00:31:35 +00:00
|
|
|
|
2024-05-22 22:01:54 +00:00
|
|
|
cli, err := start(cCtx, name, port, apiModules, telemetryUrl)
|
2024-03-19 00:31:35 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2024-04-09 15:44:43 +00:00
|
|
|
defer cli.stop()
|
2024-03-19 00:31:35 +00:00
|
|
|
|
|
|
|
// Retrieve for messages
|
|
|
|
var wg sync.WaitGroup
|
|
|
|
msgCh := make(chan string)
|
|
|
|
|
|
|
|
wg.Add(1)
|
2024-04-09 15:44:43 +00:00
|
|
|
go cli.retrieveMessagesLoop(ctx, RetrieveInterval, msgCh, &wg)
|
2024-03-19 00:31:35 +00:00
|
|
|
|
2024-04-09 15:44:43 +00:00
|
|
|
// Send and accept contact request
|
2024-03-19 00:31:35 +00:00
|
|
|
dest := cCtx.String(AddFlag)
|
|
|
|
if dest != "" {
|
2024-04-09 15:44:43 +00:00
|
|
|
err := cli.sendContactRequest(cCtx, dest)
|
2024-03-19 00:31:35 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
msgID := <-msgCh
|
2024-04-09 15:44:43 +00:00
|
|
|
err = cli.sendContactRequestAcceptance(cCtx, msgID)
|
2024-03-19 00:31:35 +00:00
|
|
|
if err != nil {
|
|
|
|
logger.Error(err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Send message if mutual contact exists
|
|
|
|
sem := make(chan struct{}, 1)
|
|
|
|
wg.Add(1)
|
2024-04-09 15:44:43 +00:00
|
|
|
go cli.sendMessageLoop(ctx, SendInterval, &wg, sem, cancel)
|
2024-03-19 00:31:35 +00:00
|
|
|
|
|
|
|
wg.Wait()
|
|
|
|
logger.Info("Exiting")
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|