metadata.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. //Added Seek to 0,0 function to prevent failed to decode: Unexpected EOF error
  161. f.Seek(0, 0)
  162. reader := bufio.NewReader(f)
  163. content, err := ioutil.ReadAll(reader)
  164. if err != nil {
  165. return "", err
  166. }
  167. encoded := base64.StdEncoding.EncodeToString(content)
  168. f.Close()
  169. return string(encoded), nil
  170. }
  171. //Load a list of folder cache from websocket, pass in "" (empty string) for default sorting method
  172. func (rh *RenderHandler) HandleLoadCache(w http.ResponseWriter, r *http.Request, rpath string, sortmode string) {
  173. //Get a list of files pending to be cached and sent
  174. targetPath := filepath.ToSlash(filepath.Clean(rpath))
  175. //Check if this path already exists another websocket ongoing connection.
  176. //If yes, disconnect the oldone
  177. oldc, ok := rh.renderingFolder.Load(targetPath)
  178. if ok {
  179. //Close and remove the old connection
  180. oldc.(*websocket.Conn).Close()
  181. }
  182. files, err := specialGlob(targetPath + "/*")
  183. if err != nil {
  184. w.WriteHeader(http.StatusInternalServerError)
  185. w.Write([]byte("500 - Internal Server Error"))
  186. return
  187. }
  188. //Upgrade the connection to websocket
  189. var upgrader = websocket.Upgrader{}
  190. upgrader.CheckOrigin = func(r *http.Request) bool { return true }
  191. c, err := upgrader.Upgrade(w, r, nil)
  192. if err != nil {
  193. log.Print("upgrade:", err)
  194. w.WriteHeader(http.StatusInternalServerError)
  195. w.Write([]byte("500 - Internal Server Error"))
  196. return
  197. }
  198. //Set this realpath as websocket connected
  199. rh.renderingFolder.Store(targetPath, c)
  200. //For each file, serve a cached image preview
  201. errorExists := false
  202. filesWithoutCache := []string{}
  203. //Updates implementation 02/10/2021: Load thumbnail of files first before folder and apply user preference sort mode
  204. if sortmode == "" {
  205. sortmode = "default"
  206. }
  207. pendingFiles := []string{}
  208. pendingFolders := []string{}
  209. for _, file := range files {
  210. if isDir(file) {
  211. pendingFiles = append(pendingFiles, file)
  212. } else {
  213. pendingFolders = append(pendingFolders, file)
  214. }
  215. }
  216. pendingFiles = append(pendingFiles, pendingFolders...)
  217. files = fssort.SortFileList(pendingFiles, sortmode)
  218. //Updated implementation 24/12/2020: Load image with cache first before rendering those without
  219. for _, file := range files {
  220. if CacheExists(file) == false {
  221. //Cache not exists. Render this later
  222. filesWithoutCache = append(filesWithoutCache, file)
  223. } else {
  224. //Cache exists. Send it out first
  225. cachedImage, err := rh.LoadCache(file, false)
  226. if err != nil {
  227. } else {
  228. jsonString, _ := json.Marshal([]string{filepath.Base(file), cachedImage})
  229. err := c.WriteMessage(1, jsonString)
  230. if err != nil {
  231. //Connection closed
  232. errorExists = true
  233. break
  234. }
  235. }
  236. }
  237. }
  238. //Render the remaining cache files
  239. for _, file := range filesWithoutCache {
  240. //Load the image cache
  241. cachedImage, err := rh.LoadCache(file, false)
  242. if err != nil {
  243. } else {
  244. jsonString, _ := json.Marshal([]string{filepath.Base(file), cachedImage})
  245. err := c.WriteMessage(1, jsonString)
  246. if err != nil {
  247. //Connection closed
  248. errorExists = true
  249. break
  250. }
  251. }
  252. }
  253. //Clear record from syncmap
  254. if !errorExists {
  255. //This ended normally. Delete the targetPath
  256. rh.renderingFolder.Delete(targetPath)
  257. }
  258. c.Close()
  259. }
  260. //Check if the cache for a file exists
  261. func CacheExists(file string) bool {
  262. cacheFolder := filepath.ToSlash(filepath.Clean(filepath.Dir(file))) + "/.cache/"
  263. return fileExists(cacheFolder+filepath.Base(file)+".jpg") || fileExists(cacheFolder+filepath.Base(file)+".png")
  264. }
  265. //Get cache path for this file, given realpath
  266. func GetCacheFilePath(file string) (string, error) {
  267. if CacheExists(file) {
  268. cacheFolder := filepath.ToSlash(filepath.Clean(filepath.Dir(file))) + "/.cache/"
  269. if fileExists(cacheFolder + filepath.Base(file) + ".jpg") {
  270. return cacheFolder + filepath.Base(file) + ".jpg", nil
  271. } else if fileExists(cacheFolder + filepath.Base(file) + ".png") {
  272. return cacheFolder + filepath.Base(file) + ".png", nil
  273. } else {
  274. return "", errors.New("Unable to resolve thumbnail cache location")
  275. }
  276. } else {
  277. return "", errors.New("No thumbnail cached for this file")
  278. }
  279. }
  280. //Remove cache if exists, given realpath
  281. func RemoveCache(file string) error {
  282. if CacheExists(file) {
  283. cachePath, err := GetCacheFilePath(file)
  284. //log.Println("Removing ", cachePath, err)
  285. if err != nil {
  286. return err
  287. }
  288. //Remove the thumbnail cache
  289. os.Remove(cachePath)
  290. return nil
  291. } else {
  292. //log.Println("Cache not exists: ", file)
  293. return errors.New("Thumbnail cache not exists for this file")
  294. }
  295. }
  296. func specialGlob(path string) ([]string, error) {
  297. files, err := filepath.Glob(path)
  298. if err != nil {
  299. return []string{}, err
  300. }
  301. if strings.Contains(path, "[") == true || strings.Contains(path, "]") == true {
  302. if len(files) == 0 {
  303. //Handle reverse check. Replace all [ and ] with *
  304. newSearchPath := strings.ReplaceAll(path, "[", "?")
  305. newSearchPath = strings.ReplaceAll(newSearchPath, "]", "?")
  306. //Scan with all the similar structure except [ and ]
  307. tmpFilelist, _ := filepath.Glob(newSearchPath)
  308. for _, file := range tmpFilelist {
  309. file = filepath.ToSlash(file)
  310. if strings.Contains(file, filepath.ToSlash(filepath.Dir(path))) {
  311. files = append(files, file)
  312. }
  313. }
  314. }
  315. }
  316. //Convert all filepaths to slash
  317. for i := 0; i < len(files); i++ {
  318. files[i] = filepath.ToSlash(files[i])
  319. }
  320. return files, nil
  321. }