Commit e43da393 authored by ZHCode's avatar ZHCode
Browse files

Add faucet and crypto payment.

parent a21d2aa5
package faucet
import (
"fmt"
"github.com/gogo/protobuf/types"
"github.com/google/uuid"
"github.com/vmihailenco/msgpack"
entity "gitlab.com/service31/Data/Entity"
module "gitlab.com/service31/Data/Module/Faucet"
)
//ClaimHistory claim history entity
type ClaimHistory struct {
entity.Base
EntityID uuid.UUID `gorm:"not null"`
Amount float64 `gorm:"not null"`
}
//ToDTO dto
func (e *ClaimHistory) ToDTO() (*module.HistoryDTO, error) {
t, err := types.TimestampProto(e.Base.CreatedAt)
if err != nil {
return nil, fmt.Errorf("Failed to convert %v to timestamp format for ClaimHistory", e.Base.CreatedAt)
}
return &module.HistoryDTO{
Amount: e.Amount,
Timestamp: t,
}, nil
}
//MarshalBinary for redis
func (e *ClaimHistory) MarshalBinary() ([]byte, error) {
return msgpack.Marshal(e)
}
//UnmarshalBinary for redis
func (e *ClaimHistory) UnmarshalBinary(data []byte) error {
// convert data to yours, let's assume its json data
return msgpack.Unmarshal(data, e)
}
package faucet
import (
"github.com/vmihailenco/msgpack"
entity "gitlab.com/service31/Data/Entity"
)
//IPAddress IP Address entity
type IPAddress struct {
entity.Base
IPAddress string `gorm:"primary_key"`
IsBanned bool `gorm:"not null;default:false"`
Players []*Player
}
//MarshalBinary for redis
func (e *IPAddress) MarshalBinary() ([]byte, error) {
return msgpack.Marshal(e)
}
//UnmarshalBinary for redis
func (e *IPAddress) UnmarshalBinary(data []byte) error {
// convert data to yours, let's assume its json data
return msgpack.Unmarshal(data, e)
}
package faucet
import (
"fmt"
"time"
"github.com/gogo/protobuf/types"
"github.com/google/uuid"
"github.com/vmihailenco/msgpack"
entity "gitlab.com/service31/Data/Entity"
module "gitlab.com/service31/Data/Module/Faucet"
paymentModule "gitlab.com/service31/Data/Module/Payment"
)
//Player player entity
type Player struct {
entity.Base
EntityID uuid.UUID `gorm:"not null"`
Type string `gorm:"not null"`
LastClaim time.Time `gorm:"not null"`
BonusAmountPct uint32 `gorm:"not null;default:1"`
ReferalID uint64 `gorm:"not null;auto_increment;unique_index"`
ReferalCount uint64 `gorm:"not null;default:0"`
ReferalClaimAmount float64 `gorm:"not null;default:0"`
ReferedByID uuid.UUID
Histories []*ClaimHistory
IPAddressList []*IPAddress
}
//ToDTO dto
func (e *Player) ToDTO() (*module.PlayerDTO, error) {
t, err := types.TimestampProto(e.LastClaim)
if err != nil {
return nil, fmt.Errorf("Failed to convert %v to timestamp format for Player", e.LastClaim)
}
tp, ok := paymentModule.CryptoType_value[e.Type]
if !ok {
return nil, fmt.Errorf("%s is not found as CryptoType", e.Type)
}
dto := &module.PlayerDTO{
EntityID: e.EntityID.String(),
Type: paymentModule.CryptoType(tp),
ReferalID: e.ReferalID,
LastClaim: t,
BonusAmountPct: e.BonusAmountPct,
ReferalCount: e.ReferalCount,
ReferalClaimAmount: e.ReferalClaimAmount,
}
for _, h := range e.Histories {
hdto, err := h.ToDTO()
if err != nil {
return nil, err
}
dto.Histories = append(dto.Histories, hdto)
}
return dto, nil
}
//MarshalBinary for redis
func (e *Player) MarshalBinary() ([]byte, error) {
return msgpack.Marshal(e)
}
//UnmarshalBinary for redis
func (e *Player) UnmarshalBinary(data []byte) error {
// convert data to yours, let's assume its json data
return msgpack.Unmarshal(data, e)
}
package payment
import (
"fmt"
"github.com/google/uuid"
"github.com/vmihailenco/msgpack"
entity "gitlab.com/service31/Data/Entity"
module "gitlab.com/service31/Data/Module/Payment"
)
//CryptoBalance CryptoBalance entity
type CryptoBalance struct {
entity.Base
EntityID uuid.UUID `gorm:"primary_key;not null"`
Type string `gorm:"not null"`
Balance float32 `gorm:"not null;default:0"`
Histories []*CryptoHistory `gorm:"foreignkey:BalanceID"`
}
//ToDTO dto
func (e *CryptoBalance) ToDTO() (*module.CryptoBalanceDTO, error) {
t, ok := module.CryptoType_value[e.Type]
if !ok {
return nil, fmt.Errorf("%s is not found as CryptoType", e.Type)
}
dto := &module.CryptoBalanceDTO{
EntityID: e.EntityID.String(),
Type: module.CryptoType(t),
Balance: e.Balance,
}
for _, h := range e.Histories {
dto.Histories = append(dto.Histories, h.ToDTO())
}
return dto, nil
}
//MarshalBinary for redis
func (e *CryptoBalance) MarshalBinary() ([]byte, error) {
return msgpack.Marshal(e)
}
//UnmarshalBinary for redis
func (e *CryptoBalance) UnmarshalBinary(data []byte) error {
// convert data to yours, let's assume its json data
return msgpack.Unmarshal(data, e)
}
package payment
import (
"fmt"
"github.com/google/uuid"
"github.com/vmihailenco/msgpack"
entity "gitlab.com/service31/Data/Entity"
module "gitlab.com/service31/Data/Module/Payment"
)
//CryptoCurrency struct
type CryptoCurrency struct {
entity.Base
EntityID uuid.UUID `gorm:"primary_key;not null"`
Balance []*CryptoBalance `gorm:"not null"`
}
func (e *CryptoCurrency) ToDTO() (*module.CryptoCurrencyDTO, error) {
dto := &module.CryptoCurrencyDTO{
EntityID: e.EntityID.String(),
}
for _, b := range e.Balance {
bdto, err := b.ToDTO()
if err != nil {
return nil, fmt.Errorf("Failed to parse CryptoCurrencyDTO. Error: " + err.Error())
}
dto.Balance = append(dto.Balance, bdto)
}
return dto, nil
}
//MarshalBinary for redis
func (e *CryptoCurrency) MarshalBinary() ([]byte, error) {
return msgpack.Marshal(e)
}
//UnmarshalBinary for redis
func (e *CryptoCurrency) UnmarshalBinary(data []byte) error {
// convert data to yours, let's assume its json data
return msgpack.Unmarshal(data, e)
}
package payment
import (
"github.com/vmihailenco/msgpack"
entity "gitlab.com/service31/Data/Entity"
module "gitlab.com/service31/Data/Module/Payment"
)
//CryptoHistory transaction history
type CryptoHistory struct {
entity.Base
Amount float32 `gorm:"not null"`
Reason string `gorm:"not null"`
WithdrawAddress string
Tx string
}
//ToDTO dto
func (e *CryptoHistory) ToDTO() *module.CryptoHistoryDTO {
return &module.CryptoHistoryDTO{
Amount: e.Amount,
Reason: e.Reason,
WithdrawAddress: e.WithdrawAddress,
Tx: e.Tx,
}
}
//MarshalBinary for redis
func (e *CryptoHistory) MarshalBinary() ([]byte, error) {
return msgpack.Marshal(e)
}
//UnmarshalBinary for redis
func (e *CryptoHistory) UnmarshalBinary(data []byte) error {
// convert data to yours, let's assume its json data
return msgpack.Unmarshal(data, e)
}
......@@ -15,7 +15,7 @@ type User struct {
EntityID string `gorm:"not null"`
Username string `gorm:"not null"`
Password string `gorm:"not null"`
Gender string `gorm:"not null"`
Gender string
PhoneNumber string
Email string
DOB time.Time
......
This diff is collapsed.
// Code generated by protoc-gen-grpc-gateway. DO NOT EDIT.
// source: Module/Faucet/faucet.proto
/*
Package faucet is a reverse proxy.
It translates gRPC into RESTful JSON APIs.
*/
package faucet
import (
"context"
"io"
"net/http"
"github.com/golang/protobuf/descriptor"
"github.com/golang/protobuf/proto"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"github.com/grpc-ecosystem/grpc-gateway/utilities"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/grpclog"
"google.golang.org/grpc/status"
)
// Suppress "imported and not used" errors
var _ codes.Code
var _ io.Reader
var _ status.Status
var _ = runtime.String
var _ = utilities.NewDoubleArray
var _ = descriptor.ForMessage
func request_FaucetService_GetPlayer_0(ctx context.Context, marshaler runtime.Marshaler, client FaucetServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq EmptyRequest
var metadata runtime.ServerMetadata
msg, err := client.GetPlayer(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_FaucetService_GetPlayer_0(ctx context.Context, marshaler runtime.Marshaler, server FaucetServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq EmptyRequest
var metadata runtime.ServerMetadata
msg, err := server.GetPlayer(ctx, &protoReq)
return msg, metadata, err
}
func request_FaucetService_Claim_0(ctx context.Context, marshaler runtime.Marshaler, client FaucetServiceClient, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ClaimRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := client.Claim(ctx, &protoReq, grpc.Header(&metadata.HeaderMD), grpc.Trailer(&metadata.TrailerMD))
return msg, metadata, err
}
func local_request_FaucetService_Claim_0(ctx context.Context, marshaler runtime.Marshaler, server FaucetServiceServer, req *http.Request, pathParams map[string]string) (proto.Message, runtime.ServerMetadata, error) {
var protoReq ClaimRequest
var metadata runtime.ServerMetadata
newReader, berr := utilities.IOReaderFactory(req.Body)
if berr != nil {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", berr)
}
if err := marshaler.NewDecoder(newReader()).Decode(&protoReq); err != nil && err != io.EOF {
return nil, metadata, status.Errorf(codes.InvalidArgument, "%v", err)
}
msg, err := server.Claim(ctx, &protoReq)
return msg, metadata, err
}
// RegisterFaucetServiceHandlerServer registers the http handlers for service FaucetService to "mux".
// UnaryRPC :call FaucetServiceServer directly.
// StreamingRPC :currently unsupported pending https://github.com/grpc/grpc-go/issues/906.
func RegisterFaucetServiceHandlerServer(ctx context.Context, mux *runtime.ServeMux, server FaucetServiceServer) error {
mux.Handle("GET", pattern_FaucetService_GetPlayer_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_FaucetService_GetPlayer_0(rctx, inboundMarshaler, server, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_FaucetService_GetPlayer_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_FaucetService_Claim_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateIncomingContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := local_request_FaucetService_Claim_0(rctx, inboundMarshaler, server, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_FaucetService_Claim_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
// RegisterFaucetServiceHandlerFromEndpoint is same as RegisterFaucetServiceHandler but
// automatically dials to "endpoint" and closes the connection when "ctx" gets done.
func RegisterFaucetServiceHandlerFromEndpoint(ctx context.Context, mux *runtime.ServeMux, endpoint string, opts []grpc.DialOption) (err error) {
conn, err := grpc.Dial(endpoint, opts...)
if err != nil {
return err
}
defer func() {
if err != nil {
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
return
}
go func() {
<-ctx.Done()
if cerr := conn.Close(); cerr != nil {
grpclog.Infof("Failed to close conn to %s: %v", endpoint, cerr)
}
}()
}()
return RegisterFaucetServiceHandler(ctx, mux, conn)
}
// RegisterFaucetServiceHandler registers the http handlers for service FaucetService to "mux".
// The handlers forward requests to the grpc endpoint over "conn".
func RegisterFaucetServiceHandler(ctx context.Context, mux *runtime.ServeMux, conn *grpc.ClientConn) error {
return RegisterFaucetServiceHandlerClient(ctx, mux, NewFaucetServiceClient(conn))
}
// RegisterFaucetServiceHandlerClient registers the http handlers for service FaucetService
// to "mux". The handlers forward requests to the grpc endpoint over the given implementation of "FaucetServiceClient".
// Note: the gRPC framework executes interceptors within the gRPC handler. If the passed in "FaucetServiceClient"
// doesn't go through the normal gRPC flow (creating a gRPC client etc.) then it will be up to the passed in
// "FaucetServiceClient" to call the correct interceptors.
func RegisterFaucetServiceHandlerClient(ctx context.Context, mux *runtime.ServeMux, client FaucetServiceClient) error {
mux.Handle("GET", pattern_FaucetService_GetPlayer_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_FaucetService_GetPlayer_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_FaucetService_GetPlayer_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
mux.Handle("POST", pattern_FaucetService_Claim_0, func(w http.ResponseWriter, req *http.Request, pathParams map[string]string) {
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
inboundMarshaler, outboundMarshaler := runtime.MarshalerForRequest(mux, req)
rctx, err := runtime.AnnotateContext(ctx, mux, req)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
resp, md, err := request_FaucetService_Claim_0(rctx, inboundMarshaler, client, req, pathParams)
ctx = runtime.NewServerMetadataContext(ctx, md)
if err != nil {
runtime.HTTPError(ctx, mux, outboundMarshaler, w, req, err)
return
}
forward_FaucetService_Claim_0(ctx, mux, outboundMarshaler, w, req, resp, mux.GetForwardResponseOptions()...)
})
return nil
}
var (
pattern_FaucetService_GetPlayer_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"api", "v1", "faucet", "player"}, "", runtime.AssumeColonVerbOpt(true)))
pattern_FaucetService_Claim_0 = runtime.MustPattern(runtime.NewPattern(1, []int{2, 0, 2, 1, 2, 2, 2, 3}, []string{"api", "v1", "faucet", "player"}, "", runtime.AssumeColonVerbOpt(true)))
)
var (
forward_FaucetService_GetPlayer_0 = runtime.ForwardResponseMessage
forward_FaucetService_Claim_0 = runtime.ForwardResponseMessage
)
syntax = "proto3";
package faucet;
import "google/api/annotations.proto";
import "google/protobuf/timestamp.proto";
import "protoc-gen-swagger/options/annotations.proto";
import "github.com/gogo/protobuf/gogoproto/gogo.proto";
import "gitlab.com/service31/Data/Module/Payment/payment.proto";
// Enable custom Marshal method.
option (gogoproto.marshaler_all) = true;
// Enable custom Unmarshal method.
option (gogoproto.unmarshaler_all) = true;
// Enable custom Size method (Required by Marshal and Unmarshal).
option (gogoproto.sizer_all) = true;
// Enable registration with golang/protobuf for the grpc-gateway.
option (gogoproto.goproto_registration) = true;
// Enable generation of XXX_MessageName methods for grpc-go/status.
option (gogoproto.messagename_all) = true;
option (grpc.gateway.protoc_gen_swagger.options.openapiv2_swagger) = {
info: {
version: "1.0"
}
external_docs: {
url: "https://faucet.service.api.zhironghuang.com"
description: "Faucet gRPC API Doc"
}
schemes: HTTPS
};
message HistoryDTO {
google.protobuf.Timestamp Timestamp = 1;
double Amount = 2;
}
message PlayerDTO {
string EntityID = 1;
payment.CryptoType Type = 2;
uint64 ReferalID = 3;
google.protobuf.Timestamp LastClaim = 11;
uint32 BonusAmountPct = 12;
uint64 ReferalCount = 31;
double ReferalClaimAmount = 32;
repeated HistoryDTO Histories = 51;
}
message EmptyRequest {}
message ClaimRequest{
payment.CryptoType Type = 1;
}
service FaucetService {
rpc GetPlayer(EmptyRequest) returns (PlayerDTO) {
option (google.api.http) = {
get: "/api/v1/faucet/player"
};
}
rpc Claim(ClaimRequest) returns (ClaimRequest) {
option (google.api.http) = {
post: "/api/v1/faucet/player"
body: "*"
};
}
}
\ No newline at end of file
{
"swagger": "2.0",
"info": {
"title": "Module/Faucet/faucet.proto",
"version": "1.0"
},
"schemes": [
"https"
],
"consumes": [
"application/json"
],
"produces": [
"application/json"
],