ezshare/server/fileservice.go

66 lines
1.9 KiB
Go
Raw Normal View History

2021-12-03 22:04:09 +00:00
package server
import (
"context"
"fmt"
"gitea.benny.dog/torjus/ezshare/pb"
"gitea.benny.dog/torjus/ezshare/store"
2021-12-06 06:55:30 +00:00
"github.com/dustin/go-humanize"
"go.uber.org/zap"
2021-12-03 22:04:09 +00:00
)
type GRPCFileServiceServer struct {
2021-12-06 06:55:30 +00:00
Logger *zap.SugaredLogger
2021-12-03 22:04:09 +00:00
Hostname string
store store.FileStore
pb.UnimplementedFileServiceServer
}
func NewGRPCFileServiceServer(store store.FileStore) *GRPCFileServiceServer {
2021-12-06 06:55:30 +00:00
return &GRPCFileServiceServer{Hostname: "localhost:8051", store: store, Logger: zap.NewNop().Sugar()}
2021-12-03 22:04:09 +00:00
}
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 {
2021-12-06 06:55:30 +00:00
s.Logger.Warnw("Error storing file.", "error", err)
2021-12-03 22:04:09 +00:00
return nil, err
}
2021-12-06 06:55:30 +00:00
s.Logger.Infow("Received file.", "id", id, "size", humanize.Bytes(uint64(len(f.Data))))
2021-12-03 22:04:09 +00:00
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
}
2021-12-06 06:55:30 +00:00
s.Logger.Infow("Sending file to client.", "id", f.FileId, "size", humanize.Bytes(uint64(len(f.Data))))
2021-12-03 22:04:09 +00:00
return &pb.GetFileResponse{File: f}, nil
}
2021-12-04 10:30:42 +00:00
func (s *GRPCFileServiceServer) DeleteFile(ctx context.Context, req *pb.DeleteFileRequest) (*pb.DeleteFileResponse, error) {
2021-12-06 06:55:30 +00:00
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
2021-12-04 10:30:42 +00:00
}
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
}