25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 

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