utils.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. case bool:
  117. if inter.(bool) {
  118. return "true"
  119. } else {
  120. return "false"
  121. }
  122. case nil:
  123. return ""
  124. }
  125. return fmt.Sprintf("%v", inter)
  126. }
  127. func UnescapeHTML(x string) interface{} {
  128. return template.HTML(x)
  129. }
  130. func IntMax(a int, b int) int {
  131. if a >= b {
  132. return a
  133. } else {
  134. return b
  135. }
  136. }
  137. func IsIP(s string) bool {
  138. ip := net.ParseIP(s)
  139. return ip != nil
  140. }
  141. func GetUUID() string {
  142. code := uuid.New().String()
  143. code = strings.Replace(code, "-", "", -1)
  144. return code
  145. }
  146. const keyChars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  147. func init() {
  148. rand.New(rand.NewSource(time.Now().UnixNano()))
  149. }
  150. func GenerateRandomCharsKey(length int) (string, error) {
  151. b := make([]byte, length)
  152. maxI := big.NewInt(int64(len(keyChars)))
  153. for i := range b {
  154. n, err := crand.Int(crand.Reader, maxI)
  155. if err != nil {
  156. return "", err
  157. }
  158. b[i] = keyChars[n.Int64()]
  159. }
  160. return string(b), nil
  161. }
  162. func GenerateRandomKey(length int) (string, error) {
  163. bytes := make([]byte, length*3/4) // 对于48位的输出,这里应该是36
  164. if _, err := crand.Read(bytes); err != nil {
  165. return "", err
  166. }
  167. return base64.StdEncoding.EncodeToString(bytes), nil
  168. }
  169. func GenerateKey() (string, error) {
  170. //rand.Seed(time.Now().UnixNano())
  171. return GenerateRandomCharsKey(48)
  172. }
  173. func GetRandomInt(max int) int {
  174. //rand.Seed(time.Now().UnixNano())
  175. return rand.Intn(max)
  176. }
  177. func GetTimestamp() int64 {
  178. return time.Now().Unix()
  179. }
  180. func GetTimeString() string {
  181. now := time.Now()
  182. return fmt.Sprintf("%s%d", now.Format("20060102150405"), now.UnixNano()%1e9)
  183. }
  184. func Max(a int, b int) int {
  185. if a >= b {
  186. return a
  187. } else {
  188. return b
  189. }
  190. }
  191. func MessageWithRequestId(message string, id string) string {
  192. return fmt.Sprintf("%s (request id: %s)", message, id)
  193. }
  194. func RandomSleep() {
  195. // Sleep for 0-3000 ms
  196. time.Sleep(time.Duration(rand.Intn(3000)) * time.Millisecond)
  197. }
  198. func GetPointer[T any](v T) *T {
  199. return &v
  200. }
  201. func Any2Type[T any](data any) (T, error) {
  202. var zero T
  203. bytes, err := json.Marshal(data)
  204. if err != nil {
  205. return zero, err
  206. }
  207. var res T
  208. err = json.Unmarshal(bytes, &res)
  209. if err != nil {
  210. return zero, err
  211. }
  212. return res, nil
  213. }
  214. // SaveTmpFile saves data to a temporary file. The filename would be apppended with a random string.
  215. func SaveTmpFile(filename string, data io.Reader) (string, error) {
  216. f, err := os.CreateTemp(os.TempDir(), filename)
  217. if err != nil {
  218. return "", errors.Wrapf(err, "failed to create temporary file %s", filename)
  219. }
  220. defer f.Close()
  221. _, err = io.Copy(f, data)
  222. if err != nil {
  223. return "", errors.Wrapf(err, "failed to copy data to temporary file %s", filename)
  224. }
  225. return f.Name(), nil
  226. }
  227. // GetAudioDuration returns the duration of an audio file in seconds.
  228. func GetAudioDuration(ctx context.Context, filename string, ext string) (float64, error) {
  229. // ffprobe -v error -show_entries format=duration -of default=noprint_wrappers=1:nokey=1 {{input}}
  230. c := exec.CommandContext(ctx, "ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filename)
  231. output, err := c.Output()
  232. if err != nil {
  233. return 0, errors.Wrap(err, "failed to get audio duration")
  234. }
  235. durationStr := string(bytes.TrimSpace(output))
  236. if durationStr == "N/A" {
  237. // Create a temporary output file name
  238. tmpFp, err := os.CreateTemp("", "audio-*"+ext)
  239. if err != nil {
  240. return 0, errors.Wrap(err, "failed to create temporary file")
  241. }
  242. tmpName := tmpFp.Name()
  243. // Close immediately so ffmpeg can open the file on Windows.
  244. _ = tmpFp.Close()
  245. defer os.Remove(tmpName)
  246. // ffmpeg -y -i filename -vcodec copy -acodec copy <tmpName>
  247. ffmpegCmd := exec.CommandContext(ctx, "ffmpeg", "-y", "-i", filename, "-vcodec", "copy", "-acodec", "copy", tmpName)
  248. if err := ffmpegCmd.Run(); err != nil {
  249. return 0, errors.Wrap(err, "failed to run ffmpeg")
  250. }
  251. // Recalculate the duration of the new file
  252. c = exec.CommandContext(ctx, "ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", tmpName)
  253. output, err := c.Output()
  254. if err != nil {
  255. return 0, errors.Wrap(err, "failed to get audio duration after ffmpeg")
  256. }
  257. durationStr = string(bytes.TrimSpace(output))
  258. }
  259. return strconv.ParseFloat(durationStr, 64)
  260. }
  261. // BuildURL concatenates base and endpoint, returns the complete url string
  262. func BuildURL(base string, endpoint string) string {
  263. u, err := url.Parse(base)
  264. if err != nil {
  265. return base + endpoint
  266. }
  267. end := endpoint
  268. if end == "" {
  269. end = "/"
  270. }
  271. ref, err := url.Parse(end)
  272. if err != nil {
  273. return base + endpoint
  274. }
  275. return u.ResolveReference(ref).String()
  276. }