timetable_calendar.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from PyQt5.QtCore import *
  2. from copy import copy
  3. from typing import *
  4. import json
  5. import os
  6. _file_path = 'calendar.json'
  7. _loaded = False
  8. _calendar: Dict[QDate, int] = {}
  9. def _save_calendar() -> None:
  10. global _calendar, _file_path
  11. serialized_calendar = {}
  12. for key, value in _calendar.items():
  13. new_key = f'{key.year()}.{key.month()}.{key.day()}'
  14. serialized_calendar[new_key] = value
  15. try:
  16. file = open(_file_path, 'w+')
  17. json.dump(serialized_calendar, file, ensure_ascii=False, indent=4, sort_keys=True)
  18. file.close()
  19. except Exception as exception:
  20. print('Ошибка сохранения календаря!')
  21. print(exception.with_traceback(None))
  22. def _load_calendar() -> None:
  23. global _loaded, _file_path, _calendar
  24. if _loaded:
  25. return
  26. _calendar = {}
  27. _loaded = True
  28. if not os.path.exists(_file_path):
  29. return
  30. try:
  31. file = open(_file_path, 'r', encoding='utf-8')
  32. raw_calendar = json.load(file)
  33. file.close()
  34. except Exception as exception:
  35. return
  36. _calendar = {}
  37. for key, value in raw_calendar.items():
  38. year, month, day = (int(x) for x in key.split('.'))
  39. new_key = QDate(year, month, day)
  40. _calendar[new_key] = value
  41. def set_profile(date: QDate, profile_id: int) -> None:
  42. global _calendar
  43. _load_calendar()
  44. _calendar[date] = profile_id
  45. _save_calendar()
  46. def notify_profile_removal(profile_id: int) -> None:
  47. global _calendar
  48. _load_calendar()
  49. _calendar = {key: value for key, value in _calendar.items() if value != profile_id}
  50. _save_calendar()
  51. def get_calendar() -> Dict[QDate, int]:
  52. global _calendar
  53. _load_calendar()
  54. return copy(_calendar)
  55. def get_profile_id(date: QDate) -> Union[int, None]:
  56. global _calendar
  57. _load_calendar()
  58. return _calendar.get(date)
  59. def clear_profile(date: QDate) -> None:
  60. global _calendar
  61. _load_calendar()
  62. _calendar = {key: value for key, value in _calendar.items() if key != date}
  63. _save_calendar()