arns-lt-tree-push-service/server.go
2024-04-14 20:48:34 +03:00

143 lines
2.7 KiB
Go

package main
import (
"context"
"fmt"
"io"
"log"
"net"
"os"
"path"
zordTree "g.arns.lt/zordsdavini/zord-tree"
"google.golang.org/grpc"
)
type server struct {
UnimplementedTreeManagerServer
}
func (TreeManagerServer *server) GetSummery(_ context.Context, in *TreeRequest) (*Tree, error) {
log.Println(in)
tree, err := zordTree.BuildTree(source, meta, config)
if err != nil {
log.Fatal(err)
return nil, err
}
if *in.Path != "" {
ntree, err := tree.Slice(source + *in.Path)
if err != nil {
log.Fatal(err)
return &Tree{}, err
}
tree = ntree
}
if len(in.Filter) != 0 {
ntree, found := tree.Filter(simplifyFilter(in.Filter))
if !found {
return &Tree{}, err
}
tree = ntree
}
formattedTree := FormatTreeSummery(tree)
return &formattedTree, nil
}
func (TreeManagerServer *server) GetFile(_ context.Context, in *FileRequest) (*FileContent, error) {
log.Println(in)
tree, err := zordTree.BuildTree(source, meta, config)
if err != nil {
log.Fatal(err)
return nil, err
}
file, err := tree.FileById(in.Id)
if err != nil {
return nil, err
}
fileContent := GetContent(file)
return &fileContent, nil
}
func (TreeManagerServer *server) RebuildTree(
ctx context.Context,
in *TreeSecret,
) (*RebuildResponse, error) {
log.Println(in, key)
success := false
if in.Key == key {
Collect()
success = true
}
response := RebuildResponse{Success: success}
return &response, nil
}
func (TreeManagerServer *server) DownloadAttachment(
in *AttachmentRequest,
responseStream TreeManager_DownloadAttachmentServer,
) error {
file, err := os.Open(
path.Clean(fmt.Sprintf("%s/%s/%s", source, config.AttachmentDirName, in.Path)),
)
if err != nil {
return err
}
defer file.Close()
bufferSize := 64 * 1024
buff := make([]byte, bufferSize)
for {
bytesRead, err := file.Read(buff)
if err != nil {
if err != io.EOF {
log.Println("Error during downloadingAttachment: ", err)
}
break
}
resp := &AttachmentResponse{Chunk: buff[:bytesRead]}
err = responseStream.Send(resp)
if err != nil {
return err
}
}
return nil
}
func simplifyFilter(filter []*TreeRequest_Filter) map[string][]string {
simpleFilter := make(map[string][]string)
for _, f := range filter {
simpleFilter[f.Key] = append(simpleFilter[f.Key], f.Value)
}
return simpleFilter
}
func Run() {
if _, err := os.Stat(source); os.IsNotExist(err) {
log.Fatalf("Source directory does not exist.")
}
ln, err := net.Listen("tcp", ":8301")
if err != nil {
log.Fatalf("Failed to listen: " + err.Error())
}
var opts []grpc.ServerOption
grpcServer := grpc.NewServer(opts...)
RegisterTreeManagerServer(grpcServer, &server{})
err = grpcServer.Serve(ln)
if err != nil {
log.Fatalf("failed to serve: %v", err)
}
}