metadata.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  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. //Audio formats that might contains id4 thumbnail
  108. id4Formats := []string{".mp3", ".ogg", ".flac"}
  109. if inArray(id4Formats, strings.ToLower(filepath.Ext(file))) {
  110. img, err := generateThumbnailForAudio(cacheFolder, file, generateOnly)
  111. rh.renderingFiles.Delete(file)
  112. return img, err
  113. }
  114. //Generate resized image for images
  115. imageFormats := []string{".png", ".jpeg", ".jpg"}
  116. if inArray(imageFormats, strings.ToLower(filepath.Ext(file))) {
  117. img, err := generateThumbnailForImage(cacheFolder, file, generateOnly)
  118. rh.renderingFiles.Delete(file)
  119. return img, err
  120. }
  121. //Video formats, extract from the 5 sec mark
  122. vidFormats := []string{".mkv", ".mp4", ".webm", ".ogv", ".avi", ".rmvb"}
  123. if inArray(vidFormats, strings.ToLower(filepath.Ext(file))) {
  124. img, err := generateThumbnailForVideo(cacheFolder, file, generateOnly)
  125. rh.renderingFiles.Delete(file)
  126. return img, err
  127. }
  128. //3D Model Formats
  129. modelFormats := []string{".stl", ".obj"}
  130. if inArray(modelFormats, strings.ToLower(filepath.Ext(file))) {
  131. img, err := generateThumbnailForModel(cacheFolder, file, generateOnly)
  132. rh.renderingFiles.Delete(file)
  133. return img, err
  134. }
  135. //Photoshop file
  136. if strings.ToLower(filepath.Ext(file)) == ".psd" {
  137. img, err := generateThumbnailForPSD(cacheFolder, file, generateOnly)
  138. rh.renderingFiles.Delete(file)
  139. return img, err
  140. }
  141. //Folder preview renderer
  142. if isDir(file) && len(filepath.Base(file)) > 0 && filepath.Base(file)[:1] != "." {
  143. img, err := generateThumbnailForFolder(cacheFolder, file, generateOnly)
  144. rh.renderingFiles.Delete(file)
  145. return img, err
  146. }
  147. //Other filters
  148. rh.renderingFiles.Delete(file)
  149. return "", errors.New("No supported format")
  150. }
  151. func (rh *RenderHandler) fileIsBusy(path string) bool {
  152. if rh == nil {
  153. log.Println("RenderHandler is null!")
  154. return true
  155. }
  156. _, ok := rh.renderingFiles.Load(path)
  157. if !ok {
  158. //File path is not being process by another process
  159. return false
  160. } else {
  161. return true
  162. }
  163. }
  164. func getImageAsBase64(path string) (string, error) {
  165. f, err := os.Open(path)
  166. if err != nil {
  167. return "", err
  168. }
  169. //Added Seek to 0,0 function to prevent failed to decode: Unexpected EOF error
  170. f.Seek(0, 0)
  171. reader := bufio.NewReader(f)
  172. content, err := ioutil.ReadAll(reader)
  173. if err != nil {
  174. return "", err
  175. }
  176. encoded := base64.StdEncoding.EncodeToString(content)
  177. f.Close()
  178. return string(encoded), nil
  179. }
  180. //Load a list of folder cache from websocket, pass in "" (empty string) for default sorting method
  181. func (rh *RenderHandler) HandleLoadCache(w http.ResponseWriter, r *http.Request, rpath string, sortmode string) {
  182. //Get a list of files pending to be cached and sent
  183. targetPath := filepath.ToSlash(filepath.Clean(rpath))
  184. //Check if this path already exists another websocket ongoing connection.
  185. //If yes, disconnect the oldone
  186. oldc, ok := rh.renderingFolder.Load(targetPath)
  187. if ok {
  188. //Close and remove the old connection
  189. oldc.(*websocket.Conn).Close()
  190. }
  191. files, err := specialGlob(targetPath + "/*")
  192. if err != nil {
  193. w.WriteHeader(http.StatusInternalServerError)
  194. w.Write([]byte("500 - Internal Server Error"))
  195. return
  196. }
  197. //Upgrade the connection to websocket
  198. var upgrader = websocket.Upgrader{}
  199. upgrader.CheckOrigin = func(r *http.Request) bool { return true }
  200. c, err := upgrader.Upgrade(w, r, nil)
  201. if err != nil {
  202. log.Print("upgrade:", err)
  203. w.WriteHeader(http.StatusInternalServerError)
  204. w.Write([]byte("500 - Internal Server Error"))
  205. return
  206. }
  207. //Set this realpath as websocket connected
  208. rh.renderingFolder.Store(targetPath, c)
  209. //For each file, serve a cached image preview
  210. errorExists := false
  211. filesWithoutCache := []string{}
  212. //Updates implementation 02/10/2021: Load thumbnail of files first before folder and apply user preference sort mode
  213. if sortmode == "" {
  214. sortmode = "default"
  215. }
  216. pendingFiles := []string{}
  217. pendingFolders := []string{}
  218. for _, file := range files {
  219. if isDir(file) {
  220. pendingFiles = append(pendingFiles, file)
  221. } else {
  222. pendingFolders = append(pendingFolders, file)
  223. }
  224. }
  225. pendingFiles = append(pendingFiles, pendingFolders...)
  226. files = fssort.SortFileList(pendingFiles, sortmode)
  227. //Updated implementation 24/12/2020: Load image with cache first before rendering those without
  228. for _, file := range files {
  229. if !CacheExists(file) {
  230. //Cache not exists. Render this later
  231. filesWithoutCache = append(filesWithoutCache, file)
  232. } else {
  233. //Cache exists. Send it out first
  234. cachedImage, err := rh.LoadCache(file, false)
  235. if err != nil {
  236. } else {
  237. jsonString, _ := json.Marshal([]string{filepath.Base(file), cachedImage})
  238. err := c.WriteMessage(1, jsonString)
  239. if err != nil {
  240. //Connection closed
  241. errorExists = true
  242. break
  243. }
  244. }
  245. }
  246. }
  247. retryList := []string{}
  248. //Render the remaining cache files
  249. for _, file := range filesWithoutCache {
  250. //Load the image cache
  251. cachedImage, err := rh.LoadCache(file, false)
  252. if err != nil {
  253. //Unable to load this file's cache. Push it to retry list
  254. retryList = append(retryList, file)
  255. } else {
  256. jsonString, _ := json.Marshal([]string{filepath.Base(file), cachedImage})
  257. err := c.WriteMessage(1, jsonString)
  258. if err != nil {
  259. //Connection closed
  260. errorExists = true
  261. break
  262. }
  263. }
  264. }
  265. //Process the retry list after some wait time
  266. if len(retryList) > 0 {
  267. time.Sleep(1000 * time.Millisecond)
  268. for _, file := range retryList {
  269. //Load the image cache
  270. cachedImage, err := rh.LoadCache(file, false)
  271. if err != nil {
  272. } else {
  273. jsonString, _ := json.Marshal([]string{filepath.Base(file), cachedImage})
  274. err := c.WriteMessage(1, jsonString)
  275. if err != nil {
  276. //Connection closed
  277. errorExists = true
  278. break
  279. }
  280. }
  281. }
  282. }
  283. //Clear record from syncmap
  284. if !errorExists {
  285. //This ended normally. Delete the targetPath
  286. rh.renderingFolder.Delete(targetPath)
  287. }
  288. c.Close()
  289. }
  290. //Check if the cache for a file exists
  291. func CacheExists(file string) bool {
  292. cacheFolder := filepath.ToSlash(filepath.Clean(filepath.Dir(file))) + "/.cache/"
  293. return fileExists(cacheFolder+filepath.Base(file)+".jpg") || fileExists(cacheFolder+filepath.Base(file)+".png")
  294. }
  295. //Get cache path for this file, given realpath
  296. func GetCacheFilePath(file string) (string, error) {
  297. if CacheExists(file) {
  298. cacheFolder := filepath.ToSlash(filepath.Clean(filepath.Dir(file))) + "/.cache/"
  299. if fileExists(cacheFolder + filepath.Base(file) + ".jpg") {
  300. return cacheFolder + filepath.Base(file) + ".jpg", nil
  301. } else if fileExists(cacheFolder + filepath.Base(file) + ".png") {
  302. return cacheFolder + filepath.Base(file) + ".png", nil
  303. } else {
  304. return "", errors.New("Unable to resolve thumbnail cache location")
  305. }
  306. } else {
  307. return "", errors.New("No thumbnail cached for this file")
  308. }
  309. }
  310. //Remove cache if exists, given realpath
  311. func RemoveCache(file string) error {
  312. if CacheExists(file) {
  313. cachePath, err := GetCacheFilePath(file)
  314. //log.Println("Removing ", cachePath, err)
  315. if err != nil {
  316. return err
  317. }
  318. //Remove the thumbnail cache
  319. os.Remove(cachePath)
  320. return nil
  321. } else {
  322. //log.Println("Cache not exists: ", file)
  323. return errors.New("Thumbnail cache not exists for this file")
  324. }
  325. }
  326. func specialGlob(path string) ([]string, error) {
  327. files, err := filepath.Glob(path)
  328. if err != nil {
  329. return []string{}, err
  330. }
  331. if strings.Contains(path, "[") == true || strings.Contains(path, "]") == true {
  332. if len(files) == 0 {
  333. //Handle reverse check. Replace all [ and ] with *
  334. newSearchPath := strings.ReplaceAll(path, "[", "?")
  335. newSearchPath = strings.ReplaceAll(newSearchPath, "]", "?")
  336. //Scan with all the similar structure except [ and ]
  337. tmpFilelist, _ := filepath.Glob(newSearchPath)
  338. for _, file := range tmpFilelist {
  339. file = filepath.ToSlash(file)
  340. if strings.Contains(file, filepath.ToSlash(filepath.Dir(path))) {
  341. files = append(files, file)
  342. }
  343. }
  344. }
  345. }
  346. //Convert all filepaths to slash
  347. for i := 0; i < len(files); i++ {
  348. files[i] = filepath.ToSlash(files[i])
  349. }
  350. return files, nil
  351. }