storage.lua 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. -- TODO: maybe local cache?
  2. function mail.getMailFile(playername)
  3. local saneplayername = string.gsub(playername, "[.|/]", "")
  4. return mail.maildir .. "/" .. saneplayername .. ".json"
  5. end
  6. function mail.getContactsFile(playername)
  7. local saneplayername = string.gsub(playername, "[.|/]", "")
  8. return mail.maildir .. "/contacts/" .. saneplayername .. ".json"
  9. end
  10. mail.getMessages = function(playername)
  11. local messages = mail.read_json_file(mail.getMailFile(playername))
  12. --if messages then
  13. -- mail.hud_update(playername, messages)
  14. --end
  15. return messages
  16. end
  17. mail.setMessages = function(playername, messages)
  18. if mail.write_json_file(mail.getMailFile(playername), messages) then
  19. -- mail.hud_update(playername, messages)
  20. return true
  21. else
  22. minetest.log("error","[mail] Save failed - messages may be lost! ("..playername..")")
  23. return false
  24. end
  25. end
  26. mail.getContacts = function(playername)
  27. return mail.read_json_file(mail.getContactsFile(playername))
  28. end
  29. function mail.pairsByKeys(t, f)
  30. -- http://www.lua.org/pil/19.3.html
  31. local a = {}
  32. for n in pairs(t) do table.insert(a, n) end
  33. table.sort(a, f)
  34. local i = 0 -- iterator variable
  35. local iter = function() -- iterator function
  36. i = i + 1
  37. if a[i] == nil then
  38. return nil
  39. else
  40. --return a[i], t[a[i]]
  41. -- add the current position and the length for convenience
  42. return a[i], t[a[i]], i, #a
  43. end
  44. end
  45. return iter
  46. end
  47. mail.setContacts = function(playername, contacts)
  48. if mail.write_json_file(mail.getContactsFile(playername), contacts) then
  49. return true
  50. else
  51. minetest.log("error","[mail] Save failed - contacts may be lost! ("..playername..")")
  52. return false
  53. end
  54. end
  55. function mail.read_json_file(path)
  56. local file = io.open(path, "r")
  57. local content = {}
  58. if file then
  59. local json = file:read("*a")
  60. content = minetest.parse_json(json or "[]") or {}
  61. file:close()
  62. end
  63. return content
  64. end
  65. function mail.write_json_file(path, content)
  66. local file = io.open(path,"w")
  67. local json = minetest.write_json(content)
  68. if file and file:write(json) and file:close() then
  69. return true
  70. else
  71. return false
  72. end
  73. end