NotificationManager.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import warnings
  2. from functools import partial
  3. from socketio import Server
  4. from typing import Callable
  5. from pycs import app
  6. from pycs.database.File import File
  7. from pycs.database.Label import Label
  8. from pycs.database.Model import Model
  9. from pycs.database.Project import Project
  10. from pycs.database.Result import Result
  11. from pycs.frontend.util.JSONEncoder import JSONEncoder
  12. from pycs.jobs.Job import Job
  13. from pycs.util import Singleton
  14. class NotificationManager(Singleton):
  15. """
  16. send events via a socket.io connection
  17. """
  18. def __repr__(self) -> str:
  19. return f"<{self.__class__.__name__} 0x{id(self):x}>"
  20. def setup(self, sio: Server):
  21. self.sio = sio
  22. def init(self):
  23. self.sio = None
  24. self.json = JSONEncoder()
  25. def __call__(self, name, obj_id, cls=None):
  26. if self.sio is None:
  27. warnings.warn("NotificationManager was called before a setup was performed!")
  28. return
  29. if cls is not None:
  30. assert isinstance(obj_id, int), \
  31. f"{cls.__name__} ID must be an integer, but was {type(obj_id)} ({obj_id=})!"
  32. obj = cls.query.get(obj_id)
  33. else:
  34. obj = obj_id
  35. assert obj is not None, "Object was unexpectedly None!"
  36. app.logger.debug(f"{name}: {obj}")
  37. enc = self.json.default(obj)
  38. self.sio.emit(name, enc)
  39. def _new_signal(self, signal_name, suffix, *args, **kwargs):
  40. return partial(self, f'{signal_name}-{suffix}', *args, **kwargs)
  41. def create(self, suffix, *args, **kwargs) -> Callable:
  42. return self._new_signal('create', suffix, *args, **kwargs)
  43. def edit(self, suffix, *args, **kwargs) -> Callable:
  44. return self._new_signal('edit', suffix, *args, **kwargs)
  45. def remove(self, suffix, *args, **kwargs) -> Callable:
  46. return self._new_signal('remove', suffix, *args, **kwargs)
  47. @classmethod
  48. def removed(kls, suffix, *args, **kwargs):
  49. return kls().remove(suffix)(*args, **kwargs)
  50. @classmethod
  51. def edited(kls, suffix, *args, **kwargs):
  52. return kls().edit(suffix)(*args, **kwargs)
  53. @classmethod
  54. def created(kls, suffix, *args, **kwargs):
  55. return kls().create(suffix)(*args, **kwargs)