utils.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. # Copyright: (c) OpenSpug Organization. https://github.com/openspug/spug
  2. # Copyright: (c) <spug.dev@gmail.com>
  3. # Released under the AGPL-3.0 License.
  4. from django.db import close_old_connections
  5. from apps.alarm.models import Alarm
  6. from apps.monitor.models import Detection
  7. from libs.spug import Notification
  8. import json
  9. def seconds_to_human(seconds):
  10. text = ''
  11. if seconds > 3600:
  12. text = f'{int(seconds / 3600)}小时'
  13. seconds = seconds % 3600
  14. if seconds > 60:
  15. text += f'{int(seconds / 60)}分钟'
  16. seconds = seconds % 60
  17. if seconds:
  18. text += f'{seconds}秒'
  19. return text
  20. def _record_alarm(det, target, duration, status):
  21. Alarm.objects.create(
  22. name=det.name,
  23. type=det.get_type_display(),
  24. target=target,
  25. status=status,
  26. duration=duration,
  27. notify_grp=det.notify_grp,
  28. notify_mode=det.notify_mode)
  29. def handle_notify(task_id, target, is_ok, out, fault_times):
  30. close_old_connections()
  31. det = Detection.objects.get(pk=task_id)
  32. duration = seconds_to_human(det.rate * fault_times * 60)
  33. event = '2' if is_ok else '1'
  34. _record_alarm(det, target, duration, event)
  35. grp = json.loads(det.notify_grp)
  36. notify = Notification(grp, event, target, det.name, out, duration)
  37. notify.dispatch(json.loads(det.notify_mode))