unpacker.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import os
  2. import json
  3. import socket
  4. import sys
  5. import time
  6. import tempfile
  7. from threading import Thread
  8. from subprocess import check_output
  9. from bookworm import s3
  10. from bookworm.logger import log, setup_logger
  11. from bookworm.constants import RAW_FILE_BUCKET, PROCESSED_FILE_BUCKET, UNPACKABLE_EXTENSIONS, REDIS_UNPACK_FILE
  12. import redis
  13. def should_unpack(fname):
  14. fname = fname.lower()
  15. return fname.endswith('rar') or fname.endswith('zip')
  16. def archive_contents(fd):
  17. to_extract = {}
  18. contents = check_output(['lsar', '-j', fd.name]).decode('utf-8')
  19. contents = json.loads(contents)
  20. log.debug(contents['lsarContents'])
  21. for f in contents['lsarContents']:
  22. fname = f['XADFileName']
  23. if any([extension in fname.lower() for extension in UNPACKABLE_EXTENSIONS]):
  24. log.info('Extracting %s from the archive', fname)
  25. to_extract[f['XADIndex']] = fname
  26. return to_extract
  27. def convert_to_mobi(orig_fname) -> bytes:
  28. with tempfile.NamedTemporaryFile(suffix='.mobi') as fd:
  29. log.info('Converting %s to mobi at %s', orig_fname, fd.name)
  30. check_output(['ebook-convert', orig_fname, fd.name, '--output-profile=kindle_pw'])
  31. log.info('Done converting')
  32. buff = open(fd.name, 'rb').read()
  33. return buff
  34. def store_file(s3client, fname, file_contents):
  35. log.info('Puttin in s3 under bucket %s with key %s', PROCESSED_FILE_BUCKET, fname)
  36. s3client.put_object(Body=file_contents, Bucket=PROCESSED_FILE_BUCKET, Key=fname)
  37. log.info('Put in s3 under bucket %s with key %s', PROCESSED_FILE_BUCKET, fname)
  38. def delete_raw_file(s3client, job_key):
  39. log.info('Deleting %s from %s', job_key, RAW_FILE_BUCKET)
  40. s3client.delete_object(Bucket=RAW_FILE_BUCKET, Key=job_key)
  41. def unpack_and_convert(job_key, s3client, redis):
  42. unpacked_files = unpack(job_key, s3client, redis)
  43. # TODO set_job_state(job_key, 'UNPACK_DONE', job_key)
  44. log.info('Done unpacking job %s', job_key)
  45. for fname, data in unpacked_files:
  46. if not fname.lower().endswith('mobi'):
  47. log.info('Asked to store %s, need to convert first', fname)
  48. fname_no_ext, ext = os.path.splitext(fname)
  49. with tempfile.NamedTemporaryFile(suffix=ext) as original:
  50. original.write(data)
  51. original.flush()
  52. converted_data = convert_to_mobi(original.name)
  53. data = converted_data
  54. fname = fname_no_ext + '.mobi'
  55. store_file(s3client, fname, data)
  56. delete_raw_file(s3client, job_key)
  57. def unpack(job_key, s3client, redis):
  58. log.info('Got a request to unpack %s', job_key)
  59. data = s3client.get_object(Key=job_key, Bucket=RAW_FILE_BUCKET)
  60. with tempfile.NamedTemporaryFile() as fd:
  61. raw_file_contents = data['Body'].read()
  62. fd.write(raw_file_contents)
  63. fd.flush()
  64. if not should_unpack(job_key):
  65. log.info("Not unpacking %s", job_key)
  66. return [(job_key, raw_file_contents)]
  67. to_extract = archive_contents(fd)
  68. if not to_extract:
  69. log.info(contents['lsarContents'])
  70. log.error("Could not find any valid file")
  71. return []
  72. ret = []
  73. for index, fname in to_extract.items():
  74. log.info('Processing %s %s', index, fname)
  75. file_contents = check_output(['unar', '-o', '-', '-i', fd.name, str(index)])
  76. log.info('Got %d bytes', len(file_contents))
  77. ret.append(fname, file_contents)
  78. return ret
  79. def main():
  80. r = redis.StrictRedis(host='localhost', port=6379)
  81. setup_logger()
  82. s3client = s3.client()
  83. while True:
  84. log.info('Waiting for message...')
  85. topic, message = r.blpop(REDIS_UNPACK_FILE)
  86. log.info('got message: %s', message)
  87. params = json.loads(message.decode('utf-8'))
  88. log.info('params for unpacker: %s', params)
  89. params['s3client'] = s3client
  90. params['redis'] = r
  91. t = Thread(target=unpack_and_convert, kwargs=params)
  92. t.daemon = True
  93. t.start()
  94. main()