Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 

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