metadata.go 10 KB

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