cbase.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. for i := 0; i < size; i++ {
  79. if isAll {
  80. ikind = rand.Intn(3)
  81. }
  82. scope, base := kinds[ikind][0], kinds[ikind][1]
  83. result[i] = uint8(base + rand.Intn(scope))
  84. }
  85. return result
  86. }
  87. type BaseController struct {
  88. beego.Controller
  89. UserName string
  90. Password string
  91. }
  92. type BaseResponse struct {
  93. Code int `json:"code"`
  94. Message string `json:"msg"`
  95. Data interface{} `json:"data,omitempty"`
  96. }
  97. func LcValidation(user string, password string) (uint, string, error) {
  98. list, err := redisCltRawdata.HMGet(user, "id", "code", "password").Result()
  99. if err != nil {
  100. beego.Error("LcValidation发生错误:", err)
  101. return 0, "", err
  102. } else {
  103. if list[0] == nil || list[1] == nil || list[2] == nil {
  104. beego.Error("LcValidation从redis返回的数据不完整:", list)
  105. return 0, "", ErrorDataUnvalid
  106. }
  107. if list[2].(string) != password {
  108. beego.Error("用户名密码错误,用户名:", user, ",密码:", password)
  109. return 0, "", ErrorUserPassword
  110. }
  111. id, err := strconv.Atoi(list[0].(string))
  112. if err != nil {
  113. beego.Error("LcValidation发生ID转换错误:", list[0].(string))
  114. return 0, "", err
  115. }
  116. //if err := redisCltRawdata.HSet(LED_STATUS_PREFIX+list[0].(string), TIME, util.MlNow().Format("2006-01-02 15:04:05")).Err(); err != nil {
  117. // beego.Error("CheckLogin缓存时间发生错误:", err)
  118. //}
  119. return uint(id), list[1].(string), nil
  120. }
  121. }
  122. func (c *BaseController) Prepare() {
  123. username, password, ok := c.Ctx.Request.BasicAuth()
  124. if ok {
  125. c.UserName = username
  126. c.Password = password
  127. }
  128. }
  129. func (c *BaseController) Response(Code int, Message string, Data interface{}) {
  130. var respObj BaseResponse
  131. respObj.Code = Code
  132. respObj.Message = Message
  133. respObj.Data = Data
  134. c.Data["json"] = respObj
  135. c.ServeJSON()
  136. }
  137. type ErrorController struct {
  138. beego.Controller
  139. }
  140. func (o *ErrorController) Error404() {
  141. var obj BaseResponse
  142. obj.Code = 404
  143. obj.Message = "资源不存在,请检查URL"
  144. obj.Data = "Resouce Not Found"
  145. o.Data["json"] = obj
  146. o.ServeJSON()
  147. }
  148. func (o *ErrorController) Error501() {
  149. var obj BaseResponse
  150. obj.Code = 501
  151. obj.Message = "API内部错误,请联系管理员"
  152. obj.Data = "Server Error"
  153. o.Data["json"] = obj
  154. o.ServeJSON()
  155. }
  156. func GetDeviceSubId(gwid string, comid int, rtuid string) string {
  157. id := gwid + "_" + strconv.Itoa(comid) + "_" + rtuid
  158. return id
  159. }
  160. func CheckMD5(reader io.Reader, strmd5 string) bool {
  161. if strmd5 == "" {
  162. return true
  163. }
  164. md5hash := md5.New()
  165. _, err := io.Copy(md5hash, reader)
  166. if err != nil {
  167. return true
  168. }
  169. strmd5_ := strings.ToLower(hex.EncodeToString(md5hash.Sum(nil)))
  170. if strmd5 != strmd5_ {
  171. return false
  172. }
  173. return true
  174. }
  175. func GetRelationids(js string) string {
  176. reg := regexp.MustCompile(`dat\w{16,}`)
  177. s := reg.FindAllString(js, -1)
  178. if len(s) > 0 {
  179. if len(s) > 1 {
  180. sort.Strings(s)
  181. ss := Duplicate(s)
  182. return strings.Replace(strings.Trim(fmt.Sprint(ss), "[]"), " ", ";", -1)
  183. } else {
  184. return s[0]
  185. }
  186. }
  187. return ""
  188. }
  189. func Duplicate(a interface{}) (ret []interface{}) {
  190. va := reflect.ValueOf(a)
  191. for i := 0; i < va.Len(); i++ {
  192. if i > 0 && reflect.DeepEqual(va.Index(i-1).Interface(), va.Index(i).Interface()) {
  193. continue
  194. }
  195. ret = append(ret, va.Index(i).Interface())
  196. }
  197. return ret
  198. }