konfa-server/cmd/main.go

114 lines
2.6 KiB
Go
Raw Normal View History

2024-12-23 12:54:51 +00:00
package main
import (
"context"
"fmt"
"log"
"net"
2024-12-23 16:09:20 +00:00
"github.com/ilyakaznacheev/cleanenv"
2024-12-23 12:54:51 +00:00
"github.com/royalcat/konfa-server/pkg/uuid"
2024-12-25 14:20:49 +00:00
"github.com/royalcat/konfa-server/src/auth"
2024-12-23 12:54:51 +00:00
"github.com/royalcat/konfa-server/src/konfa"
"github.com/royalcat/konfa-server/src/proto"
chatv1 "github.com/royalcat/konfa-server/src/proto/konfa/chat/v1"
serverv1 "github.com/royalcat/konfa-server/src/proto/konfa/server/v1"
"github.com/royalcat/konfa-server/src/store"
"google.golang.org/grpc"
)
2024-12-23 16:09:20 +00:00
type Config struct {
DB string `env:"DB"`
}
2024-12-23 12:54:51 +00:00
func main() {
ctx := context.Background()
2024-12-23 16:09:20 +00:00
var cfg Config
err := cleanenv.ReadEnv(&cfg)
if err != nil {
panic(err)
}
db, dbpool, err := store.ConnectPostgres(ctx, cfg.DB)
2024-12-23 12:54:51 +00:00
if err != nil {
panic(err)
}
srv := konfa.NewService(db, dbpool)
2024-12-25 14:20:49 +00:00
authen, err := auth.NewAuthenticator(ctx, db, auth.AuthenticatorConfig{
Issuer: "https://sso.konfach.ru/realms/konfach",
ClientID: "konfa",
ClientSecret: "UqeaMowRXcGULkAepr0EAEUfE82OjY72",
})
if err != nil {
panic(err)
}
grpcServer := grpc.NewServer(
grpc.UnaryInterceptor(authen.UnaryAuthenticate),
grpc.StreamInterceptor(authen.StreamAuthenticate),
)
2024-12-23 12:54:51 +00:00
chatv1.RegisterChatServiceServer(grpcServer, proto.NewChatService(srv))
serverv1.RegisterServerServiceServer(grpcServer, proto.NewServerService(srv))
serverID, chanID, err := createKonfach(ctx, srv)
if err != nil {
panic(err)
}
println(serverID.String())
println(chanID.String())
port := 38100
lis, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", port))
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
println("Server is running on port", port)
panic(grpcServer.Serve(lis))
}
func createKonfach(ctx context.Context, srv *konfa.Service) (uuid.UUID, uuid.UUID, error) {
var serverID uuid.UUID
servers, err := srv.ListServers(ctx)
if err != nil {
return uuid.Nil, uuid.Nil, fmt.Errorf("failed to list servers: %w", err)
}
for _, serv := range servers {
if serv.Name == "konfach" {
serverID = serv.ID
}
}
if serverID == uuid.Nil {
serverID, err = srv.CreateServer(ctx, "konfach")
if err != nil {
return uuid.Nil, uuid.Nil, fmt.Errorf("failed to create server: %w", err)
}
}
var chanID uuid.UUID
2024-12-25 14:20:49 +00:00
channels, err := srv.ListTextChannelsOnServer(ctx, serverID)
2024-12-23 12:54:51 +00:00
if err != nil {
return uuid.Nil, uuid.Nil, err
}
for _, channel := range channels {
if channel.Name == "general" {
chanID = channel.ID
}
}
if chanID == uuid.Nil {
2024-12-25 14:20:49 +00:00
chanID, err = srv.CreateTextChannel(ctx, serverID, "general")
2024-12-23 12:54:51 +00:00
if err != nil {
return uuid.Nil, uuid.Nil, fmt.Errorf("failed to create channel: %w", err)
}
}
return serverID, chanID, nil
}