utils.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. package common
  2. import (
  3. "bytes"
  4. "context"
  5. crand "crypto/rand"
  6. "encoding/base64"
  7. "encoding/json"
  8. "fmt"
  9. "html/template"
  10. "io"
  11. "log"
  12. "math/big"
  13. "math/rand"
  14. "net"
  15. "os"
  16. "os/exec"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "github.com/google/uuid"
  22. "github.com/pkg/errors"
  23. )
  24. func OpenBrowser(url string) {
  25. var err error
  26. switch runtime.GOOS {
  27. case "linux":
  28. err = exec.Command("xdg-open", url).Start()
  29. case "windows":
  30. err = exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
  31. case "darwin":
  32. err = exec.Command("open", url).Start()
  33. }
  34. if err != nil {
  35. log.Println(err)
  36. }
  37. }
  38. func GetIp() (ip string) {
  39. ips, err := net.InterfaceAddrs()
  40. if err != nil {
  41. log.Println(err)
  42. return ip
  43. }
  44. for _, a := range ips {
  45. if ipNet, ok := a.(*net.IPNet); ok && !ipNet.IP.IsLoopback() {
  46. if ipNet.IP.To4() != nil {
  47. ip = ipNet.IP.String()
  48. if strings.HasPrefix(ip, "10") {
  49. return
  50. }
  51. if strings.HasPrefix(ip, "172") {
  52. return
  53. }
  54. if strings.HasPrefix(ip, "192.168") {
  55. return
  56. }
  57. ip = ""
  58. }
  59. }
  60. }
  61. return
  62. }
  63. var sizeKB = 1024
  64. var sizeMB = sizeKB * 1024
  65. var sizeGB = sizeMB * 1024
  66. func Bytes2Size(num int64) string {
  67. numStr := ""
  68. unit := "B"
  69. if num/int64(sizeGB) > 1 {
  70. numStr = fmt.Sprintf("%.2f", float64(num)/float64(sizeGB))
  71. unit = "GB"
  72. } else if num/int64(sizeMB) > 1 {
  73. numStr = fmt.Sprintf("%d", int(float64(num)/float64(sizeMB)))
  74. unit = "MB"
  75. } else if num/int64(sizeKB) > 1 {
  76. numStr = fmt.Sprintf("%d", int(float64(num)/float64(sizeKB)))
  77. unit = "KB"
  78. } else {
  79. numStr = fmt.Sprintf("%d", num)
  80. }
  81. return numStr + " " + unit
  82. }
  83. func Seconds2Time(num int) (time string) {
  84. if num/31104000 > 0 {
  85. time += strconv.Itoa(num/31104000) + " 年 "
  86. num %= 31104000
  87. }
  88. if num/2592000 > 0 {
  89. time += strconv.Itoa(num/2592000) + " 个月 "
  90. num %= 2592000
  91. }
  92. if num/86400 > 0 {
  93. time += strconv.Itoa(num/86400) + " 天 "
  94. num %= 86400
  95. }
  96. if num/3600 > 0 {
  97. time += strconv.Itoa(num/3600) + " 小时 "
  98. num %= 3600
  99. }
  100. if num/60 > 0 {
  101. time += strconv.Itoa(num/60) + " 分钟 "
  102. num %= 60
  103. }
  104. time += strconv.Itoa(num) + " 秒"
  105. return
  106. }
  107. func Interface2String(inter interface{}) string {
  108. switch inter.(type) {
  109. case string:
  110. return inter.(string)
  111. case int:
  112. return fmt.Sprintf("%d", inter.(int))
  113. case float64:
  114. return fmt.Sprintf("%f", inter.(float64))
  115. }
  116. return "Not Implemented"
  117. }
  118. func UnescapeHTML(x string) interface{} {
  119. return template.HTML(x)
  120. }
  121. func IntMax(a int, b int) int {
  122. if a >= b {
  123. return a
  124. } else {
  125. return b
  126. }
  127. }
  128. func IsIP(s string) bool {
  129. ip := net.ParseIP(s)
  130. return ip != nil
  131. }
  132. func GetUUID() string {
  133. code := uuid.New().String()
  134. code = strings.Replace(code, "-", "", -1)
  135. return code
  136. }
  137. const keyChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  138. func init() {
  139. rand.New(rand.NewSource(time.Now().UnixNano()))
  140. }
  141. func GenerateRandomCharsKey(length int) (string, error) {
  142. b := make([]byte, length)
  143. maxI := big.NewInt(int64(len(keyChars)))
  144. for i := range b {
  145. n, err := crand.Int(crand.Reader, maxI)
  146. if err != nil {
  147. return "", err
  148. }
  149. b[i] = keyChars[n.Int64()]
  150. }
  151. return string(b), nil
  152. }
  153. func GenerateRandomKey(length int) (string, error) {
  154. bytes := make([]byte, length*3/4) // 对于48位的输出,这里应该是36
  155. if _, err := crand.Read(bytes); err != nil {
  156. return "", err
  157. }
  158. return base64.StdEncoding.EncodeToString(bytes), nil
  159. }
  160. func GenerateKey() (string, error) {
  161. //rand.Seed(time.Now().UnixNano())
  162. return GenerateRandomCharsKey(48)
  163. }
  164. func GetRandomInt(max int) int {
  165. //rand.Seed(time.Now().UnixNano())
  166. return rand.Intn(max)
  167. }
  168. func GetTimestamp() int64 {
  169. return time.Now().Unix()
  170. }
  171. func GetTimeString() string {
  172. now := time.Now()
  173. return fmt.Sprintf("%s%d", now.Format("20060102150405"), now.UnixNano()%1e9)
  174. }
  175. func Max(a int, b int) int {
  176. if a >= b {
  177. return a
  178. } else {
  179. return b
  180. }
  181. }
  182. func MessageWithRequestId(message string, id string) string {
  183. return fmt.Sprintf("%s (request id: %s)", message, id)
  184. }
  185. func RandomSleep() {
  186. // Sleep for 0-3000 ms
  187. time.Sleep(time.Duration(rand.Intn(3000)) * time.Millisecond)
  188. }
  189. func GetPointer[T any](v T) *T {
  190. return &v
  191. }
  192. func Any2Type[T any](data any) (T, error) {
  193. var zero T
  194. bytes, err := json.Marshal(data)
  195. if err != nil {
  196. return zero, err
  197. }
  198. var res T
  199. err = json.Unmarshal(bytes, &res)
  200. if err != nil {
  201. return zero, err
  202. }
  203. return res, nil
  204. }
  205. // SaveTmpFile saves data to a temporary file. The filename would be apppended with a random string.
  206. func SaveTmpFile(filename string, data io.Reader) (string, error) {
  207. f, err := os.CreateTemp(os.TempDir(), filename)
  208. if err != nil {
  209. return "", errors.Wrapf(err, "failed to create temporary file %s", filename)
  210. }
  211. defer f.Close()
  212. _, err = io.Copy(f, data)
  213. if err != nil {
  214. return "", errors.Wrapf(err, "failed to copy data to temporary file %s", filename)
  215. }
  216. return f.Name(), nil
  217. }
  218. // GetAudioDuration returns the duration of an audio file in seconds.
  219. func GetAudioDuration(ctx context.Context, filename string) (float64, error) {
  220. // ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 {{input}}
  221. c := exec.CommandContext(ctx, "ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filename)
  222. output, err := c.Output()
  223. if err != nil {
  224. return 0, errors.Wrap(err, "failed to get audio duration")
  225. }
  226. return strconv.ParseFloat(string(bytes.TrimSpace(output)), 64)
  227. }