Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

91 lines
2.1KB

  1. package main
  2. import (
  3. "encoding/json"
  4. "io"
  5. "io/ioutil"
  6. "log"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "strconv"
  11. "time"
  12. )
  13. func saveURL(url string) (tmpFile string, contentType string, err error) {
  14. var myClient = &http.Client{Timeout: 20 * time.Second}
  15. r, err := myClient.Get(url)
  16. if err != nil {
  17. log.Fatal("Fail to get URL:" + url)
  18. log.Fatal(err)
  19. return "", "", err
  20. }
  21. defer r.Body.Close()
  22. contentType = r.Header.Get("Content-Type")
  23. contentLen := r.Header.Get("Content-Length")
  24. len, _ := strconv.Atoi(contentLen)
  25. file, err := ioutil.TempFile(os.TempDir(), "wechat_hitxy_")
  26. // Use io.Copy to just dump the response body to the file. This supports huge files
  27. _, err = io.Copy(file, r.Body)
  28. if err != nil {
  29. return "", contentType, err
  30. }
  31. tmpFile = file.Name()
  32. file.Close()
  33. //see if its a video url
  34. if len < 4096 && contentType == "text/plain" {
  35. u := readVideoURL(tmpFile)
  36. if u != "" {
  37. os.Remove(tmpFile) //remove json file
  38. tmpFile, contentType, err = saveVideo(u)
  39. }
  40. }
  41. return
  42. }
  43. func contentType2MediaType(contentType string) (mediaType string) {
  44. switch contentType {
  45. case "image/jpeg":
  46. mediaType = "image"
  47. case "text/plain":
  48. mediaType = "json"
  49. }
  50. return
  51. }
  52. //{"video_url":"http://153.37.232.145/vweixinp.tc.qq.com/1007_6475d21fb443453b8adeac7e59cc0e1c.f10.mp4?vkey=E79C6B0DA06E7A434D15E24774F91412386D1956768C400AC93ECA5320ACAAAF050E1E1BA5C22DFD81B5EE3FBA97E928E0FC2DC597CF611B3E6641BC1AEE2892736FFE29E993F200AA4A0811FEB4E234C48516131207DDE4&sha=0&save=1"}
  53. type videoURL struct {
  54. VideoURL string `json:"video_url"`
  55. }
  56. //readVideoURL try to read a file into json structure
  57. //containing video_url
  58. //
  59. func readVideoURL(path string) (u string) {
  60. body, err := ioutil.ReadFile(path)
  61. if err == nil {
  62. var v = videoURL{}
  63. err = json.Unmarshal([]byte(body), &v)
  64. if err == nil {
  65. _, err = url.ParseRequestURI(v.VideoURL)
  66. if err == nil {
  67. return v.VideoURL
  68. }
  69. }
  70. }
  71. return ""
  72. }
  73. func saveVideo(path string) (tmpFile string, contentType string, err error) {
  74. u := readVideoURL(path)
  75. if u != "" {
  76. tmpFile, contentType, err = saveURL(u)
  77. }
  78. return
  79. }