cli.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. import os
  2. import sys
  3. from argparse import ArgumentParser, Action
  4. from datetime import datetime
  5. import logging
  6. logging.basicConfig(stream=sys.stdout)
  7. logger = logging.getLogger("cli")
  8. CWD = os.getcwd()
  9. from . import forge
  10. from . import maint
  11. from .config_manager import get_config
  12. from . import server
  13. def pre_check_permissions():
  14. def is_writable(d):
  15. return os.access(d, os.W_OK)
  16. if is_writable(get_config()["AUDIO_INPUT"]):
  17. yield "Audio input '%s' writable" % get_config()["AUDIO_INPUT"]
  18. if not os.access(get_config()["AUDIO_INPUT"], os.R_OK):
  19. yield "Audio input '%s' unreadable" % get_config()["AUDIO_INPUT"]
  20. sys.exit(10)
  21. if is_writable(os.getcwd()):
  22. yield "Code writable"
  23. if not is_writable(get_config()["AUDIO_OUTPUT"]):
  24. yield "Audio output '%s' not writable" % get_config()["AUDIO_OUTPUT"]
  25. logger.critical("Aborting")
  26. sys.exit(10)
  27. def pre_check_user():
  28. if os.geteuid() == 0:
  29. yield "You're running as root; this is dangerous"
  30. def pre_check_ffmpeg():
  31. path = get_config()["FFMPEG_PATH"]
  32. if not path.startswith("/"):
  33. yield "FFMPEG_PATH is not absolute: %s" % path
  34. from subprocess import check_output
  35. try:
  36. check_output([path, "-version"])
  37. except OSError:
  38. yield "FFMPEG not found as " + path
  39. else:
  40. if not os.path.exists(path):
  41. yield "FFMPEG not found in " + path
  42. class DateTimeAction(Action):
  43. def __call__(self, parser, namespace, values, option_string=None):
  44. if len(values) == 15 or len(values) == 13:
  45. parsed_val = datetime.strptime(values, "%Y%m%d-%H%M%S")
  46. else:
  47. raise ValueError("'%s' is not a valid datetime" % values)
  48. setattr(namespace, self.dest, parsed_val)
  49. def common_pre():
  50. prechecks = [pre_check_user, pre_check_permissions, pre_check_ffmpeg]
  51. configs = ["default_config.py"]
  52. if "TECHREC_CONFIG" in os.environ:
  53. for conf in os.environ["TECHREC_CONFIG"].split(":"):
  54. if not conf:
  55. continue
  56. path = os.path.realpath(conf)
  57. if not os.path.exists(path):
  58. logger.warn("Configuration file '%s' does not exist; skipping" % path)
  59. continue
  60. configs.append(path)
  61. os.chdir(os.path.dirname(os.path.realpath(__file__)))
  62. for conf in configs:
  63. get_config().from_pyfile(conf)
  64. for check in prechecks:
  65. for warn in check():
  66. logger.warn(warn)
  67. def main():
  68. parser = ArgumentParser(description="creates mp3 from live recordings")
  69. parser.add_argument(
  70. "--verbose",
  71. "-v",
  72. action="count",
  73. default=0,
  74. help="Increase verbosity; can be used multiple times",
  75. )
  76. parser.add_argument(
  77. "--pretend",
  78. "-p",
  79. action="store_true",
  80. default=False,
  81. help="Only pretend; no real action will be done",
  82. )
  83. sub = parser.add_subparsers(
  84. title="main subcommands", description="valid subcommands"
  85. )
  86. serve_p = sub.add_parser("serve", help="Start an HTTP server")
  87. serve_p.set_defaults(func=server.main_cmd)
  88. forge_p = sub.add_parser("forge", help="Create an audio file")
  89. forge_p.add_argument(
  90. "starttime",
  91. metavar="START",
  92. help="Start time, espressed as 19450425_1200 (%%Y%%m%%d-%%H%%M%%S)",
  93. action=DateTimeAction,
  94. )
  95. forge_p.add_argument(
  96. "endtime",
  97. metavar="END",
  98. help="End time, espressed as 19450425_1200 (%%Y%%m%%d-%%H%%M%%S)",
  99. action=DateTimeAction,
  100. )
  101. forge_p.add_argument(
  102. "-o",
  103. metavar="OUTFILE",
  104. dest="outfile",
  105. default="out.mp3",
  106. help="Path of the output mp3",
  107. )
  108. forge_p.set_defaults(func=forge.main_cmd)
  109. cleanold_p = sub.add_parser(
  110. "cleanold",
  111. help="Remove old files from DB",
  112. description="Will remove oldfiles with no filename from DB",
  113. )
  114. cleanold_p.add_argument(
  115. "-t",
  116. metavar="MINAGE",
  117. dest="minage",
  118. default="14",
  119. type=int,
  120. help="Minimum age (in days) for removal",
  121. )
  122. cleanold_p.set_defaults(func=maint.cleanold_cmd)
  123. options = parser.parse_args()
  124. options.cwd = CWD
  125. if options.verbose < 1:
  126. logging.basicConfig(level=logging.WARNING)
  127. elif options.verbose == 1:
  128. logging.basicConfig(level=logging.INFO)
  129. elif options.verbose >= 2:
  130. logging.basicConfig(level=logging.DEBUG)
  131. if options.verbose > 2:
  132. logging.info("giving verbose flag >2 times is useless")
  133. common_pre()
  134. options.func(options)
  135. if __name__ == "__main__":
  136. main()