mediaServer.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. package main
  2. import (
  3. "errors"
  4. "log"
  5. "net/http"
  6. "net/url"
  7. "os"
  8. "path/filepath"
  9. "strconv"
  10. "strings"
  11. "imuslab.com/arozos/mod/common"
  12. fs "imuslab.com/arozos/mod/filesystem"
  13. "imuslab.com/arozos/mod/network/gzipmiddleware"
  14. )
  15. /*
  16. Media Server
  17. This function serve large file objects like video and audio file via asynchronize go routine :)
  18. Example usage:
  19. /media/?file=user:/Desktop/test/02.Orchestra- エミール (Addendum version).mp3
  20. /media/?file=user:/Desktop/test/02.Orchestra- エミール (Addendum version).mp3&download=true
  21. This will serve / download the file located at files/users/{username}/Desktop/test/02.Orchestra- エミール (Addendum version).mp3
  22. PLEASE ALWAYS USE URLENCODE IN THE LINK PASSED INTO THE /media ENDPOINT
  23. */
  24. //
  25. func mediaServer_init() {
  26. if *enable_gzip {
  27. http.HandleFunc("/media/", gzipmiddleware.CompressFunc(serverMedia))
  28. http.HandleFunc("/media/getMime/", gzipmiddleware.CompressFunc(serveMediaMime))
  29. } else {
  30. http.HandleFunc("/media/", serverMedia)
  31. http.HandleFunc("/media/getMime/", serveMediaMime)
  32. }
  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. //Serve the file
  119. if downloadMode {
  120. userAgent := r.Header.Get("User-Agent")
  121. filename := strings.ReplaceAll(url.QueryEscape(filepath.Base(realFilepath)), "+", "%20")
  122. //log.Println(r.Header.Get("User-Agent"))
  123. if strings.Contains(userAgent, "Safari/") {
  124. //This is Safari. Use speial header
  125. w.Header().Set("Content-Disposition", "attachment; filename="+filepath.Base(realFilepath))
  126. } else {
  127. //Fixing the header issue on Golang url encode lib problems
  128. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+filename)
  129. }
  130. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  131. //Serve content length by trying to get filesize
  132. fi, err := os.Stat(filepath.Clean(realFilepath))
  133. if err == nil {
  134. w.Header().Set("Content-Length", strconv.Itoa(int(fi.Size())))
  135. }
  136. }
  137. http.ServeFile(w, r, realFilepath)
  138. }