mediaServer.go 4.5 KB

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