KikkaMemory.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import os
  2. import json
  3. from Kikka.KikkaConst import *
  4. from Kikka.Utils.Singleton import singleton
  5. class Storageable():
  6. def toDict(self):
  7. raise NotImplementedError
  8. @singleton
  9. class KikkaMemory():
  10. def __init__(self):
  11. self._memory = None
  12. def awake(self):
  13. if os.path.exists(MEMORY_FILE):
  14. with open(MEMORY_FILE, "r", encoding="utf8") as fp:
  15. self._memory = json.load(fp)
  16. def storage(self):
  17. def data2dict(obj):
  18. if isinstance(obj, Storageable):
  19. return obj.toDict()
  20. json_str = json.dumps(self._memory, default=data2dict, ensure_ascii=False, indent=4)
  21. with open(MEMORY_FILE, mode="w", newline="", encoding="utf8") as fp:
  22. fp.write(json_str)
  23. def getAction(self):
  24. return self._memory.get("action", {})
  25. def updateAction(self, action_data):
  26. self._memory["action"] = action_data
  27. self.storage()
  28. def getConfig(self):
  29. return self._memory.get("config", {})
  30. def updateConfig(self, config_data):
  31. self._memory["config"] = config_data
  32. self.storage()