mediaServer.go 4.7 KB

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