You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

154 lines
5.6 KiB

  1. #!/usr/bin/env python3
  2. # Kosmorro - Compute The Next Ephemerides
  3. # Copyright (C) 2019 Jérôme Deuchnord <jerome@deuchnord.fr>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU Affero General Public License as
  7. # published by the Free Software Foundation, either version 3 of the
  8. # License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU Affero General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU Affero General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. from abc import ABC, abstractmethod
  18. import datetime
  19. import json
  20. from tabulate import tabulate
  21. from skyfield.timelib import Time
  22. from numpy import int64
  23. from .data import Object, AsterEphemerides, MoonPhase, Event
  24. from .i18n import _
  25. FULL_DATE_FORMAT = _('{day_of_week} {month} {day_number}, {year}').format(day_of_week='%A', month='%B',
  26. day_number='%d', year='%Y')
  27. TIME_FORMAT = _('{hours}:{minutes}').format(hours='%H', minutes='%M')
  28. class Dumper(ABC):
  29. def __init__(self, ephemeris: dict, events: [Event], date: datetime.date = datetime.date.today()):
  30. self.ephemeris = ephemeris
  31. self.events = events
  32. self.date = date
  33. @abstractmethod
  34. def to_string(self):
  35. pass
  36. class JsonDumper(Dumper):
  37. def to_string(self):
  38. self.ephemeris['events'] = self.events
  39. self.ephemeris['ephemerides'] = self.ephemeris.pop('details')
  40. return json.dumps(self.ephemeris,
  41. default=self._json_default,
  42. indent=4)
  43. @staticmethod
  44. def _json_default(obj):
  45. # Fixes the "TypeError: Object of type int64 is not JSON serializable"
  46. # See https://stackoverflow.com/a/50577730
  47. if isinstance(obj, int64):
  48. return int(obj)
  49. if isinstance(obj, Time):
  50. return obj.utc_iso()
  51. if isinstance(obj, Object):
  52. obj = obj.__dict__
  53. obj.pop('skyfield_name')
  54. obj['object'] = obj.pop('name')
  55. obj['details'] = obj.pop('ephemerides')
  56. return obj
  57. if isinstance(obj, AsterEphemerides):
  58. return obj.__dict__
  59. if isinstance(obj, MoonPhase):
  60. moon_phase = obj.__dict__
  61. moon_phase['phase'] = moon_phase.pop('identifier')
  62. moon_phase['date'] = moon_phase.pop('time')
  63. return moon_phase
  64. if isinstance(obj, Event):
  65. event = obj.__dict__
  66. event['objects'] = [object.name for object in event['objects']]
  67. return event
  68. raise TypeError('Object of type "%s" could not be integrated in the JSON' % str(type(obj)))
  69. class TextDumper(Dumper):
  70. def to_string(self):
  71. text = self.date.strftime(FULL_DATE_FORMAT)
  72. # Always capitalize the first character
  73. text = ''.join([text[0].upper(), text[1:]])
  74. if len(self.ephemeris['details']) > 0:
  75. text = '\n\n'.join([text,
  76. self.get_asters(self.ephemeris['details'])
  77. ])
  78. text = '\n\n'.join([text,
  79. self.get_moon(self.ephemeris['moon_phase'])
  80. ])
  81. if len(self.events) > 0:
  82. text = '\n\n'.join([text,
  83. _('Expected events:'),
  84. self.get_events(self.events)
  85. ])
  86. text = '\n\n'.join([text, _('Note: All the hours are given in UTC.')])
  87. return text
  88. @staticmethod
  89. def get_asters(asters: [Object]) -> str:
  90. data = []
  91. for aster in asters:
  92. name = aster.name
  93. if aster.ephemerides.rise_time is not None:
  94. planet_rise = aster.ephemerides.rise_time.utc_strftime(TIME_FORMAT)
  95. else:
  96. planet_rise = '-'
  97. if aster.ephemerides.culmination_time is not None:
  98. planet_culmination = aster.ephemerides.culmination_time.utc_strftime(TIME_FORMAT)
  99. else:
  100. planet_culmination = '-'
  101. if aster.ephemerides.set_time is not None:
  102. planet_set = aster.ephemerides.set_time.utc_strftime(TIME_FORMAT)
  103. else:
  104. planet_set = '-'
  105. data.append([name, planet_rise, planet_culmination, planet_set])
  106. return tabulate(data, headers=[_('Object'), _('Rise time'), _('Culmination time'), _('Set time')],
  107. tablefmt='simple', stralign='center', colalign=('left',))
  108. @staticmethod
  109. def get_events(events: [Event]) -> str:
  110. data = []
  111. for event in events:
  112. data.append([event.start_time.utc_strftime(TIME_FORMAT), event.get_description()])
  113. return tabulate(data, tablefmt='plain', stralign='left')
  114. @staticmethod
  115. def get_moon(moon_phase: MoonPhase) -> str:
  116. current_moon_phase = _('Moon phase: {current_moon_phase}').format(
  117. current_moon_phase=moon_phase.get_phase()
  118. )
  119. new_moon_phase = _('{next_moon_phase} on {next_moon_phase_date} at {next_moon_phase_time}').format(
  120. next_moon_phase=moon_phase.get_next_phase(),
  121. next_moon_phase_date=moon_phase.next_phase_date.utc_strftime(FULL_DATE_FORMAT),
  122. next_moon_phase_time=moon_phase.next_phase_date.utc_strftime(TIME_FORMAT)
  123. )
  124. return '\n'.join([current_moon_phase, new_moon_phase])