66 lines
1.9 KiB
Go
66 lines
1.9 KiB
Go
package server
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"gitea.benny.dog/torjus/ezshare/pb"
|
|
"gitea.benny.dog/torjus/ezshare/store"
|
|
"github.com/dustin/go-humanize"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
type GRPCFileServiceServer struct {
|
|
Logger *zap.SugaredLogger
|
|
Hostname string
|
|
store store.FileStore
|
|
pb.UnimplementedFileServiceServer
|
|
}
|
|
|
|
func NewGRPCFileServiceServer(store store.FileStore) *GRPCFileServiceServer {
|
|
return &GRPCFileServiceServer{Hostname: "localhost:8051", store: store, Logger: zap.NewNop().Sugar()}
|
|
}
|
|
|
|
func (s *GRPCFileServiceServer) UploadFile(ctx context.Context, req *pb.UploadFileRequest) (*pb.UploadFileResponse, error) {
|
|
var f pb.File
|
|
f.Data = req.GetData()
|
|
|
|
id, err := s.store.StoreFile(&f)
|
|
if err != nil {
|
|
s.Logger.Warnw("Error storing file.", "error", err)
|
|
return nil, err
|
|
}
|
|
s.Logger.Infow("Received file.", "id", id, "size", humanize.Bytes(uint64(len(f.Data))))
|
|
return &pb.UploadFileResponse{Id: id, FileUrl: fmt.Sprintf("%s/files/%s", s.Hostname, id)}, nil
|
|
}
|
|
|
|
func (s *GRPCFileServiceServer) GetFile(ctx context.Context, req *pb.GetFileRequest) (*pb.GetFileResponse, error) {
|
|
f, err := s.store.GetFile(req.Id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
s.Logger.Infow("Sending file to client.", "id", f.FileId, "size", humanize.Bytes(uint64(len(f.Data))))
|
|
|
|
return &pb.GetFileResponse{File: f}, nil
|
|
}
|
|
|
|
func (s *GRPCFileServiceServer) DeleteFile(ctx context.Context, req *pb.DeleteFileRequest) (*pb.DeleteFileResponse, error) {
|
|
if err := s.store.DeleteFile(req.Id); err != nil {
|
|
s.Logger.Warnw("Error deleting file.", "error", err)
|
|
return nil, err
|
|
}
|
|
s.Logger.Infow("Deleted file.", "id", req.Id)
|
|
return &pb.DeleteFileResponse{}, nil
|
|
}
|
|
|
|
func (s *GRPCFileServiceServer) ListFiles(ctx context.Context, req *pb.ListFilesRequest) (*pb.ListFilesResponse, error) {
|
|
infos, err := s.store.ListFiles()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &pb.ListFilesResponse{
|
|
Files: infos,
|
|
}, nil
|
|
}
|