cbase.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. package controllers
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "math/rand"
  9. "os"
  10. "path/filepath"
  11. "reflect"
  12. "regexp"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "time"
  17. "github.com/astaxie/beego"
  18. jsoniter "github.com/json-iterator/go"
  19. "lc/common/util"
  20. )
  21. var json = jsoniter.ConfigCompatibleWithStandardLibrary
  22. var IDGen util.IdWorker
  23. var ErrorUserPassword = errors.New("用户名密码错误")
  24. var ErrorDataUnvalid = errors.New("数据错误")
  25. var (
  26. Success = 0
  27. Failure = 1
  28. )
  29. type RedisConfig struct {
  30. Conn string `json:"conn"`
  31. Password string `json:"password"`
  32. }
  33. // FileDownloadInfo 素材下载
  34. type FileDownloadInfo struct {
  35. ID uint
  36. SourceUrl string
  37. SavaPath string
  38. }
  39. var DownQueue *util.MlQueue
  40. var bjtz *time.Location
  41. var LcFiledir string
  42. var FileBaseUrl string
  43. var BaseUrl string
  44. func init() {
  45. loc, err := time.LoadLocation("Asia/Shanghai")
  46. if err != nil {
  47. bjtz = time.Local
  48. } else {
  49. bjtz = loc
  50. }
  51. IDGen.InitIdWorker(1000, 1)
  52. DownQueue = util.NewQueue(10000)
  53. //LcFiledir, _ = filepath.Abs(filepath.Dir(os.Args[0]))
  54. LcFiledir, _ = os.Getwd()
  55. LcFiledir = LcFiledir + string(filepath.Separator) + "file" + string(filepath.Separator)
  56. BaseUrl = beego.AppConfig.String("baseurl")
  57. FileBaseUrl = BaseUrl + "/file/"
  58. if GetMqttHandler() == nil {
  59. panic("GetMqttHandler错误")
  60. }
  61. go GetEventMgr().Handler()
  62. //go DownloadFile()
  63. }
  64. func GetNextUint64() uint64 {
  65. u64, _ := IDGen.NextId()
  66. return uint64(u64)
  67. }
  68. const (
  69. KcRandKindNum = 0 // 纯数字
  70. KcRandKindLower = 1 // 小写字母
  71. KcRandKindUpper = 2 // 大写字母
  72. KcRandKindAll = 3 // 数字、大小写字母
  73. )
  74. // Krand 随机字符串
  75. func Krand(size int, kind int) []byte {
  76. ikind, kinds, result := kind, [][]int{[]int{10, 48}, []int{26, 97}, []int{26, 65}}, make([]byte, size)
  77. isAll := kind > 2 || kind < 0
  78. rand.Seed(time.Now().UnixNano())
  79. for i := 0; i < size; i++ {
  80. if isAll {
  81. ikind = rand.Intn(3)
  82. }
  83. scope, base := kinds[ikind][0], kinds[ikind][1]
  84. result[i] = uint8(base + rand.Intn(scope))
  85. }
  86. return result
  87. }
  88. type BaseController struct {
  89. beego.Controller
  90. UserName string
  91. Password string
  92. }
  93. type BaseResponse struct {
  94. Code int `json:"code"`
  95. Message string `json:"msg"`
  96. Data interface{} `json:"data,omitempty"`
  97. }
  98. func LcValidation(user string, password string) (uint, string, error) {
  99. list, err := redisCltRawdata.HMGet(user, "id", "code", "password").Result()
  100. if err != nil {
  101. beego.Error("LcValidation发生错误:", err)
  102. return 0, "", err
  103. } else {
  104. if list[0] == nil || list[1] == nil || list[2] == nil {
  105. beego.Error("LcValidation从redis返回的数据不完整:", list)
  106. return 0, "", ErrorDataUnvalid
  107. }
  108. if list[2].(string) != password {
  109. beego.Error("用户名密码错误,用户名:", user, ",密码:", password)
  110. return 0, "", ErrorUserPassword
  111. }
  112. id, err := strconv.Atoi(list[0].(string))
  113. if err != nil {
  114. beego.Error("LcValidation发生ID转换错误:", list[0].(string))
  115. return 0, "", err
  116. }
  117. //if err := redisCltRawdata.HSet(LED_STATUS_PREFIX+list[0].(string), TIME, util.MlNow().Format("2006-01-02 15:04:05")).Err(); err != nil {
  118. // beego.Error("CheckLogin缓存时间发生错误:", err)
  119. //}
  120. return uint(id), list[1].(string), nil
  121. }
  122. }
  123. func (c *BaseController) Prepare() {
  124. username, password, ok := c.Ctx.Request.BasicAuth()
  125. if ok {
  126. c.UserName = username
  127. c.Password = password
  128. }
  129. }
  130. func (c *BaseController) Response(Code int, Message string, Data interface{}) {
  131. var respObj BaseResponse
  132. respObj.Code = Code
  133. respObj.Message = Message
  134. respObj.Data = Data
  135. c.Data["json"] = respObj
  136. c.ServeJSON()
  137. }
  138. type ErrorController struct {
  139. beego.Controller
  140. }
  141. func (o *ErrorController) Error404() {
  142. var obj BaseResponse
  143. obj.Code = 404
  144. obj.Message = "资源不存在,请检查URL"
  145. obj.Data = "Resouce Not Found"
  146. o.Data["json"] = obj
  147. o.ServeJSON()
  148. }
  149. func (o *ErrorController) Error501() {
  150. var obj BaseResponse
  151. obj.Code = 501
  152. obj.Message = "API内部错误,请联系管理员"
  153. obj.Data = "Server Error"
  154. o.Data["json"] = obj
  155. o.ServeJSON()
  156. }
  157. func GetDeviceSubId(gwid string, comid int, rtuid string) string {
  158. id := gwid + "_" + strconv.Itoa(comid) + "_" + rtuid
  159. return id
  160. }
  161. func CheckMD5(reader io.Reader, strmd5 string) bool {
  162. if strmd5 == "" {
  163. return true
  164. }
  165. md5hash := md5.New()
  166. _, err := io.Copy(md5hash, reader)
  167. if err != nil {
  168. return true
  169. }
  170. strmd5_ := strings.ToLower(hex.EncodeToString(md5hash.Sum(nil)))
  171. if strmd5 != strmd5_ {
  172. return false
  173. }
  174. return true
  175. }
  176. func GetRelationids(js string) string {
  177. reg := regexp.MustCompile(`dat\w{16,}`)
  178. s := reg.FindAllString(js, -1)
  179. if len(s) > 0 {
  180. if len(s) > 1 {
  181. sort.Strings(s)
  182. ss := Duplicate(s)
  183. return strings.Replace(strings.Trim(fmt.Sprint(ss), "[]"), " ", ";", -1)
  184. } else {
  185. return s[0]
  186. }
  187. }
  188. return ""
  189. }
  190. func Duplicate(a interface{}) (ret []interface{}) {
  191. va := reflect.ValueOf(a)
  192. for i := 0; i < va.Len(); i++ {
  193. if i > 0 && reflect.DeepEqual(va.Index(i-1).Interface(), va.Index(i).Interface()) {
  194. continue
  195. }
  196. ret = append(ret, va.Index(i).Interface())
  197. }
  198. return ret
  199. }