2
0

screenshots.lua 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. --Minetest
  2. --Copyright (C) 2023-24 rubenwardy
  3. --
  4. --This program is free software; you can redistribute it and/or modify
  5. --it under the terms of the GNU Lesser General Public License as published by
  6. --the Free Software Foundation; either version 2.1 of the License, or
  7. --(at your option) any later version.
  8. --
  9. --This program is distributed in the hope that it will be useful,
  10. --but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. --GNU Lesser General Public License for more details.
  13. --
  14. --You should have received a copy of the GNU Lesser General Public License along
  15. --with this program; if not, write to the Free Software Foundation, Inc.,
  16. --51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  17. -- Screenshot
  18. local screenshot_dir = core.get_cache_path() .. DIR_DELIM .. "cdb"
  19. assert(core.create_dir(screenshot_dir))
  20. local screenshot_downloading = {}
  21. local screenshot_downloaded = {}
  22. local function get_file_extension(path)
  23. local parts = path:split(".")
  24. return parts[#parts]
  25. end
  26. function get_screenshot(package)
  27. if not package.thumbnail then
  28. return defaulttexturedir .. "no_screenshot.png"
  29. elseif screenshot_downloading[package.thumbnail] then
  30. return defaulttexturedir .. "loading_screenshot.png"
  31. end
  32. -- Get tmp screenshot path
  33. local ext = get_file_extension(package.thumbnail)
  34. local filepath = screenshot_dir .. DIR_DELIM ..
  35. ("%s-%s-%s.%s"):format(package.type, package.author, package.name, ext)
  36. -- Return if already downloaded
  37. local file = io.open(filepath, "r")
  38. if file then
  39. file:close()
  40. return filepath
  41. end
  42. -- Show error if we've failed to download before
  43. if screenshot_downloaded[package.thumbnail] then
  44. return defaulttexturedir .. "error_screenshot.png"
  45. end
  46. -- Download
  47. local function download_screenshot(params)
  48. return core.download_file(params.url, params.dest)
  49. end
  50. local function callback(success)
  51. screenshot_downloading[package.thumbnail] = nil
  52. screenshot_downloaded[package.thumbnail] = true
  53. if not success then
  54. core.log("warning", "Screenshot download failed for some reason")
  55. end
  56. ui.update()
  57. end
  58. if core.handle_async(download_screenshot,
  59. { dest = filepath, url = package.thumbnail }, callback) then
  60. screenshot_downloading[package.thumbnail] = true
  61. else
  62. core.log("error", "ERROR: async event failed")
  63. return defaulttexturedir .. "error_screenshot.png"
  64. end
  65. return defaulttexturedir .. "loading_screenshot.png"
  66. end