utils.go 6.8 KB

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