Create & Init Project...

This commit is contained in:
2019-04-22 18:49:16 +08:00
commit fc4fa37393
25440 changed files with 4054998 additions and 0 deletions

View File

@@ -0,0 +1,65 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = ["service_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/report-click/conf:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"err_report.go",
"ip.go",
"service.go",
],
importpath = "go-common/app/interface/main/report-click/service",
tags = ["automanaged"],
deps = [
"//app/interface/main/history/model:go_default_library",
"//app/interface/main/history/rpc/client:go_default_library",
"//app/interface/main/report-click/conf:go_default_library",
"//app/interface/main/report-click/dao:go_default_library",
"//app/interface/main/report-click/model:go_default_library",
"//app/interface/main/report-click/service/crypto/aes:go_default_library",
"//app/interface/main/report-click/service/crypto/padding:go_default_library",
"//app/service/main/account/model:go_default_library",
"//app/service/main/account/rpc/client:go_default_library",
"//library/ecode:go_default_library",
"//library/log:go_default_library",
"//library/net/metadata:go_default_library",
"//library/stat/prom:go_default_library",
"//library/sync/pipeline/fanout:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [
":package-srcs",
"//app/interface/main/report-click/service/crypto/aes:all-srcs",
"//app/interface/main/report-click/service/crypto/cipher:all-srcs",
"//app/interface/main/report-click/service/crypto/padding:all-srcs",
],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,44 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = ["aes_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/report-click/service/crypto/padding:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = ["aes.go"],
importpath = "go-common/app/interface/main/report-click/service/crypto/aes",
tags = ["automanaged"],
deps = [
"//app/interface/main/report-click/service/crypto/cipher:go_default_library",
"//app/interface/main/report-click/service/crypto/padding:go_default_library",
],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,103 @@
package aes
import (
iaes "crypto/aes"
icipher "crypto/cipher"
"errors"
"go-common/app/interface/main/report-click/service/crypto/cipher"
"go-common/app/interface/main/report-click/service/crypto/padding"
)
var (
ErrAesBlockSize = errors.New("plaintext is not a multiple of the block size")
ErrAesSrcSize = errors.New("ciphertext too short")
ErrAesIVSize = errors.New("iv size is not a block size")
)
// ECBEncrypt aes ecb encrypt.
func ECBEncrypt(src, key []byte, p padding.Padding) ([]byte, error) {
if p == nil {
if len(src) < iaes.BlockSize || len(src)%iaes.BlockSize != 0 {
return nil, ErrAesBlockSize
}
} else {
src = p.Padding(src, iaes.BlockSize)
}
b, err := iaes.NewCipher(key)
if err != nil {
return nil, err
}
mode := cipher.NewECBEncrypter(b)
encryptText := make([]byte, len(src))
mode.CryptBlocks(encryptText, src)
return encryptText, nil
}
// ECBDecrypt aes ecb decrypt.
func ECBDecrypt(src, key []byte, p padding.Padding) ([]byte, error) {
if len(src) < iaes.BlockSize || len(src)%iaes.BlockSize != 0 {
return nil, ErrAesSrcSize
}
b, err := iaes.NewCipher(key)
if err != nil {
return nil, err
}
mode := cipher.NewECBDecrypter(b)
decryptText := make([]byte, len(src))
mode.CryptBlocks(decryptText, src)
if p == nil {
return decryptText, nil
} else {
return p.Unpadding(decryptText, iaes.BlockSize)
}
}
// CBCEncrypt aes cbc encrypt.
func CBCEncrypt(src, key, iv []byte, p padding.Padding) ([]byte, error) {
// check iv
if len(iv) != iaes.BlockSize {
return nil, ErrAesIVSize
}
if p == nil {
// if no padding check src
if len(src) < iaes.BlockSize || len(src)%iaes.BlockSize != 0 {
return nil, ErrAesSrcSize
}
} else {
// padding
src = p.Padding(src, iaes.BlockSize)
}
block, err := iaes.NewCipher(key)
if err != nil {
return nil, err
}
mode := icipher.NewCBCEncrypter(block, iv)
encryptText := make([]byte, len(src))
mode.CryptBlocks(encryptText, src)
return encryptText, nil
}
// CBCDecrypt aes cbc decrypt.
func CBCDecrypt(src, key, iv []byte, p padding.Padding) ([]byte, error) {
// check src
if len(src) < iaes.BlockSize || len(src)%iaes.BlockSize != 0 {
return nil, ErrAesSrcSize
}
// check iv
if len(iv) != iaes.BlockSize {
return nil, ErrAesIVSize
}
block, err := iaes.NewCipher(key)
if err != nil {
return nil, err
}
mode := icipher.NewCBCDecrypter(block, iv)
decryptText := make([]byte, len(src))
mode.CryptBlocks(decryptText, src)
if p == nil {
return decryptText, nil
} else {
return p.Unpadding(decryptText, iaes.BlockSize)
}
}

View File

@@ -0,0 +1,24 @@
package aes
import (
"testing"
"go-common/app/interface/main/report-click/service/crypto/padding"
. "github.com/smartystreets/goconvey/convey"
)
func TestAES(t *testing.T) {
var (
aesKey = ""
aesIv = ""
bs = []byte("this is test massage ")
)
Convey("aes test ", t, func() {
bs, _ = CBCDecrypt(bs, []byte(aesKey), []byte(aesIv), padding.PKCS5)
ECBDecrypt(bs, []byte(aesKey), padding.PKCS5)
bs = []byte("this is test massage ")
bs, _ = CBCEncrypt(bs, []byte(aesKey), []byte(aesIv), padding.PKCS5)
CBCDecrypt(bs, []byte(aesKey), []byte(aesIv), padding.PKCS5)
})
}

View File

@@ -0,0 +1,40 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = ["ecb_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/report-click/service/crypto/padding:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = ["ecb.go"],
importpath = "go-common/app/interface/main/report-click/service/crypto/cipher",
tags = ["automanaged"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,76 @@
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Electronic Code Book (ECB) mode.
// ECB provides confidentiality by assigning a fixed ciphertext block to each
// plaintext block.
// See NIST SP 800-38A, pp 08-09
package cipher
import (
"crypto/cipher"
)
type ecb struct {
b cipher.Block
blockSize int
}
func newECB(b cipher.Block) *ecb {
return &ecb{
b: b,
blockSize: b.BlockSize(),
}
}
type ecbEncrypter ecb
// NewECBEncrypter returns a BlockMode which encrypts in electronic code book
// mode, using the given Block.
func NewECBEncrypter(b cipher.Block) cipher.BlockMode {
return (*ecbEncrypter)(newECB(b))
}
func (x *ecbEncrypter) BlockSize() int { return x.blockSize }
func (x *ecbEncrypter) CryptBlocks(dst, src []byte) {
if len(src)%x.blockSize != 0 {
panic("crypto/cipher: input not full blocks")
}
if len(dst) < len(src) {
panic("crypto/cipher: output smaller than input")
}
for len(src) > 0 {
x.b.Encrypt(dst, src[:x.blockSize])
src = src[x.blockSize:]
dst = dst[x.blockSize:]
}
}
type ecbDecrypter ecb
// NewECBDecrypter returns a BlockMode which decrypts in electronic code book
// mode, using the given Block.
func NewECBDecrypter(b cipher.Block) cipher.BlockMode {
return (*ecbDecrypter)(newECB(b))
}
func (x *ecbDecrypter) BlockSize() int { return x.blockSize }
func (x *ecbDecrypter) CryptBlocks(dst, src []byte) {
if len(src)%x.blockSize != 0 {
panic("crypto/cipher: input not full blocks")
}
if len(dst) < len(src) {
panic("crypto/cipher: output smaller than input")
}
for len(src) > 0 {
x.b.Decrypt(dst, src[:x.blockSize])
src = src[x.blockSize:]
dst = dst[x.blockSize:]
}
}

View File

@@ -0,0 +1,29 @@
package cipher
import (
iaes "crypto/aes"
"testing"
"go-common/app/interface/main/report-click/service/crypto/padding"
. "github.com/smartystreets/goconvey/convey"
)
func TestECB(t *testing.T) {
var (
aesKey = "903ef9925be1300f843b41df2ca55410"
bs = []byte("this is test massage ")
)
Convey("cipher test ", t, func() {
var p = padding.PKCS5
bs = p.Padding(bs, iaes.BlockSize)
b, _ := iaes.NewCipher([]byte(aesKey))
ecbe := NewECBEncrypter(b)
encryptText := make([]byte, len(bs))
ecbe.CryptBlocks(encryptText, bs)
ecbd := NewECBDecrypter(b)
decryptText := make([]byte, len(bs))
ecbd.CryptBlocks(decryptText, bs)
p.Unpadding(bs, iaes.BlockSize)
})
}

View File

@@ -0,0 +1,43 @@
package(default_visibility = ["//visibility:public"])
load(
"@io_bazel_rules_go//go:def.bzl",
"go_test",
"go_library",
)
go_test(
name = "go_default_test",
srcs = ["pkcs5_test.go"],
embed = [":go_default_library"],
rundir = ".",
tags = ["automanaged"],
deps = [
"//app/interface/main/report-click/service/crypto/cipher:go_default_library",
"//vendor/github.com/smartystreets/goconvey/convey:go_default_library",
],
)
go_library(
name = "go_default_library",
srcs = [
"padding.go",
"pkcs5.go",
],
importpath = "go-common/app/interface/main/report-click/service/crypto/padding",
tags = ["automanaged"],
)
filegroup(
name = "package-srcs",
srcs = glob(["**"]),
tags = ["automanaged"],
visibility = ["//visibility:private"],
)
filegroup(
name = "all-srcs",
srcs = [":package-srcs"],
tags = ["automanaged"],
visibility = ["//visibility:public"],
)

View File

@@ -0,0 +1,15 @@
package padding
import (
"errors"
)
var (
ErrPaddingSize = errors.New("pkcs5 padding size error")
)
// Padding is interface used for crypto.
type Padding interface {
Padding(src []byte, blockSize int) []byte
Unpadding(src []byte, blockSize int) ([]byte, error)
}

View File

@@ -0,0 +1,30 @@
package padding
var (
PKCS5 = &pkcs5{}
)
// pkcs5Padding is a pkcs5 padding struct.
type pkcs5 struct{}
// Padding implements the Padding interface Padding method.
func (p *pkcs5) Padding(src []byte, blockSize int) []byte {
srcLen := len(src)
padLen := byte(blockSize - (srcLen % blockSize))
pd := make([]byte, srcLen+int(padLen))
copy(pd, src)
for i := srcLen; i < len(pd); i++ {
pd[i] = padLen
}
return pd
}
// Unpadding implements the Padding interface Unpadding method.
func (p *pkcs5) Unpadding(src []byte, blockSize int) ([]byte, error) {
srcLen := len(src)
paddingLen := int(src[srcLen-1])
if paddingLen >= srcLen || paddingLen > blockSize {
return nil, ErrPaddingSize
}
return src[:srcLen-paddingLen], nil
}

View File

@@ -0,0 +1,29 @@
package padding
import (
iaes "crypto/aes"
"testing"
"go-common/app/interface/main/report-click/service/crypto/cipher"
. "github.com/smartystreets/goconvey/convey"
)
func TestECB(t *testing.T) {
var (
aesKey = "903ef9925be1300f843b41df2ca55410"
bs = []byte("this is test massage ")
)
Convey("cipher test ", t, func() {
var p = PKCS5
bs = p.Padding(bs, iaes.BlockSize)
b, _ := iaes.NewCipher([]byte(aesKey))
ecbe := cipher.NewECBEncrypter(b)
encryptText := make([]byte, len(bs))
ecbe.CryptBlocks(encryptText, bs)
ecbd := cipher.NewECBDecrypter(b)
decryptText := make([]byte, len(bs))
ecbd.CryptBlocks(decryptText, bs)
p.Unpadding(bs, iaes.BlockSize)
})
}

View File

@@ -0,0 +1,17 @@
package service
import (
"context"
"go-common/app/interface/main/report-click/model"
)
// ErrReport reports the failures of calling the api "heartbeat/mobile"
func (s *Service) ErrReport(ctx context.Context, req *model.ErrReport) {
s.promErr.Incr(req.ToProm())
}
// SuccReport reports the success of calling the api "heartbeat/mobile"
func (s *Service) SuccReport(ctx context.Context, req *model.SuccReport) {
s.promInfo.Incr(req.ToProm())
}

View File

@@ -0,0 +1,137 @@
package service
import (
"fmt"
"math"
"net"
)
const sixtyTwo uint64 = 62
func encode(num uint64) string {
var numStr string
for num != 0 {
r := num % sixtyTwo
if r <= 9 {
numStr = string(byte(r)+48) + numStr
} else if r <= 35 {
numStr = string(byte(r)+87) + numStr
} else {
numStr = string(byte(r)+29) + numStr
}
num = num / sixtyTwo
}
return numStr
}
func decode(bs []byte) uint64 {
f := 0.0
l := len(bs) - 1
for _, v := range bs {
if v >= 97 {
v -= 87
} else if v >= 65 {
v -= 29
} else {
v -= 48
}
f = f + float64(v)*math.Pow(float64(sixtyTwo), float64(l))
l = l - 1
}
return uint64(f)
}
// ntoIPv6 conver uint32 to ip addr.
func ntoIPv6(sip []string) string {
if len(sip) != 3 {
return ""
}
ip := make(net.IP, net.IPv6len)
sum := decode([]byte(sip[0]))
ip[0] = byte((sum >> 40) & 0xFF)
ip[1] = byte((sum >> 32) & 0xFF)
ip[2] = byte((sum >> 24) & 0xFF)
ip[3] = byte((sum >> 16) & 0xFF)
ip[4] = byte((sum >> 8) & 0xFF)
ip[5] = byte(sum & 0xFF)
sum = decode([]byte(sip[1]))
ip[6] = byte((sum >> 40) & 0xFF)
ip[7] = byte((sum >> 32) & 0xFF)
ip[8] = byte((sum >> 24) & 0xFF)
ip[9] = byte((sum >> 16) & 0xFF)
ip[10] = byte((sum >> 8) & 0xFF)
ip[11] = byte(sum & 0xFF)
sum = decode([]byte(sip[2]))
ip[12] = byte((sum >> 24) & 0xFF)
ip[13] = byte((sum >> 16) & 0xFF)
ip[14] = byte((sum >> 8) & 0xFF)
ip[15] = byte(sum & 0xFF)
return ip.String()
}
// ipv6AtoN conver ip addr to uint32.
func ipv6AtoN(ip net.IP) (sip string) {
ip = ip.To16()
if ip == nil {
return
}
sum := uint64(ip[0]) << 40
sum += uint64(ip[1]) << 32
sum += uint64(ip[2]) << 24
sum += uint64(ip[3]) << 16
sum += uint64(ip[4]) << 8
sum += uint64(ip[5])
sip = encode(sum)
sum = uint64(ip[6]) << 40
sum += uint64(ip[7]) << 32
sum += uint64(ip[8]) << 24
sum += uint64(ip[9]) << 16
sum += uint64(ip[10]) << 8
sum += uint64(ip[11])
sip = sip + ":" + encode(sum)
sum = uint64(ip[12]) << 24
sum += uint64(ip[13]) << 16
sum += uint64(ip[14]) << 8
sum += uint64(ip[15])
sip = sip + ":" + encode(sum)
fmt.Println(sip, "len:", len(sip))
return
}
// netAtoN conver ipv4 addr to uint32.
func netAtoN(ip net.IP) (sum uint32) {
ip = ip.To4()
if ip == nil {
return
}
sum += uint32(ip[0]) << 24
sum += uint32(ip[1]) << 16
sum += uint32(ip[2]) << 8
sum += uint32(ip[3])
return sum
}
// netNtoA conver uint32 to ipv4 addr.
func netNtoA(sum uint32) string {
ip := make(net.IP, net.IPv4len)
ip[0] = byte((sum >> 24) & 0xFF)
ip[1] = byte((sum >> 16) & 0xFF)
ip[2] = byte((sum >> 8) & 0xFF)
ip[3] = byte(sum & 0xFF)
return ip.String()
}
func parseIP(s string) (net.IP, bool) {
for i := 0; i < len(s); i++ {
switch s[i] {
case '.':
return net.ParseIP(s), true
case ':':
return net.ParseIP(s), false
}
}
return nil, false
}

View File

@@ -0,0 +1,260 @@
package service
import (
"bytes"
"context"
"crypto/md5"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"fmt"
"net/url"
"strconv"
"strings"
"time"
hmdl "go-common/app/interface/main/history/model"
hrpc "go-common/app/interface/main/history/rpc/client"
"go-common/app/interface/main/report-click/conf"
"go-common/app/interface/main/report-click/dao"
"go-common/app/interface/main/report-click/service/crypto/aes"
"go-common/app/interface/main/report-click/service/crypto/padding"
accmdl "go-common/app/service/main/account/model"
accrpc "go-common/app/service/main/account/rpc/client"
"go-common/library/ecode"
"go-common/library/log"
"go-common/library/net/metadata"
"go-common/library/stat/prom"
"go-common/library/sync/pipeline/fanout"
)
// 0 1 2 3 4 5 6 7 8 9 : <-> d w o i k p s x m q l
// 48 49 50 51 52 53 54 55 56 57 58 <-> 100 119 111 105 107 112 115 120 109 113 108
var ecKeys = map[rune]rune{
48: 119,
49: 111,
50: 105,
51: 107,
52: 112,
53: 115,
54: 120,
55: 109,
56: 113,
57: 108,
58: 100,
119: 48,
111: 49,
105: 50,
107: 51,
112: 52,
115: 53,
120: 54,
109: 55,
113: 56,
108: 57,
100: 58,
}
// Service service struct info.
type Service struct {
c *conf.Config
d *dao.Dao
accRPC *accrpc.Service3
hisRPC *hrpc.Service
cache *fanout.Fanout
promErr *prom.Prom
promInfo *prom.Prom
}
// New service.
func New(c *conf.Config) (s *Service) {
s = &Service{
c: c,
d: dao.New(c),
accRPC: accrpc.New3(c.AccRPC),
hisRPC: hrpc.New(c.HisRPC),
cache: fanout.New("cache", fanout.Worker(1), fanout.Buffer(1024)),
promErr: prom.BusinessErrCount,
promInfo: prom.BusinessInfoCount,
}
return
}
// FlashSigned flash Signed.
func (s *Service) FlashSigned(params url.Values, secret string, now time.Time) (err error) {
st := params.Get("stime")
stime, err := strconv.ParseInt(st, 10, 64)
if err != nil {
err = ecode.ClickQueryFormatErr
return
}
if now.Unix()-stime > 60 {
err = ecode.ClickServerTimeout
return
}
sign := params.Get("sign")
params.Del("sign")
mh := md5.Sum([]byte(strings.ToLower(params.Encode()) + secret))
if hex.EncodeToString(mh[:]) != sign {
err = ecode.ClickQuerySignErr
}
return
}
// Decrypt decrypt bytes by aes key and iv.
func (s *Service) Decrypt(src []byte, aesKey, aesIv string) (res []byte, err error) {
res, err = aes.CBCDecrypt(src, []byte(aesKey), []byte(aesIv), padding.PKCS5)
if err != nil {
log.Error("aes.CBCDecrypt(%s, %s, %s) error(%v)", base64.StdEncoding.EncodeToString(src), s.c.Click.AesKey, s.c.Click.AesIv, err)
err = ecode.ClickAesDecryptErr
}
return
}
// Verify verify bytes from post body.
func (s *Service) Verify(src []byte, aesSalt string, now time.Time) (p url.Values, err error) {
p, err = url.ParseQuery(string(src))
if err != nil {
err = ecode.ClickQueryFormatErr
return
}
// check server time
st := p.Get("stime")
stime, err := strconv.ParseInt(st, 10, 64)
if err != nil {
err = ecode.ClickQueryFormatErr
return
}
if now.Unix()-stime > 60*3 {
err = ecode.ClickServerTimeout
return
}
// verify sign
sign := p.Get("sign")
sbs, err := hex.DecodeString(sign)
if err != nil {
log.Error("hex.DecodeString(%s) error(%v)", sign, err)
err = ecode.ClickQuerySignErr
return
}
p.Del("sign")
// sha 256
h := sha256.New()
// h.Write([]byte(strings.ToLower(p.Encode())))
h.Write([]byte(p.Encode()))
h.Write([]byte(aesSalt))
bs := h.Sum(nil)
// bytes queal
if !bytes.Equal(sbs, bs) {
log.Error("hmac.Equal(%s, %x) params(%s) not equal", sign, bs, p.Encode())
err = ecode.ClickHmacSignErr
}
return
}
// Play send play count to kafka.
func (s *Service) Play(c context.Context, plat, aid, cid, part, mid, level, ftime, stime, did, ip, agent, buvid, cookieSid, refer, typeID, subType, sid, epid, playMode, platform, device, mobiAapp, autoPlay, session string) {
if aid == "" || aid == "0" {
return
}
m, errP := strconv.ParseInt(mid, 10, 64)
if errP != nil {
log.Warn("strconv.ParseInt(%s) error(%v)", mid, errP)
mid = "0"
}
if m != 0 {
arg := &accmdl.ArgMid{Mid: m}
res, err := s.accRPC.Card3(c, arg)
if err != nil {
log.Error("s.accRPC.UserInfo() error(%v)", err)
return
}
if res.Silence == 1 {
log.Warn("user mid(%d) spacesta(%d) too lower", m, res.Silence)
return
}
level = fmt.Sprintf("%d", res.Level)
}
s.cache.Do(c, func(ctx context.Context) {
s.d.Play(ctx, plat, aid, cid, part, mid, level, ftime, stime, did, ip, agent, buvid, cookieSid, refer, typeID, subType, sid, epid, playMode, platform, device, mobiAapp, autoPlay, session)
})
}
// GenDid gen did.
func (s *Service) GenDid(ip string, now time.Time) string {
var src string
ft := now.Unix() - int64(now.Second())
uip, ok := parseIP(ip)
if uip == nil {
return ""
}
if ok {
src = fmt.Sprintf("%d:%d", netAtoN(uip), ft)
return myEncryptDecrypt(src)
}
fs := encode(uint64(ft))
ipRes := ipv6AtoN(uip)
if len(ipRes) > 25 { // total 32, 25 for ip, 1 for :, 6 for ftime
ipRes = ipRes[:25]
}
return fmt.Sprintf("%s:%s", ipRes, fs)
}
// CheckDid check did.
func (s *Service) CheckDid(did string) (ip, ft string) {
params := strings.Split(did, ":")
if len(params) == 4 {
log.Warn("report click did:%s", did)
return ntoIPv6(params[:3]), fmt.Sprintf("%d", decode([]byte(params[3])))
}
dst := myEncryptDecrypt(did)
params = strings.Split(dst, ":")
if len(params) != 2 {
return
}
ipInt, _ := strconv.ParseInt(params[0], 10, 64)
ip = netNtoA(uint32(ipInt))
ft = params[1]
return
}
func myEncryptDecrypt(src string) (dst string) {
var tmp []rune
for _, k := range src {
if _, ok := ecKeys[k]; !ok {
return ""
}
tmp = append(tmp, ecKeys[k])
}
dst = string(tmp)
return
}
// Report report to history.
func (s *Service) Report(c context.Context, proStr, cidStr, tpStr, subType, realtimeStr, aidStr, midstr, sidStr, epidStr, dtStr, tsStr string) (err error) {
var (
tp, stp, dt int
)
if tp, err = strconv.Atoi(tpStr); err != nil {
log.Warn("Report type:%s", tpStr)
}
stp, _ = strconv.Atoi(subType)
mid, _ := strconv.ParseInt(midstr, 10, 64)
aid, _ := strconv.ParseInt(aidStr, 10, 64)
sid, _ := strconv.ParseInt(sidStr, 10, 64)
epid, _ := strconv.ParseInt(epidStr, 10, 64)
cid, _ := strconv.ParseInt(cidStr, 10, 64)
if aid == 0 && cid == 0 {
return ecode.RequestErr
}
pro, _ := strconv.ParseInt(proStr, 10, 64)
realtime, _ := strconv.ParseInt(realtimeStr, 10, 64)
if dt, err = strconv.Atoi(dtStr); err != nil {
dt = 2
}
ip := metadata.String(c, metadata.RemoteIP)
ts, _ := strconv.ParseInt(tsStr, 10, 64)
history := &hmdl.History{Aid: aid, Sid: sid, Epid: epid, TP: int8(tp), STP: int8(stp), Cid: cid, DT: int8(dt), Pro: pro, Unix: ts}
arg := &hmdl.ArgHistory{Mid: mid, Realtime: realtime, RealIP: ip, History: history}
return s.hisRPC.Add(c, arg)
}

View File

@@ -0,0 +1,55 @@
package service
import (
"context"
"flag"
"path/filepath"
"testing"
"time"
"go-common/app/interface/main/report-click/conf"
. "github.com/smartystreets/goconvey/convey"
)
var svr *Service
func init() {
flag.Parse()
dir, _ := filepath.Abs("../cmd/report-click.toml")
flag.Set("conf", dir)
conf.Init()
svr = New(conf.Conf)
}
func TestReport(t *testing.T) {
var (
c = context.Background()
err error
aid = "11159485"
cid = "18464413"
mid = "35152246"
playedTime = "0"
realtime = "0"
tp = "3"
dt = "2"
bs = []byte("this is test massage ")
)
Convey("Decrypt Verify err should return nil", t, func() {
bs, _ = svr.Decrypt(bs, conf.Conf.Click.AesKey, conf.Conf.Click.AesIv)
svr.Verify(bs, conf.Conf.Click.AesSalt, time.Now())
})
Convey("Report err should return nil", t, func() {
err = svr.Report(c, playedTime, cid, tp, "", realtime, aid, mid, "", "", dt, "1516695880")
So(err, ShouldBeNil)
})
Convey("CheckDid err should return nil", t, func() {
svr.CheckDid("1516695880")
})
Convey("GenDid err should return nil", t, func() {
svr.GenDid("127.0.0.1", time.Now())
})
Convey("Play err should return nil", t, func() {
svr.Play(c, "web", "128546345", "12345", "", "14771787", "1", "", "", "", "127.0.0.1", "2", "1", "1212", "", "1", "3", "2", "4", "", "", "", "", "", "")
})
}