cli.py 4.4 KB

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