utils.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package afreeca
  2. import (
  3. "fmt"
  4. "math"
  5. "math/rand"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. "time"
  10. )
  11. const regexUserId = `^(?is)(\w+)(?:\(([0-9]+)\))?$`
  12. func GenerateUID() string {
  13. mask := []string{"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F"}
  14. arr := make([]string, 36)
  15. k := 0
  16. rand.New(rand.NewSource(time.Now().UnixNano()))
  17. for i := 0; i < 8; i++ {
  18. k++
  19. arr[k] = mask[int64(math.Floor(16*rand.Float64()))]
  20. }
  21. for i := 0; i < 3; i++ {
  22. for k := 0; k < 4; k++ {
  23. k++
  24. arr[k] = mask[int64(math.Floor(16*rand.Float64()))]
  25. }
  26. }
  27. hex := fmt.Sprintf("0000000%s",
  28. strings.ToUpper(strconv.FormatInt(time.Now().UnixNano()/int64(time.Millisecond), 16)))
  29. l := len(hex)
  30. hexMask := []byte(hex[l-8 : l])
  31. for i := 0; i < 8; i++ {
  32. k++
  33. arr[k] = string(hexMask[i])
  34. }
  35. for i := 0; i < 4; i++ {
  36. k++
  37. arr[k] = mask[int64(math.Floor(16*rand.Float64()))]
  38. }
  39. return strings.Join(arr, "")
  40. }
  41. func NormalizeUserID(s string) string {
  42. var (
  43. m = regexp.MustCompile(regexUserId).FindStringSubmatch(s)
  44. groups int
  45. userId = strings.TrimSpace(s)
  46. )
  47. if groups = len(m); groups == 0 {
  48. return userId
  49. }
  50. return strings.TrimSpace(m[1])
  51. }