metadata.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. package metadata
  2. import (
  3. "encoding/base64"
  4. "encoding/json"
  5. "errors"
  6. "log"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/gorilla/websocket"
  14. "imuslab.com/arozos/mod/filesystem"
  15. "imuslab.com/arozos/mod/filesystem/fssort"
  16. hidden "imuslab.com/arozos/mod/filesystem/hidden"
  17. "imuslab.com/arozos/mod/utils"
  18. )
  19. /*
  20. This package is used to extract meta data from files like mp3 and mp4
  21. Also support image caching
  22. */
  23. type RenderHandler struct {
  24. renderingFiles sync.Map
  25. renderingFolder sync.Map
  26. }
  27. //Create a new RenderHandler
  28. func NewRenderHandler() *RenderHandler {
  29. return &RenderHandler{
  30. renderingFiles: sync.Map{},
  31. renderingFolder: sync.Map{},
  32. }
  33. }
  34. //Build cache for all files (non recursive) for the given filepath
  35. func (rh *RenderHandler) BuildCacheForFolder(fsh *filesystem.FileSystemHandler, vpath string, username string) error {
  36. fshAbs := fsh.FileSystemAbstraction
  37. rpath, _ := fshAbs.VirtualPathToRealPath(vpath, username)
  38. //Get a list of all files inside this path
  39. fis, err := fshAbs.ReadDir(filepath.ToSlash(filepath.Clean(rpath)))
  40. if err != nil {
  41. return err
  42. }
  43. for _, fi := range fis {
  44. //Load Cache in generate mode
  45. rh.LoadCache(fsh, filepath.Join(rpath, fi.Name()), true)
  46. }
  47. //Check if the cache folder has file. If not, remove it
  48. cachedFiles, _ := fshAbs.ReadDir(filepath.ToSlash(filepath.Join(filepath.Clean(rpath), "/.metadata/.cache/")))
  49. if len(cachedFiles) == 0 {
  50. fshAbs.RemoveAll(filepath.ToSlash(filepath.Join(filepath.Clean(rpath), "/.metadata/.cache/")) + "/")
  51. }
  52. return nil
  53. }
  54. func (rh *RenderHandler) LoadCacheAsBytes(fsh *filesystem.FileSystemHandler, vpath string, username string, generateOnly bool) ([]byte, error) {
  55. fshAbs := fsh.FileSystemAbstraction
  56. rpath, _ := fshAbs.VirtualPathToRealPath(vpath, username)
  57. b64, err := rh.LoadCache(fsh, rpath, generateOnly)
  58. if err != nil {
  59. return []byte{}, err
  60. }
  61. resultingBytes, _ := base64.StdEncoding.DecodeString(b64)
  62. return resultingBytes, nil
  63. }
  64. //Try to load a cache from file. If not exists, generate it now
  65. func (rh *RenderHandler) LoadCache(fsh *filesystem.FileSystemHandler, rpath string, generateOnly bool) (string, error) {
  66. //Create a cache folder
  67. fshAbs := fsh.FileSystemAbstraction
  68. cacheFolder := filepath.ToSlash(filepath.Join(filepath.Clean(filepath.Dir(rpath)), "/.metadata/.cache/") + "/")
  69. fshAbs.MkdirAll(cacheFolder, 0755)
  70. hidden.HideFile(filepath.Dir(filepath.Clean(cacheFolder)))
  71. hidden.HideFile(cacheFolder)
  72. //Check if cache already exists. If yes, return the image from the cache folder
  73. if CacheExists(fsh, rpath) {
  74. if generateOnly {
  75. //Only generate, do not return image
  76. return "", nil
  77. }
  78. //Allow thumbnail to be either jpg or png file
  79. ext := ".jpg"
  80. if !fshAbs.FileExists(cacheFolder + filepath.Base(rpath) + ".jpg") {
  81. ext = ".png"
  82. }
  83. //Updates 02/10/2021: Check if the source file is newer than the cache. Update the cache if true
  84. folderModeTime, _ := fshAbs.GetModTime(rpath)
  85. cacheImageModeTime, _ := fshAbs.GetModTime(cacheFolder + filepath.Base(rpath) + ext)
  86. if folderModeTime > cacheImageModeTime {
  87. //File is newer than cache. Delete the cache
  88. fshAbs.Remove(cacheFolder + filepath.Base(rpath) + ext)
  89. } else {
  90. //Check if the file is being writting by another process. If yes, wait for it
  91. counter := 0
  92. for rh.fileIsBusy(rpath) && counter < 15 {
  93. counter += 1
  94. time.Sleep(1 * time.Second)
  95. }
  96. //Time out and the file is still busy
  97. if rh.fileIsBusy(rpath) {
  98. log.Println("Process racing for cache file. Skipping", filepath.Base(rpath))
  99. return "", errors.New("Process racing for cache file. Skipping")
  100. }
  101. //Read and return the image
  102. ctx, err := getImageAsBase64(fsh, cacheFolder+filepath.Base(rpath)+ext)
  103. return ctx, err
  104. }
  105. } else if fsh.ReadOnly {
  106. //Not exists, but this Fsh is read only. Return nothing
  107. return "", errors.New("Cannot generate thumbnail on readonly file system")
  108. } else {
  109. //This file not exists yet. Check if it is being hold by another process already
  110. if rh.fileIsBusy(rpath) {
  111. log.Println("Process racing for cache file. Skipping", filepath.Base(rpath))
  112. return "", errors.New("Process racing for cache file. Skipping")
  113. }
  114. }
  115. //Cache image not exists. Set this file to busy
  116. rh.renderingFiles.Store(rpath, "busy")
  117. //That object not exists. Generate cache image
  118. //Audio formats that might contains id4 thumbnail
  119. id4Formats := []string{".mp3", ".ogg", ".flac"}
  120. if utils.StringInArray(id4Formats, strings.ToLower(filepath.Ext(rpath))) {
  121. img, err := generateThumbnailForAudio(fsh, cacheFolder, rpath, generateOnly)
  122. rh.renderingFiles.Delete(rpath)
  123. return img, err
  124. }
  125. //Generate resized image for images
  126. imageFormats := []string{".png", ".jpeg", ".jpg"}
  127. if utils.StringInArray(imageFormats, strings.ToLower(filepath.Ext(rpath))) {
  128. img, err := generateThumbnailForImage(fsh, cacheFolder, rpath, generateOnly)
  129. rh.renderingFiles.Delete(rpath)
  130. return img, err
  131. }
  132. //Video formats, extract from the 5 sec mark
  133. vidFormats := []string{".mkv", ".mp4", ".webm", ".ogv", ".avi", ".rmvb"}
  134. if utils.StringInArray(vidFormats, strings.ToLower(filepath.Ext(rpath))) {
  135. img, err := generateThumbnailForVideo(fsh, cacheFolder, rpath, generateOnly)
  136. rh.renderingFiles.Delete(rpath)
  137. return img, err
  138. }
  139. //3D Model Formats
  140. modelFormats := []string{".stl", ".obj"}
  141. if utils.StringInArray(modelFormats, strings.ToLower(filepath.Ext(rpath))) {
  142. img, err := generateThumbnailForModel(fsh, cacheFolder, rpath, generateOnly)
  143. rh.renderingFiles.Delete(rpath)
  144. return img, err
  145. }
  146. //Photoshop file
  147. if strings.ToLower(filepath.Ext(rpath)) == ".psd" {
  148. img, err := generateThumbnailForPSD(fsh, cacheFolder, rpath, generateOnly)
  149. rh.renderingFiles.Delete(rpath)
  150. return img, err
  151. }
  152. //Folder preview renderer
  153. if fshAbs.IsDir(rpath) && len(filepath.Base(rpath)) > 0 && filepath.Base(rpath)[:1] != "." {
  154. img, err := generateThumbnailForFolder(fsh, cacheFolder, rpath, generateOnly)
  155. rh.renderingFiles.Delete(rpath)
  156. return img, err
  157. }
  158. //Other filters
  159. rh.renderingFiles.Delete(rpath)
  160. return "", errors.New("No supported format")
  161. }
  162. func (rh *RenderHandler) fileIsBusy(path string) bool {
  163. if rh == nil {
  164. log.Println("RenderHandler is null!")
  165. return true
  166. }
  167. _, ok := rh.renderingFiles.Load(path)
  168. if !ok {
  169. //File path is not being process by another process
  170. return false
  171. } else {
  172. return true
  173. }
  174. }
  175. func getImageAsBase64(fsh *filesystem.FileSystemHandler, rpath string) (string, error) {
  176. fshAbs := fsh.FileSystemAbstraction
  177. content, err := fshAbs.ReadFile(rpath)
  178. if err != nil {
  179. return "", err
  180. }
  181. encoded := base64.StdEncoding.EncodeToString(content)
  182. return string(encoded), nil
  183. }
  184. //Load a list of folder cache from websocket, pass in "" (empty string) for default sorting method
  185. func (rh *RenderHandler) HandleLoadCache(w http.ResponseWriter, r *http.Request, fsh *filesystem.FileSystemHandler, rpath string, sortmode string) {
  186. //Get a list of files pending to be cached and sent
  187. targetPath := filepath.ToSlash(filepath.Clean(rpath))
  188. //Check if this path already exists another websocket ongoing connection.
  189. //If yes, disconnect the oldone
  190. oldc, ok := rh.renderingFolder.Load(targetPath)
  191. if ok {
  192. //Close and remove the old connection
  193. oldc.(*websocket.Conn).Close()
  194. }
  195. fis, err := fsh.FileSystemAbstraction.ReadDir(targetPath)
  196. if err != nil {
  197. w.WriteHeader(http.StatusInternalServerError)
  198. w.Write([]byte("500 - Internal Server Error"))
  199. return
  200. }
  201. //Upgrade the connection to websocket
  202. var upgrader = websocket.Upgrader{}
  203. upgrader.CheckOrigin = func(r *http.Request) bool { return true }
  204. c, err := upgrader.Upgrade(w, r, nil)
  205. if err != nil {
  206. log.Print("upgrade:", err)
  207. w.WriteHeader(http.StatusInternalServerError)
  208. w.Write([]byte("500 - Internal Server Error"))
  209. return
  210. }
  211. //Set this realpath as websocket connected
  212. rh.renderingFolder.Store(targetPath, c)
  213. //For each file, serve a cached image preview
  214. errorExists := false
  215. filesWithoutCache := []string{}
  216. //Updates implementation 02/10/2021: Load thumbnail of files first before folder and apply user preference sort mode
  217. if sortmode == "" {
  218. sortmode = "default"
  219. }
  220. sortedFis := fssort.SortDirEntryList(fis, sortmode)
  221. pendingFiles := []string{}
  222. pendingFolders := []string{}
  223. for _, fileInfo := range sortedFis {
  224. if !fileInfo.IsDir() {
  225. pendingFiles = append(pendingFiles, filepath.Join(targetPath, fileInfo.Name()))
  226. } else {
  227. pendingFolders = append(pendingFolders, filepath.Join(targetPath, fileInfo.Name()))
  228. }
  229. }
  230. pendingFiles = append(pendingFiles, pendingFolders...)
  231. files := pendingFiles
  232. //Updated implementation 24/12/2020: Load image with cache first before rendering those without
  233. for _, file := range files {
  234. if !CacheExists(fsh, file) {
  235. //Cache not exists. Render this later
  236. filesWithoutCache = append(filesWithoutCache, file)
  237. } else {
  238. //Cache exists. Send it out first
  239. cachedImage, err := rh.LoadCache(fsh, file, false)
  240. if err != nil {
  241. } else {
  242. jsonString, _ := json.Marshal([]string{filepath.Base(file), cachedImage})
  243. err := c.WriteMessage(1, jsonString)
  244. if err != nil {
  245. //Connection closed
  246. errorExists = true
  247. break
  248. }
  249. }
  250. }
  251. }
  252. retryList := []string{}
  253. //Render the remaining cache files
  254. for _, file := range filesWithoutCache {
  255. //Load the image cache
  256. cachedImage, err := rh.LoadCache(fsh, file, false)
  257. if err != nil {
  258. //Unable to load this file's cache. Push it to retry list
  259. retryList = append(retryList, file)
  260. } else {
  261. jsonString, _ := json.Marshal([]string{filepath.Base(file), cachedImage})
  262. err := c.WriteMessage(1, jsonString)
  263. if err != nil {
  264. //Connection closed
  265. errorExists = true
  266. break
  267. }
  268. }
  269. }
  270. //Process the retry list after some wait time
  271. if len(retryList) > 0 {
  272. time.Sleep(1000 * time.Millisecond)
  273. for _, file := range retryList {
  274. //Load the image cache
  275. cachedImage, err := rh.LoadCache(fsh, file, false)
  276. if err != nil {
  277. } else {
  278. jsonString, _ := json.Marshal([]string{filepath.Base(file), cachedImage})
  279. err := c.WriteMessage(1, jsonString)
  280. if err != nil {
  281. //Connection closed
  282. errorExists = true
  283. break
  284. }
  285. }
  286. }
  287. }
  288. //Clear record from syncmap
  289. if !errorExists {
  290. //This ended normally. Delete the targetPath
  291. rh.renderingFolder.Delete(targetPath)
  292. }
  293. c.Close()
  294. }
  295. //Check if the cache for a file exists
  296. func CacheExists(fsh *filesystem.FileSystemHandler, file string) bool {
  297. cacheFolder := filepath.ToSlash(filepath.Join(filepath.Clean(filepath.Dir(file)), "/.metadata/.cache/") + "/")
  298. return fsh.FileSystemAbstraction.FileExists(cacheFolder+filepath.Base(file)+".jpg") || fsh.FileSystemAbstraction.FileExists(cacheFolder+filepath.Base(file)+".png")
  299. }
  300. //Get cache path for this file, given realpath
  301. func GetCacheFilePath(fsh *filesystem.FileSystemHandler, file string) (string, error) {
  302. if CacheExists(fsh, file) {
  303. fshAbs := fsh.FileSystemAbstraction
  304. cacheFolder := filepath.ToSlash(filepath.Join(filepath.Clean(filepath.Dir(file)), "/.metadata/.cache/") + "/")
  305. if fshAbs.FileExists(cacheFolder + filepath.Base(file) + ".jpg") {
  306. return cacheFolder + filepath.Base(file) + ".jpg", nil
  307. } else if fshAbs.FileExists(cacheFolder + filepath.Base(file) + ".png") {
  308. return cacheFolder + filepath.Base(file) + ".png", nil
  309. } else {
  310. return "", errors.New("Unable to resolve thumbnail cache location")
  311. }
  312. } else {
  313. return "", errors.New("No thumbnail cached for this file")
  314. }
  315. }
  316. //Remove cache if exists, given realpath
  317. func RemoveCache(fsh *filesystem.FileSystemHandler, file string) error {
  318. if CacheExists(fsh, file) {
  319. cachePath, err := GetCacheFilePath(fsh, file)
  320. //log.Println("Removing ", cachePath, err)
  321. if err != nil {
  322. return err
  323. }
  324. //Remove the thumbnail cache
  325. os.Remove(cachePath)
  326. return nil
  327. } else {
  328. //log.Println("Cache not exists: ", file)
  329. return errors.New("Thumbnail cache not exists for this file")
  330. }
  331. }