main.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import source
  2. import config
  3. from event import Event, HeapEvent
  4. from datetime import datetime, timedelta
  5. from time import sleep
  6. import notification
  7. from analyse_event import *
  8. def make_tz_aware(dt, tz='UTC', is_dst=None):
  9. """Add timezone information to a datetime object, only if it is naive."""
  10. tz = dt.tzinfo or tz
  11. try:
  12. tz = pytz.timezone(tz)
  13. except AttributeError:
  14. pass
  15. return tz.localize(dt, is_dst=is_dst)
  16. def main():
  17. event_seen = set()
  18. heap = HeapEvent()
  19. manual = [Event('manual_1', datetime.now()+timedelta(minutes=30, seconds=10), "Villejuif", "descr Villejuif"),
  20. Event('manual_2', datetime.now()+timedelta(minutes=30, seconds=3), "Cachan", "descr Cachan"),
  21. Event('manual_3', datetime.now()+timedelta(minutes=30, seconds=12), "université paris 7", "descr p7")]
  22. gap = timedelta(minutes=30) # 30 minutes : time to check trafic before an event
  23. refresh = timedelta(seconds=30) # grab events every 30 secondes
  24. while True:
  25. # feed heap
  26. for event in get_events() + manual:
  27. # check if we already know it
  28. if event.id not in event_seen:
  29. event_seen.add(event.id)
  30. print()
  31. if (event.date - datetime.now()).total_seconds() < 0:
  32. print("Ignore event in the past:")
  33. else:
  34. print("Add event:")
  35. heap.push(event)
  36. print(str(event))
  37. # sleep the min between 1 minute and the next event - gap
  38. next = refresh
  39. if not heap.empty():
  40. next = min(next, heap.top().date-datetime.now()-gap)
  41. if next.total_seconds() > 0:
  42. print()
  43. print("Sleeping " + str(next))
  44. sleep(next.total_seconds())
  45. # next event
  46. if not heap.empty() and heap.top().date-datetime.now() < gap:
  47. event = heap.pop()
  48. print()
  49. print("Check event:")
  50. print(str(event))
  51. # get useful ids of sources for this location
  52. ids_sources = source.from_location(event.location)
  53. # flatten this dictionary
  54. ids_sources_flat = [item for (key, sublist) in ids_sources.items() for item in sublist]
  55. # grab info from internet for these sources
  56. sources=source.gen_sources(ids_sources)
  57. if 'print' in config.notification['methods']:
  58. print() # show an empty line
  59. for src in sources:
  60. if src.id in ids_sources_flat and src.problem():
  61. # there is a problem ! We notify the user...
  62. notification.notify(src.message)
  63. if __name__ == "__main__":
  64. main()