bot.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. #!/usr/bin/env python3.7
  2. import logging
  3. import queue
  4. import shlex
  5. import subprocess
  6. import sys
  7. from threading import Thread
  8. from ircclient import IRCClient, MODE_SEARCH, MODE_BOOK
  9. logging.basicConfig(level=logging.DEBUG)
  10. log = logging.getLogger(__name__)
  11. log.setLevel(logging.DEBUG)
  12. def usage():
  13. print("USAGE:")
  14. print("\t SEARCH <BOOK>")
  15. print("\t BOOK <BOT COMMAND>")
  16. def get_books_from_list(filename):
  17. f = open(filename, "r")
  18. ret = []
  19. for line in f.readlines():
  20. line = line.lower().strip()
  21. if not line.startswith('!') or not any(_type in line for _type in ['epub', 'mobi']):
  22. continue
  23. ret.append(line)
  24. log.info("Book matches: %s", line)
  25. ret = list(set(ret)) # dedup
  26. return ret
  27. def mode_from_files(files):
  28. for f in files:
  29. f = f.lower()
  30. if 'searchbot' in f or 'searchook' in f.lower():
  31. return MODE_SEARCH
  32. return MODE_BOOK
  33. def handle_files(files):
  34. log.info("Unarchived files %s", files)
  35. out = []
  36. mode = mode_from_files(files)
  37. if mode == MODE_SEARCH:
  38. for f in files:
  39. if "searchbot" not in f.lower() and "searchook" not in f.lower():
  40. continue
  41. out.extend(get_books_from_list(f))
  42. return
  43. for f in files:
  44. if f.lower().endswith(".epub"):
  45. log.info("EPUB %s", f)
  46. new_fname = f.replace("epub", "mobi")
  47. p = subprocess.Popen(["ebook-convert", f, new_fname], stdout=subprocess.DEVNULL)
  48. # TODO log to file?
  49. p.wait()
  50. out.append(new_fname)
  51. out.append(f)
  52. # TODO make paths absolute?
  53. for filename in out:
  54. log.info(filename)
  55. def handle_results(q):
  56. while True:
  57. item = q.get()
  58. log.info("Got a result! %s", item)
  59. if item['type'] == 'status':
  60. print(item['key'], item['status'])
  61. elif item['type'] == 'files':
  62. handle_files(item['files'])
  63. def main():
  64. q = queue.Queue()
  65. rq = queue.Queue()
  66. client = IRCClient(command_queue=q, results_queue=rq)
  67. client.start()
  68. results_t = Thread(target=handle_results, args=(rq,))
  69. results_t.daemon = True
  70. results_t.start()
  71. for line in sys.stdin:
  72. line = line.strip().lower()
  73. try:
  74. split = shlex.split(line)
  75. except Exception as e:
  76. print(e)
  77. continue
  78. if split[0].lower() not in [MODE_SEARCH, MODE_BOOK]:
  79. usage()
  80. continue
  81. mode = split[0]
  82. query = " ".join(split[1:])
  83. data = {'query': query, 'mode': mode}
  84. q.put(data)
  85. client.join()
  86. results_t.join()
  87. if __name__ == "__main__":
  88. try:
  89. main()
  90. except KeyboardInterrupt:
  91. print("\nBye")