mediaServer.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. package main
  2. import (
  3. "errors"
  4. "log"
  5. "net/http"
  6. "net/url"
  7. "path/filepath"
  8. "strings"
  9. fs "imuslab.com/arozos/mod/filesystem"
  10. "imuslab.com/arozos/mod/network/gzipmiddleware"
  11. )
  12. /*
  13. Media Server
  14. This function serve large file objects like video and audio file via asynchronize go routine :)
  15. Example usage:
  16. /media/?file=user:/Desktop/test/02.Orchestra- エミール (Addendum version).mp3
  17. /media/?file=user:/Desktop/test/02.Orchestra- エミール (Addendum version).mp3&download=true
  18. This will serve / download the file located at files/users/{username}/Desktop/test/02.Orchestra- エミール (Addendum version).mp3
  19. PLEASE ALWAYS USE URLENCODE IN THE LINK PASSED INTO THE /media ENDPOINT
  20. */
  21. //
  22. func mediaServer_init() {
  23. http.HandleFunc("/media/", gzipmiddleware.CompressFunc(serverMedia))
  24. http.HandleFunc("/media/getMime/", gzipmiddleware.CompressFunc(serveMediaMime))
  25. }
  26. //This function validate the incoming media request and return the real path for the targed file
  27. func media_server_validateSourceFile(w http.ResponseWriter, r *http.Request) (string, error) {
  28. username, err := authAgent.GetUserName(w, r)
  29. if err != nil {
  30. return "", errors.New("User not logged in")
  31. }
  32. userinfo, _ := userHandler.GetUserInfoFromUsername(username)
  33. //Validate url valid
  34. if strings.Count(r.URL.String(), "?") > 1 {
  35. return "", errors.New("Invalid paramters. Multiple ? found")
  36. }
  37. targetfile, _ := mv(r, "file", false)
  38. targetfile, _ = url.QueryUnescape(targetfile)
  39. if targetfile == "" {
  40. return "", errors.New("Missing paramter 'file'")
  41. }
  42. //Translate the virtual directory to realpath
  43. realFilepath, err := userinfo.VirtualPathToRealPath(targetfile)
  44. if fileExists(realFilepath) && IsDir(realFilepath) {
  45. return "", errors.New("Given path is not a file.")
  46. }
  47. if err != nil {
  48. return "", errors.New("Unable to translate the given filepath")
  49. }
  50. if !fileExists(realFilepath) {
  51. //Sometime if url is not URL encoded, this error might be shown as well
  52. //Try to use manual segmentation
  53. originalURL := r.URL.String()
  54. //Must be pre-processed with system special URI Decode function to handle edge cases
  55. originalURL = fs.DecodeURI(originalURL)
  56. if strings.Contains(originalURL, "&download=true") {
  57. originalURL = strings.ReplaceAll(originalURL, "&download=true", "")
  58. } else if strings.Contains(originalURL, "download=true") {
  59. originalURL = strings.ReplaceAll(originalURL, "download=true", "")
  60. }
  61. if strings.Contains(originalURL, "&file=") {
  62. originalURL = strings.ReplaceAll(originalURL, "&file=", "file=")
  63. }
  64. urlInfo := strings.Split(originalURL, "file=")
  65. possibleVirtualFilePath := urlInfo[len(urlInfo)-1]
  66. possibleRealpath, err := userinfo.VirtualPathToRealPath(possibleVirtualFilePath)
  67. if err != nil {
  68. log.Println("Error when trying to serve file in compatibility mode", err.Error())
  69. return "", errors.New("Error when trying to serve file in compatibility mode")
  70. }
  71. if fileExists(possibleRealpath) {
  72. realFilepath = possibleRealpath
  73. log.Println("[Media Server] Serving file " + filepath.Base(possibleRealpath) + " in compatibility mode. Do not to use '&' or '+' sign in filename! ")
  74. return realFilepath, nil
  75. } else {
  76. return "", errors.New("File not exists")
  77. }
  78. }
  79. return realFilepath, nil
  80. }
  81. func serveMediaMime(w http.ResponseWriter, r *http.Request) {
  82. realFilepath, err := media_server_validateSourceFile(w, r)
  83. if err != nil {
  84. sendErrorResponse(w, err.Error())
  85. return
  86. }
  87. mime := "text/directory"
  88. if !IsDir(realFilepath) {
  89. m, _, err := fs.GetMime(realFilepath)
  90. if err != nil {
  91. mime = ""
  92. }
  93. mime = m
  94. }
  95. sendTextResponse(w, mime)
  96. }
  97. func serverMedia(w http.ResponseWriter, r *http.Request) {
  98. //Serve normal media files
  99. realFilepath, err := media_server_validateSourceFile(w, r)
  100. if err != nil {
  101. sendErrorResponse(w, err.Error())
  102. return
  103. }
  104. //Check if downloadMode
  105. downloadMode := false
  106. dw, _ := mv(r, "download", false)
  107. if dw == "true" {
  108. downloadMode = true
  109. }
  110. //Serve the file
  111. if downloadMode {
  112. userAgent := r.Header.Get("User-Agent")
  113. filename := strings.ReplaceAll(url.QueryEscape(filepath.Base(realFilepath)), "+", "%20")
  114. log.Println(r.Header.Get("User-Agent"))
  115. if strings.Contains(userAgent, "Safari/") {
  116. //This is Safari. Use speial header
  117. w.Header().Set("Content-Disposition", "attachment; filename="+filepath.Base(realFilepath))
  118. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  119. } else {
  120. //Fixing the header issue on Golang url encode lib problems
  121. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+filename)
  122. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  123. }
  124. }
  125. http.ServeFile(w, r, realFilepath)
  126. }