metadata.go 9.8 KB

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