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.
 
 
 
 

336 rivejä
10 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. import os.path
  22. from kosmorrolib import Position, get_ephemerides, get_events, get_moon_phase
  23. from kosmorrolib.__version__ import __version__ as kosmorrolib_version
  24. from kosmorrolib.exceptions import OutOfRangeDateError
  25. from datetime import date
  26. from termcolor import colored
  27. from . import dumper, environment, debug
  28. from .date import parse_date
  29. from .geolocation import get_position
  30. from .__version__ import __version__ as kosmorro_version
  31. from .exceptions import (
  32. InvalidOutputFormatError,
  33. UnavailableFeatureError,
  34. OutOfRangeDateError as DateRangeError,
  35. )
  36. from _kosmorro.i18n.utils import _, SHORT_DATE_FORMAT
  37. def main():
  38. env_vars = environment.get_env_vars()
  39. output_formats = get_dumpers()
  40. args = get_args(list(output_formats.keys()))
  41. debug.show_debug_messages = args.show_debug_messages
  42. output_format = args.format
  43. if args.special_action is not None:
  44. return 0 if args.special_action() else 1
  45. try:
  46. compute_date = parse_date(args.date)
  47. except ValueError as error:
  48. print(colored(error.args[0], color="red", attrs=["bold"]))
  49. return -1
  50. position = get_position(args.position) if args.position not in [None, ""] else None
  51. # if output format is not specified, try to use output file extension as output format
  52. if args.output is not None and output_format is None:
  53. file_extension = os.path.splitext(args.output)[-1][1:].lower()
  54. if file_extension:
  55. output_format = file_extension
  56. # default to .txt if output format was not given and output file did not have file extension
  57. if output_format is None:
  58. output_format = "txt"
  59. if output_format == "pdf":
  60. print(
  61. _(
  62. "Save the planet and paper!\n"
  63. "Consider printing your PDF document only if really necessary, and use the other side of the sheet."
  64. )
  65. )
  66. if position is None:
  67. print()
  68. print(
  69. colored(
  70. _(
  71. "PDF output will not contain the ephemerides, because you didn't provide the observation "
  72. "coordinates."
  73. ),
  74. "yellow",
  75. )
  76. )
  77. timezone = args.timezone
  78. if timezone is None and env_vars.timezone is not None:
  79. timezone = int(env_vars.timezone)
  80. elif timezone is None:
  81. timezone = 0
  82. try:
  83. use_colors = not environment.NO_COLOR and args.colors
  84. output = get_information(
  85. compute_date,
  86. position,
  87. timezone,
  88. output_format,
  89. use_colors,
  90. args.show_graph,
  91. )
  92. except InvalidOutputFormatError as error:
  93. print(colored(error.msg, "red"))
  94. debug.debug_print(error)
  95. return 3
  96. except UnavailableFeatureError as error:
  97. print(colored(error.msg, "red"))
  98. debug.debug_print(error)
  99. return 2
  100. except DateRangeError as error:
  101. print(colored(error.msg, "red"))
  102. debug.debug_print(error)
  103. return 1
  104. if args.output is not None:
  105. try:
  106. file_content = output.to_string()
  107. opening_mode = get_opening_mode(output_format)
  108. with open(args.output, opening_mode) as output_file:
  109. output_file.write(file_content)
  110. except UnavailableFeatureError as error:
  111. print(colored(error.msg, "red"))
  112. debug.debug_print(error)
  113. return 2
  114. except OSError as error:
  115. print(
  116. colored(
  117. _('The file could not be saved in "{path}": {error}').format(
  118. path=args.output, error=error.strerror
  119. ),
  120. "red",
  121. )
  122. )
  123. debug.debug_print(error)
  124. return 3
  125. elif not output.is_file_output_needed():
  126. print(output)
  127. else:
  128. print(
  129. colored(
  130. _("Please provide a file path to export in this format (--output)."),
  131. color="red",
  132. )
  133. )
  134. return 1
  135. return 0
  136. def get_information(
  137. compute_date: date,
  138. position: Position,
  139. timezone: int,
  140. output_format: str,
  141. colors: bool,
  142. show_graph: bool,
  143. ) -> dumper.Dumper:
  144. if position is not None:
  145. try:
  146. eph = get_ephemerides(
  147. for_date=compute_date, position=position, timezone=timezone
  148. )
  149. except OutOfRangeDateError as error:
  150. raise DateRangeError(error.min_date, error.max_date)
  151. else:
  152. eph = []
  153. try:
  154. moon_phase = get_moon_phase(for_date=compute_date, timezone=timezone)
  155. except OutOfRangeDateError as error:
  156. moon_phase = None
  157. print(
  158. colored(
  159. _(
  160. "Moon phase can only be displayed between {min_date} and {max_date}"
  161. ).format(
  162. min_date=error.min_date.strftime(SHORT_DATE_FORMAT),
  163. max_date=error.max_date.strftime(SHORT_DATE_FORMAT),
  164. ),
  165. "yellow",
  166. )
  167. )
  168. events_list = get_events(compute_date, timezone)
  169. try:
  170. return get_dumpers()[output_format](
  171. ephemerides=eph,
  172. moon_phase=moon_phase,
  173. events=events_list,
  174. date=compute_date,
  175. timezone=timezone,
  176. with_colors=colors,
  177. show_graph=show_graph,
  178. )
  179. except KeyError as error:
  180. raise InvalidOutputFormatError(output_format, list(get_dumpers().keys()))
  181. def get_dumpers() -> {str: dumper.Dumper}:
  182. return {
  183. "txt": dumper.TextDumper,
  184. "json": dumper.JsonDumper,
  185. "pdf": dumper.PdfDumper,
  186. }
  187. def get_opening_mode(format: str) -> str:
  188. if format == "pdf":
  189. return "wb"
  190. return "w"
  191. def output_version() -> bool:
  192. python_version = "%d.%d.%d" % (
  193. sys.version_info[0],
  194. sys.version_info[1],
  195. sys.version_info[2],
  196. )
  197. print("Kosmorro %s" % kosmorro_version)
  198. print(
  199. _(
  200. "Running on Python {python_version} "
  201. "with Kosmorrolib v{kosmorrolib_version}"
  202. ).format(python_version=python_version, kosmorrolib_version=kosmorrolib_version)
  203. )
  204. return True
  205. def get_args(output_formats: [str]):
  206. today = date.today()
  207. parser = argparse.ArgumentParser(
  208. description=_(
  209. "Compute the ephemerides and the events for a given date and a given position on Earth."
  210. ),
  211. epilog=_(
  212. "By default, only the events will be computed for today ({date}).\n"
  213. "To compute also the ephemerides, latitude and longitude arguments"
  214. " are needed."
  215. ).format(date=today.strftime(dumper.FULL_DATE_FORMAT)),
  216. )
  217. parser.add_argument(
  218. "--version",
  219. "-v",
  220. dest="special_action",
  221. action="store_const",
  222. const=output_version,
  223. default=None,
  224. help=_("Show the program version"),
  225. )
  226. parser.add_argument(
  227. "--format",
  228. "-f",
  229. type=str,
  230. default=None,
  231. choices=output_formats,
  232. help=_(
  233. "The format to output the information to. If not provided, the output format "
  234. "will be inferred from the file extension of the output file."
  235. ),
  236. )
  237. parser.add_argument(
  238. "--position",
  239. "-p",
  240. type=str,
  241. default=None,
  242. help=_(
  243. 'The observer\'s position on Earth, in the "{latitude},{longitude}" format.'
  244. "Can also be set in the KOSMORRO_POSITION environment variable."
  245. ),
  246. )
  247. parser.add_argument(
  248. "--date",
  249. "-d",
  250. type=str,
  251. default=today.strftime("%Y-%m-%d"),
  252. help=_(
  253. "The date for which the ephemerides must be calculated. Can be in the YYYY-MM-DD format "
  254. 'or an interval in the "[+-]YyMmDd" format (with Y, M, and D numbers). '
  255. "Defaults to today ({default_date})."
  256. ).format(default_date=today.strftime("%Y-%m-%d")),
  257. )
  258. parser.add_argument(
  259. "--timezone",
  260. "-t",
  261. type=int,
  262. default=None,
  263. help=_(
  264. "The timezone to display the hours in (e.g. 2 for UTC+2 or -3 for UTC-3). "
  265. "Can also be set in the KOSMORRO_TIMEZONE environment variable."
  266. ),
  267. )
  268. parser.add_argument(
  269. "--no-colors",
  270. dest="colors",
  271. action="store_false",
  272. help=_("Disable the colors in the console."),
  273. )
  274. parser.add_argument(
  275. "--output",
  276. "-o",
  277. type=str,
  278. default=None,
  279. help=_(
  280. "A file to export the output to. If not given, the standard output is used. "
  281. "This argument is needed for PDF format."
  282. ),
  283. )
  284. parser.add_argument(
  285. "--no-graph",
  286. dest="show_graph",
  287. action="store_false",
  288. help=_(
  289. "Do not generate a graph to represent the rise and set times in the PDF format."
  290. ),
  291. )
  292. parser.add_argument(
  293. "--debug",
  294. dest="show_debug_messages",
  295. action="store_true",
  296. help=_("Show debugging messages"),
  297. )
  298. return parser.parse_args()