This repository has been archived on 2024-07-22. You can view files and clone it, but cannot push or open issues or pull requests.
plug-sdk/pkg/plug/server.go

82 lines
2.0 KiB
Go
Raw Permalink Normal View History

2024-02-20 18:11:34 +00:00
package plug
import (
"context"
"fmt"
"log"
"net"
2024-07-06 22:26:24 +00:00
"git.dragse.it/anthrove/otter-space-sdk/v2/pkg/database"
"git.dragse.it/anthrove/otter-space-sdk/v2/pkg/models"
2024-02-20 18:11:34 +00:00
2024-07-08 13:16:59 +00:00
pb "git.dragse.it/anthrove/plug-sdk/v2/pkg/grpc"
2024-02-20 18:11:34 +00:00
"google.golang.org/grpc"
)
type TaskExecution func(ctx context.Context, database database.OtterSpace, sourceUsername string, anthroveUser models.User, deepScrape bool, apiKey string, cancelFunction func()) error
type SendMessageExecution func(ctx context.Context, userSourceID string, message string) error
type Plug struct {
address string
port string
ctx context.Context
2024-07-06 22:26:24 +00:00
database database.OtterSpace
taskExecutionFunction TaskExecution
sendMessageExecution SendMessageExecution
source models.Source
2024-02-20 18:11:34 +00:00
}
func NewPlug(ctx context.Context, address string, port string, source models.Source) Plug {
return Plug{
2024-02-20 18:11:34 +00:00
ctx: ctx,
address: address,
port: port,
source: source,
2024-02-20 18:11:34 +00:00
}
}
func (p *Plug) Listen() error {
2024-02-20 18:11:34 +00:00
var err error
plugSource, err := p.database.GetSourceByDomain(p.ctx, models.AnthroveSourceDomain(p.source.Domain))
if err != nil {
return err
}
if plugSource == nil {
2024-07-08 13:16:59 +00:00
log.Printf("no source found for domain %s, initilazing source!", p.source.Domain)
err := p.database.CreateSource(p.ctx, &p.source)
if err != nil {
return err
}
}
2024-07-08 13:16:59 +00:00
lis, err := net.Listen("tcp", fmt.Sprintf("%s:%s", p.address, p.port))
2024-02-20 18:11:34 +00:00
if err != nil {
return err
}
grpcServer := grpc.NewServer()
pb.RegisterPlugConnectorServer(grpcServer, NewGrpcServer(p.database, p.taskExecutionFunction, p.sendMessageExecution))
2024-02-20 18:11:34 +00:00
err = grpcServer.Serve(lis)
if err != nil {
return err
}
return nil
}
func (p *Plug) WithOtterSpace(graph database.OtterSpace) {
p.database = graph
}
func (p *Plug) TaskExecutionFunction(function TaskExecution) {
p.taskExecutionFunction = function
2024-02-20 18:11:34 +00:00
}
func (p *Plug) SendMessageExecution(function SendMessageExecution) {
p.sendMessageExecution = function
}