mediaServer.go 5.3 KB

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