mediaServer.go 5.0 KB

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