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.
 
 
 
 

173 lines
7.5 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. import argparse
  18. import locale
  19. import re
  20. import sys
  21. from datetime import date
  22. from termcolor import colored
  23. from . import dumper
  24. from . import core
  25. from . import events
  26. from .data import Position, EARTH
  27. from .exceptions import UnavailableFeatureError
  28. from .i18n import _
  29. from . import ephemerides
  30. from .version import VERSION
  31. def main():
  32. environment = core.get_env()
  33. output_formats = get_dumpers()
  34. args = get_args(list(output_formats.keys()))
  35. output_format = args.format
  36. if args.special_action is not None:
  37. return 0 if args.special_action() else 1
  38. try:
  39. compute_date = core.get_date(args.date)
  40. except ValueError as error:
  41. print(colored(error.args[0], color='red', attrs=['bold']))
  42. return -1
  43. position = None
  44. if args.latitude is not None or args.longitude is not None:
  45. position = Position(args.latitude, args.longitude, EARTH)
  46. elif environment.latitude is not None and environment.longitude is not None:
  47. position = Position(float(environment.latitude), float(environment.longitude), EARTH)
  48. if output_format == 'pdf':
  49. print(_('Save the planet and paper!\n'
  50. 'Consider printing you PDF document only if really necessary, and use the other side of the sheet.'))
  51. if position is None:
  52. print()
  53. print(colored(_("PDF output will not contain the ephemerides, because you didn't provide the observation "
  54. "coordinate."), 'yellow'))
  55. try:
  56. eph = ephemerides.get_ephemerides(date=compute_date, position=position) if position is not None else None
  57. moon_phase = ephemerides.get_moon_phase(compute_date)
  58. events_list = events.search_events(compute_date)
  59. timezone = args.timezone
  60. if timezone is None and environment.timezone is not None:
  61. timezone = int(environment.timezone)
  62. elif timezone is None:
  63. timezone = 0
  64. format_dumper = output_formats[output_format](ephemerides=eph, moon_phase=moon_phase, events=events_list,
  65. date=compute_date, timezone=timezone, with_colors=args.colors,
  66. show_graph=args.show_graph)
  67. output = format_dumper.to_string()
  68. except UnavailableFeatureError as error:
  69. print(colored(error.msg, 'red'))
  70. return 2
  71. if args.output is not None:
  72. try:
  73. with open(args.output, 'wb') as output_file:
  74. output_file.write(output)
  75. except OSError as error:
  76. print(_('Could not save the output in "{path}": {error}').format(path=args.output,
  77. error=error.strerror))
  78. elif not format_dumper.is_file_output_needed():
  79. print(output)
  80. else:
  81. print(colored(_('Selected output format needs an output file (--output).'), color='red'))
  82. return 1
  83. return 0
  84. def get_dumpers() -> {str: dumper.Dumper}:
  85. return {
  86. 'text': dumper.TextDumper,
  87. 'json': dumper.JsonDumper,
  88. 'pdf': dumper.PdfDumper,
  89. }
  90. def output_version() -> bool:
  91. python_version = '%d.%d.%d' % (sys.version_info[0], sys.version_info[1], sys.version_info[2])
  92. print('Kosmorro %s' % VERSION)
  93. print(_('Running on Python {python_version}').format(python_version=python_version))
  94. return True
  95. def clear_cache() -> bool:
  96. confirm = input(_("Do you really want to clear Kosmorro's cache? [yN] ")).upper()
  97. if re.match(locale.nl_langinfo(locale.YESEXPR), confirm) is not None:
  98. try:
  99. core.clear_cache()
  100. except FileNotFoundError:
  101. pass
  102. elif confirm != '' and re.match(locale.nl_langinfo(locale.NOEXPR), confirm) is None:
  103. print(_('Answer did not match expected options, cache not cleared.'))
  104. return False
  105. return True
  106. def get_args(output_formats: [str]):
  107. today = date.today()
  108. parser = argparse.ArgumentParser(description=_('Compute the ephemerides and the events for a given date,'
  109. ' at a given position on Earth.'),
  110. epilog=_('By default, only the events will be computed for today ({date}).\n'
  111. 'To compute also the ephemerides, latitude and longitude arguments'
  112. ' are needed.').format(date=today.strftime(dumper.FULL_DATE_FORMAT)))
  113. parser.add_argument('--version', '-v', dest='special_action', action='store_const', const=output_version,
  114. default=None, help=_('Show the program version'))
  115. parser.add_argument('--clear-cache', dest='special_action', action='store_const', const=clear_cache, default=None,
  116. help=_('Delete all the files Kosmorro stored in the cache.'))
  117. parser.add_argument('--format', '-f', type=str, default=output_formats[0], choices=output_formats,
  118. help=_('The format under which the information have to be output'))
  119. parser.add_argument('--latitude', '-lat', type=float, default=None,
  120. help=_("The observer's latitude on Earth. Can also be set in the KOSMORRO_LATITUDE environment "
  121. "variable."))
  122. parser.add_argument('--longitude', '-lon', type=float, default=None,
  123. help=_("The observer's longitude on Earth. Can also be set in the KOSMORRO_LONGITUDE "
  124. "environment variable."))
  125. parser.add_argument('--date', '-d', type=str, default=today.strftime('%Y-%m-%d'),
  126. help=_('The date for which the ephemerides must be computed (in the YYYY-MM-DD format). '
  127. 'Defaults to the current date ({default_date})').format(
  128. default_date=today.strftime('%Y-%m-%d')))
  129. parser.add_argument('--timezone', '-t', type=int, default=None,
  130. help=_('The timezone to display the hours in (e.g. 2 for UTC+2 or -3 for UTC-3). '
  131. 'Can also be set in the KOSMORRO_TIMEZONE environment variable.'))
  132. parser.add_argument('--no-colors', dest='colors', action='store_false',
  133. help=_('Disable the colors in the console.'))
  134. parser.add_argument('--output', '-o', type=str, default=None,
  135. help=_('A file to export the output to. If not given, the standard output is used. '
  136. 'This argument is needed for PDF format.'))
  137. parser.add_argument('--no-graph', dest='show_graph', action='store_false',
  138. help=_('Generate a graph instead of a table to show the rise, culmination set times '
  139. '(PDF only)'))
  140. return parser.parse_args()