cli.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  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"
  59. % path)
  60. continue
  61. configs.append(path)
  62. os.chdir(os.path.dirname(os.path.realpath(__file__)))
  63. for conf in configs:
  64. get_config().from_pyfile(conf)
  65. for check in prechecks:
  66. for warn in check():
  67. logger.warn(warn)
  68. def main():
  69. parser = ArgumentParser(description='creates mp3 from live recordings')
  70. parser.add_argument('--verbose', '-v', action='count',
  71. default=0,
  72. help='Increase verbosity; can be used multiple times')
  73. parser.add_argument('--pretend', '-p', action='store_true', default=False,
  74. help='Only pretend; no real action will be done')
  75. sub = parser.add_subparsers(title='main subcommands',
  76. description='valid subcommands')
  77. serve_p = sub.add_parser('serve', help="Start an HTTP server")
  78. serve_p.set_defaults(func=server.main_cmd)
  79. forge_p = sub.add_parser('forge', help="Create an audio file")
  80. forge_p.add_argument('starttime', metavar='START',
  81. help='Start time, espressed as 19450425_1200 (%%Y%%m%%d-%%H%%M%%S)',
  82. action=DateTimeAction)
  83. forge_p.add_argument('endtime', metavar='END',
  84. help='End time, espressed as 19450425_1200 (%%Y%%m%%d-%%H%%M%%S)',
  85. action=DateTimeAction)
  86. forge_p.add_argument('-o', metavar='OUTFILE', dest='outfile',
  87. default='out.mp3', help='Path of the output mp3')
  88. forge_p.set_defaults(func=forge.main_cmd)
  89. cleanold_p = sub.add_parser('cleanold', help="Remove old files from DB",
  90. description="Will remove oldfiles with no filename from DB")
  91. cleanold_p.add_argument('-t', metavar='MINAGE', dest='minage',
  92. default='14', type=int,
  93. help='Minimum age (in days) for removal')
  94. cleanold_p.set_defaults(func=maint.cleanold_cmd)
  95. options = parser.parse_args()
  96. options.cwd = CWD
  97. if options.verbose < 1:
  98. logging.basicConfig(level=logging.WARNING)
  99. elif options.verbose == 1:
  100. logging.basicConfig(level=logging.INFO)
  101. elif options.verbose >= 2:
  102. logging.basicConfig(level=logging.DEBUG)
  103. if options.verbose > 2:
  104. logging.info("giving verbose flag >2 times is useless")
  105. common_pre()
  106. options.func(options)
  107. if __name__ == "__main__":
  108. main()