Não pode escolher mais do que 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

main.py 7.2 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. output = format_dumper.to_string()
  67. except UnavailableFeatureError as error:
  68. print(colored(error.msg, 'red'))
  69. return 2
  70. if args.output is not None:
  71. try:
  72. with open(args.output, 'wb') as output_file:
  73. output_file.write(output)
  74. except OSError as error:
  75. print(_('Could not save the output in "{path}": {error}').format(path=args.output,
  76. error=error.strerror))
  77. elif not format_dumper.is_file_output_needed():
  78. print(output)
  79. else:
  80. print(colored(_('Selected output format needs an output file (--output).'), color='red'))
  81. return 1
  82. return 0
  83. def get_dumpers() -> {str: dumper.Dumper}:
  84. return {
  85. 'text': dumper.TextDumper,
  86. 'json': dumper.JsonDumper,
  87. 'pdf': dumper.PdfDumper
  88. }
  89. def output_version() -> bool:
  90. python_version = '%d.%d.%d' % (sys.version_info[0], sys.version_info[1], sys.version_info[2])
  91. print('Kosmorro %s' % VERSION)
  92. print(_('Running on Python {python_version}').format(python_version=python_version))
  93. return True
  94. def clear_cache() -> bool:
  95. confirm = input(_("Do you really want to clear Kosmorro's cache? [yN] ")).upper()
  96. if re.match(locale.nl_langinfo(locale.YESEXPR), confirm) is not None:
  97. try:
  98. core.clear_cache()
  99. except FileNotFoundError:
  100. pass
  101. elif confirm != '' and re.match(locale.nl_langinfo(locale.NOEXPR), confirm) is None:
  102. print(_('Answer did not match expected options, cache not cleared.'))
  103. return False
  104. return True
  105. def get_args(output_formats: [str]):
  106. today = date.today()
  107. parser = argparse.ArgumentParser(description=_('Compute the ephemerides and the events for a given date,'
  108. ' at a given position on Earth.'),
  109. epilog=_('By default, only the events will be computed for today ({date}).\n'
  110. 'To compute also the ephemerides, latitude and longitude arguments'
  111. ' are needed.').format(date=today.strftime(dumper.FULL_DATE_FORMAT)))
  112. parser.add_argument('--version', '-v', dest='special_action', action='store_const', const=output_version,
  113. default=None, help=_('Show the program version'))
  114. parser.add_argument('--clear-cache', dest='special_action', action='store_const', const=clear_cache, default=None,
  115. help=_('Delete all the files Kosmorro stored in the cache.'))
  116. parser.add_argument('--format', '-f', type=str, default=output_formats[0], choices=output_formats,
  117. help=_('The format under which the information have to be output'))
  118. parser.add_argument('--latitude', '-lat', type=float, default=None,
  119. help=_("The observer's latitude on Earth. Can also be set in the KOSMORRO_LATITUDE environment "
  120. "variable."))
  121. parser.add_argument('--longitude', '-lon', type=float, default=None,
  122. help=_("The observer's longitude on Earth. Can also be set in the KOSMORRO_LONGITUDE "
  123. "environment variable."))
  124. parser.add_argument('--date', '-d', type=str, default=today.strftime('%Y-%m-%d'),
  125. help=_('The date for which the ephemerides must be computed (in the YYYY-MM-DD format). '
  126. 'Defaults to the current date ({default_date})').format(
  127. default_date=today.strftime('%Y-%m-%d')))
  128. parser.add_argument('--timezone', '-t', type=int, default=None,
  129. help=_('The timezone to display the hours in (e.g. 2 for UTC+2 or -3 for UTC-3). '
  130. 'Can also be set in the KOSMORRO_TIMEZONE environment variable.'))
  131. parser.add_argument('--no-colors', dest='colors', action='store_false',
  132. help=_('Disable the colors in the console.'))
  133. parser.add_argument('--output', '-o', type=str, default=None,
  134. help=_('A file to export the output to. If not given, the standard output is used. '
  135. 'This argument is needed for PDF format.'))
  136. return parser.parse_args()