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.
 
 
 
 

159 line
6.8 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 kosmorrolib.version import VERSION
  24. from kosmorrolib import dumper
  25. from kosmorrolib import core
  26. from kosmorrolib import events
  27. from kosmorrolib.i18n import _
  28. from .ephemerides import EphemeridesComputer, Position
  29. from .exceptions import UnavailableFeatureError
  30. def main():
  31. output_formats = get_dumpers()
  32. args = get_args(list(output_formats.keys()))
  33. if args.special_action is not None:
  34. return 0 if args.special_action() else 1
  35. year = args.year
  36. month = args.month
  37. day = args.day
  38. compute_date = date(year, month, day)
  39. if day is not None and month is None:
  40. month = date.today().month
  41. if args.latitude is None or args.longitude is None:
  42. position = None
  43. else:
  44. position = Position(args.latitude, args.longitude)
  45. if args.format == 'pdf':
  46. print(_('Save the planet and paper!\n'
  47. 'Consider printing you PDF document only if really necessary, and use the other side of the sheet.'))
  48. if position is None:
  49. print()
  50. print(colored(_("PDF output will not contain the ephemerides, because you didn't provide the observation "
  51. "coordinate."), 'yellow'))
  52. try:
  53. ephemeris = EphemeridesComputer(position)
  54. ephemerides = ephemeris.compute_ephemerides(year, month, day)
  55. events_list = events.search_events(compute_date)
  56. selected_dumper = output_formats[args.format](ephemerides, events_list, compute_date, args.colors)
  57. output = selected_dumper.to_string()
  58. except UnavailableFeatureError as error:
  59. print(colored(error.msg, 'red'))
  60. return 2
  61. if args.output is not None:
  62. try:
  63. with open(args.output, 'wb') as output_file:
  64. output_file.write(output)
  65. except OSError as error:
  66. print(_('Could not save the output in "{path}": {error}').format(path=args.output,
  67. error=error.strerror))
  68. elif not selected_dumper.is_file_output_needed():
  69. print(output)
  70. else:
  71. print(colored(_('Selected output format needs an output file (--output).'), color='red'))
  72. return 1
  73. return 0
  74. def get_dumpers() -> {str: dumper.Dumper}:
  75. return {
  76. 'text': dumper.TextDumper,
  77. 'json': dumper.JsonDumper,
  78. 'pdf': dumper.PdfDumper
  79. }
  80. def output_version() -> bool:
  81. python_version = '%d.%d.%d' % (sys.version_info[0], sys.version_info[1], sys.version_info[2])
  82. print('Kosmorro %s' % VERSION)
  83. print(_('Running on Python {python_version}').format(python_version=python_version))
  84. return True
  85. def clear_cache() -> bool:
  86. confirm = input(_("Do you really want to clear Kosmorro's cache? [yN] ")).upper()
  87. if re.match(locale.nl_langinfo(locale.YESEXPR), confirm) is not None:
  88. try:
  89. core.clear_cache()
  90. except FileNotFoundError:
  91. pass
  92. elif confirm != '' and re.match(locale.nl_langinfo(locale.NOEXPR), confirm) is None:
  93. print(_('Answer did not match expected options, cache not cleared.'))
  94. return False
  95. return True
  96. def get_args(output_formats: [str]):
  97. today = date.today()
  98. parser = argparse.ArgumentParser(description=_('Compute the ephemerides and the events for a given date,'
  99. ' at a given position on Earth.'),
  100. epilog=_('By default, only the events will be computed for today ({date}).\n'
  101. 'To compute also the ephemerides, latitude and longitude arguments'
  102. ' are needed.').format(date=today.strftime(dumper.FULL_DATE_FORMAT)))
  103. parser.add_argument('--version', '-v', dest='special_action', action='store_const', const=output_version,
  104. default=None, help=_('Show the program version'))
  105. parser.add_argument('--clear-cache', dest='special_action', action='store_const', const=clear_cache, default=None,
  106. help=_('Delete all the files Kosmorro stored in the cache.'))
  107. parser.add_argument('--format', '-f', type=str, default=output_formats[0], choices=output_formats,
  108. help=_('The format under which the information have to be output'))
  109. parser.add_argument('--latitude', '-lat', type=float, default=None,
  110. help=_("The observer's latitude on Earth"))
  111. parser.add_argument('--longitude', '-lon', type=float, default=None,
  112. help=_("The observer's longitude on Earth"))
  113. parser.add_argument('--day', '-d', type=int, default=today.day,
  114. help=_('A number between 1 and 28, 29, 30 or 31 (depending on the month). The day you want to '
  115. ' compute the ephemerides for. Defaults to {default_day} (the current day).').format(
  116. default_day=today.day))
  117. parser.add_argument('--month', '-m', type=int, default=today.month,
  118. help=_('A number between 1 and 12. The month you want to compute the ephemerides for.'
  119. ' Defaults to {default_month} (the current month).').format(default_month=today.month))
  120. parser.add_argument('--year', '-y', type=int, default=today.year,
  121. help=_('The year you want to compute the ephemerides for.'
  122. ' Defaults to {default_year} (the current year).').format(default_year=today.year))
  123. parser.add_argument('--no-colors', dest='colors', action='store_false',
  124. help=_('Disable the colors in the console.'))
  125. parser.add_argument('--output', '-o', type=str, default=None,
  126. help=_('A file to export the output to. If not given, the standard output is used. '
  127. 'This argument is needed for PDF format.'))
  128. return parser.parse_args()