mediaServer.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. package main
  2. import (
  3. "crypto/md5"
  4. "encoding/hex"
  5. "errors"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "os"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "imuslab.com/arozos/mod/compatibility"
  15. "imuslab.com/arozos/mod/filesystem"
  16. fs "imuslab.com/arozos/mod/filesystem"
  17. "imuslab.com/arozos/mod/utils"
  18. )
  19. /*
  20. Media Server
  21. This function serve large file objects like video and audio file via asynchronize go routine :)
  22. Example usage:
  23. /media/?file=user:/Desktop/test/02.Orchestra- エミール (Addendum version).mp3
  24. /media/?file=user:/Desktop/test/02.Orchestra- エミール (Addendum version).mp3&download=true
  25. This will serve / download the file located at files/users/{username}/Desktop/test/02.Orchestra- エミール (Addendum version).mp3
  26. PLEASE ALWAYS USE URLENCODE IN THE LINK PASSED INTO THE /media ENDPOINT
  27. */
  28. func mediaServer_init() {
  29. http.HandleFunc("/media/", serverMedia)
  30. http.HandleFunc("/media/getMime/", serveMediaMime)
  31. http.HandleFunc("/media/download/", serverMedia)
  32. }
  33. // This function validate the incoming media request and return fsh, vpath, rpath and err if any
  34. func media_server_validateSourceFile(w http.ResponseWriter, r *http.Request) (*filesystem.FileSystemHandler, string, string, error) {
  35. username, err := authAgent.GetUserName(w, r)
  36. if err != nil {
  37. return nil, "", "", 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 nil, "", "", errors.New("Invalid paramters. Multiple ? found")
  43. }
  44. targetfile, _ := utils.GetPara(r, "file")
  45. targetfile, err = url.QueryUnescape(targetfile)
  46. if err != nil {
  47. return nil, "", "", err
  48. }
  49. if targetfile == "" {
  50. return nil, "", "", errors.New("Missing paramter 'file'")
  51. }
  52. //Translate the virtual directory to realpath
  53. fsh, subpath, err := GetFSHandlerSubpathFromVpath(targetfile)
  54. if err != nil {
  55. return nil, "", "", errors.New("Unable to load from target file system")
  56. }
  57. fshAbs := fsh.FileSystemAbstraction
  58. realFilepath, err := fshAbs.VirtualPathToRealPath(subpath, userinfo.Username)
  59. if fshAbs.FileExists(realFilepath) && fshAbs.IsDir(realFilepath) {
  60. return nil, "", "", errors.New("Given path is not a file")
  61. }
  62. if err != nil {
  63. return nil, "", "", errors.New("Unable to translate the given filepath")
  64. }
  65. if !fshAbs.FileExists(realFilepath) {
  66. //Sometime if url is not URL encoded, this error might be shown as well
  67. //Try to use manual segmentation
  68. originalURL := r.URL.String()
  69. //Must be pre-processed with system special URI Decode function to handle edge cases
  70. originalURL = fs.DecodeURI(originalURL)
  71. if strings.Contains(originalURL, "&download=true") {
  72. originalURL = strings.ReplaceAll(originalURL, "&download=true", "")
  73. } else if strings.Contains(originalURL, "download=true") {
  74. originalURL = strings.ReplaceAll(originalURL, "download=true", "")
  75. }
  76. if strings.Contains(originalURL, "&file=") {
  77. originalURL = strings.ReplaceAll(originalURL, "&file=", "file=")
  78. }
  79. urlInfo := strings.Split(originalURL, "file=")
  80. possibleVirtualFilePath := urlInfo[len(urlInfo)-1]
  81. possibleRealpath, err := fshAbs.VirtualPathToRealPath(possibleVirtualFilePath, userinfo.Username)
  82. if err != nil {
  83. systemWideLogger.PrintAndLog("Media Server", "Error when trying to serve file in compatibility mode", err)
  84. return nil, "", "", errors.New("Error when trying to serve file in compatibility mode")
  85. }
  86. if fshAbs.FileExists(possibleRealpath) {
  87. realFilepath = possibleRealpath
  88. systemWideLogger.PrintAndLog("Media Server", "Serving file "+filepath.Base(possibleRealpath)+" in compatibility mode. Do not to use '&' or '+' sign in filename! ", nil)
  89. return fsh, targetfile, realFilepath, nil
  90. } else {
  91. return nil, "", "", errors.New("File not exists")
  92. }
  93. }
  94. return fsh, targetfile, realFilepath, nil
  95. }
  96. func serveMediaMime(w http.ResponseWriter, r *http.Request) {
  97. targetFsh, _, realFilepath, err := media_server_validateSourceFile(w, r)
  98. if err != nil {
  99. utils.SendErrorResponse(w, err.Error())
  100. return
  101. }
  102. targetFshAbs := targetFsh.FileSystemAbstraction
  103. if targetFsh.RequireBuffer {
  104. //File is not on local. Guess its mime by extension
  105. utils.SendTextResponse(w, "application/"+filepath.Ext(realFilepath)[1:])
  106. return
  107. }
  108. mime := "text/directory"
  109. if !targetFshAbs.IsDir(realFilepath) {
  110. m, _, err := fs.GetMime(realFilepath)
  111. if err != nil {
  112. mime = ""
  113. }
  114. mime = m
  115. }
  116. utils.SendTextResponse(w, mime)
  117. }
  118. func serverMedia(w http.ResponseWriter, r *http.Request) {
  119. userinfo, _ := userHandler.GetUserInfoFromRequest(w, r)
  120. //Serve normal media files
  121. targetFsh, vpath, realFilepath, err := media_server_validateSourceFile(w, r)
  122. if err != nil {
  123. utils.SendErrorResponse(w, err.Error())
  124. return
  125. }
  126. targetFshAbs := targetFsh.FileSystemAbstraction
  127. //Check if downloadMode
  128. downloadMode := false
  129. dw, _ := utils.GetPara(r, "download")
  130. if dw == "true" {
  131. downloadMode = true
  132. }
  133. //New download implementations, allow /download to be used instead of &download=true
  134. if strings.Contains(r.RequestURI, "media/download/?file=") {
  135. downloadMode = true
  136. }
  137. //Serve the file
  138. if downloadMode {
  139. escapedRealFilepath, err := url.PathUnescape(realFilepath)
  140. if err != nil {
  141. utils.SendErrorResponse(w, err.Error())
  142. return
  143. }
  144. filename := filepath.Base(escapedRealFilepath)
  145. w.Header().Set("Content-Disposition", "attachment; filename=\""+filename+"\"")
  146. w.Header().Set("Content-Type", compatibility.BrowserCompatibilityOverrideContentType(r.UserAgent(), filename, r.Header.Get("Content-Type")))
  147. if targetFsh.RequireBuffer || !filesystem.FileExists(realFilepath) {
  148. //Stream it directly from remote
  149. w.Header().Set("Content-Length", strconv.Itoa(int(targetFshAbs.GetFileSize(realFilepath))))
  150. remoteStream, err := targetFshAbs.ReadStream(realFilepath)
  151. if err != nil {
  152. utils.SendErrorResponse(w, err.Error())
  153. return
  154. }
  155. io.Copy(w, remoteStream)
  156. remoteStream.Close()
  157. } else {
  158. http.ServeFile(w, r, escapedRealFilepath)
  159. }
  160. } else {
  161. if targetFsh.RequireBuffer {
  162. w.Header().Set("Content-Length", strconv.Itoa(int(targetFshAbs.GetFileSize(realFilepath))))
  163. //Check buffer exists
  164. ps, _ := targetFsh.GetUniquePathHash(vpath, userinfo.Username)
  165. buffpool := filepath.Join(*tmp_directory, "fsbuffpool")
  166. buffFile := filepath.Join(buffpool, ps)
  167. if fs.FileExists(buffFile) {
  168. //Stream the buff file if hash matches
  169. remoteFileHash, err := getHashFromRemoteFile(targetFsh.FileSystemAbstraction, realFilepath)
  170. if err == nil {
  171. localFileHash, err := os.ReadFile(buffFile + ".hash")
  172. if err == nil {
  173. if string(localFileHash) == remoteFileHash {
  174. //Hash matches. Serve local buffered file
  175. http.ServeFile(w, r, buffFile)
  176. return
  177. }
  178. }
  179. }
  180. }
  181. remoteStream, err := targetFshAbs.ReadStream(realFilepath)
  182. if err != nil {
  183. utils.SendErrorResponse(w, err.Error())
  184. return
  185. }
  186. defer remoteStream.Close()
  187. io.Copy(w, remoteStream)
  188. if *enable_buffering {
  189. os.MkdirAll(buffpool, 0775)
  190. go func() {
  191. BufferRemoteFileToTmp(buffFile, targetFsh, realFilepath)
  192. }()
  193. }
  194. } else if !filesystem.FileExists(realFilepath) {
  195. //Streaming from remote file system that support fseek
  196. f, err := targetFsh.FileSystemAbstraction.Open(realFilepath)
  197. if err != nil {
  198. w.WriteHeader(http.StatusInternalServerError)
  199. w.Write([]byte("500 - Internal Server Error"))
  200. return
  201. }
  202. fstat, _ := f.Stat()
  203. defer f.Close()
  204. http.ServeContent(w, r, filepath.Base(realFilepath), fstat.ModTime(), f)
  205. } else {
  206. http.ServeFile(w, r, realFilepath)
  207. }
  208. }
  209. }
  210. func BufferRemoteFileToTmp(buffFile string, fsh *filesystem.FileSystemHandler, rpath string) error {
  211. if fs.FileExists(buffFile + ".download") {
  212. return errors.New("another buffer process running")
  213. }
  214. //Generate a stat file for the buffer
  215. hash, err := getHashFromRemoteFile(fsh.FileSystemAbstraction, rpath)
  216. if err != nil {
  217. //Do not buffer
  218. return err
  219. }
  220. os.WriteFile(buffFile+".hash", []byte(hash), 0775)
  221. //Buffer the file from remote to local
  222. f, err := fsh.FileSystemAbstraction.ReadStream(rpath)
  223. if err != nil {
  224. os.Remove(buffFile + ".hash")
  225. return err
  226. }
  227. defer f.Close()
  228. dest, err := os.OpenFile(buffFile+".download", os.O_CREATE|os.O_WRONLY, 0775)
  229. if err != nil {
  230. os.Remove(buffFile + ".hash")
  231. return err
  232. }
  233. defer dest.Close()
  234. io.Copy(dest, f)
  235. f.Close()
  236. dest.Close()
  237. os.Rename(buffFile+".download", buffFile)
  238. //Clean the oldest buffpool item if size too large
  239. dirsize, _ := fs.GetDirctorySize(filepath.Dir(buffFile), false)
  240. oldestModtime := time.Now().Unix()
  241. oldestFile := ""
  242. for int(dirsize) > *bufferPoolSize<<20 {
  243. //fmt.Println("CLEARNING BUFF", dirsize)
  244. files, _ := filepath.Glob(filepath.ToSlash(filepath.Dir(buffFile)) + "/*")
  245. for _, file := range files {
  246. if filepath.Ext(file) == ".hash" {
  247. continue
  248. }
  249. thisModTime, _ := fs.GetModTime(file)
  250. if thisModTime < oldestModtime {
  251. oldestModtime = thisModTime
  252. oldestFile = file
  253. }
  254. }
  255. os.Remove(oldestFile)
  256. os.Remove(oldestFile + ".hash")
  257. dirsize, _ = fs.GetDirctorySize(filepath.Dir(buffFile), false)
  258. oldestModtime = time.Now().Unix()
  259. }
  260. return nil
  261. }
  262. func getHashFromRemoteFile(fshAbs filesystem.FileSystemAbstraction, rpath string) (string, error) {
  263. filestat, err := fshAbs.Stat(rpath)
  264. if err != nil {
  265. //Always pull from remote
  266. return "", err
  267. }
  268. if filestat.Size() >= int64(*bufferPoolSize<<20) {
  269. return "", errors.New("Unable to buffer: file larger than buffpool size")
  270. }
  271. if filestat.Size() >= int64(*bufferFileMaxSize<<20) {
  272. return "", errors.New("File larger than max buffer file size")
  273. }
  274. statHash := strconv.Itoa(int(filestat.ModTime().Unix() + filestat.Size()))
  275. hash := md5.Sum([]byte(statHash))
  276. return hex.EncodeToString(hash[:]), nil
  277. }