mediaServer.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  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. //
  23. func mediaServer_init() {
  24. if *enable_gzip {
  25. http.HandleFunc("/media/", gzipmiddleware.CompressFunc(serverMedia))
  26. http.HandleFunc("/media/getMime/", gzipmiddleware.CompressFunc(serveMediaMime))
  27. } else {
  28. http.HandleFunc("/media/", serverMedia)
  29. http.HandleFunc("/media/getMime/", serveMediaMime)
  30. }
  31. //Download API always bypass gzip no matter if gzip mode is enabled
  32. http.HandleFunc("/media/download/", serverMedia)
  33. }
  34. //This function validate the incoming media request and return the real path for the targed file
  35. func media_server_validateSourceFile(w http.ResponseWriter, r *http.Request) (string, error) {
  36. username, err := authAgent.GetUserName(w, r)
  37. if err != nil {
  38. return "", errors.New("User not logged in")
  39. }
  40. userinfo, _ := userHandler.GetUserInfoFromUsername(username)
  41. //Validate url valid
  42. if strings.Count(r.URL.String(), "?") > 1 {
  43. return "", errors.New("Invalid paramters. Multiple ? found")
  44. }
  45. targetfile, _ := common.Mv(r, "file", false)
  46. targetfile, err = url.QueryUnescape(targetfile)
  47. if targetfile == "" {
  48. return "", errors.New("Missing paramter 'file'")
  49. }
  50. //Translate the virtual directory to realpath
  51. realFilepath, err := userinfo.VirtualPathToRealPath(targetfile)
  52. if fs.FileExists(realFilepath) && fs.IsDir(realFilepath) {
  53. return "", errors.New("Given path is not a file.")
  54. }
  55. if err != nil {
  56. return "", errors.New("Unable to translate the given filepath")
  57. }
  58. if !fs.FileExists(realFilepath) {
  59. //Sometime if url is not URL encoded, this error might be shown as well
  60. //Try to use manual segmentation
  61. originalURL := r.URL.String()
  62. //Must be pre-processed with system special URI Decode function to handle edge cases
  63. originalURL = fs.DecodeURI(originalURL)
  64. if strings.Contains(originalURL, "&download=true") {
  65. originalURL = strings.ReplaceAll(originalURL, "&download=true", "")
  66. } else if strings.Contains(originalURL, "download=true") {
  67. originalURL = strings.ReplaceAll(originalURL, "download=true", "")
  68. }
  69. if strings.Contains(originalURL, "&file=") {
  70. originalURL = strings.ReplaceAll(originalURL, "&file=", "file=")
  71. }
  72. urlInfo := strings.Split(originalURL, "file=")
  73. possibleVirtualFilePath := urlInfo[len(urlInfo)-1]
  74. possibleRealpath, err := userinfo.VirtualPathToRealPath(possibleVirtualFilePath)
  75. if err != nil {
  76. log.Println("Error when trying to serve file in compatibility mode", err.Error())
  77. return "", errors.New("Error when trying to serve file in compatibility mode")
  78. }
  79. if fs.FileExists(possibleRealpath) {
  80. realFilepath = possibleRealpath
  81. log.Println("[Media Server] Serving file " + filepath.Base(possibleRealpath) + " in compatibility mode. Do not to use '&' or '+' sign in filename! ")
  82. return realFilepath, nil
  83. } else {
  84. return "", errors.New("File not exists")
  85. }
  86. }
  87. return realFilepath, nil
  88. }
  89. func serveMediaMime(w http.ResponseWriter, r *http.Request) {
  90. realFilepath, err := media_server_validateSourceFile(w, r)
  91. if err != nil {
  92. common.SendErrorResponse(w, err.Error())
  93. return
  94. }
  95. mime := "text/directory"
  96. if !fs.IsDir(realFilepath) {
  97. m, _, err := fs.GetMime(realFilepath)
  98. if err != nil {
  99. mime = ""
  100. }
  101. mime = m
  102. }
  103. common.SendTextResponse(w, mime)
  104. }
  105. func serverMedia(w http.ResponseWriter, r *http.Request) {
  106. //Serve normal media files
  107. realFilepath, err := media_server_validateSourceFile(w, r)
  108. if err != nil {
  109. common.SendErrorResponse(w, err.Error())
  110. return
  111. }
  112. //Check if downloadMode
  113. downloadMode := false
  114. dw, _ := common.Mv(r, "download", false)
  115. if dw == "true" {
  116. downloadMode = true
  117. }
  118. //New download implementations, allow /download to be used instead of &download=true
  119. if strings.Contains(r.RequestURI, "media/download/?file=") {
  120. downloadMode = true
  121. }
  122. //Serve the file
  123. if downloadMode {
  124. userAgent := r.Header.Get("User-Agent")
  125. filename := strings.ReplaceAll(url.QueryEscape(filepath.Base(realFilepath)), "+", "%20")
  126. //log.Println(r.Header.Get("User-Agent"))
  127. if strings.Contains(userAgent, "Safari/") {
  128. //This is Safari. Use speial header
  129. w.Header().Set("Content-Disposition", "attachment; filename="+filepath.Base(realFilepath))
  130. } else {
  131. //Fixing the header issue on Golang url encode lib problems
  132. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+filename)
  133. }
  134. //w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  135. }
  136. http.ServeFile(w, r, realFilepath)
  137. }