mediaServer.go 4.8 KB

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