cli.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import click
  2. import pkgutil
  3. import shutil
  4. import os.path
  5. from datetime import datetime
  6. from slackviewer.constants import SLACKVIEWER_TEMP_PATH
  7. from slackviewer.utils.click import envvar, flag_ennvar
  8. from slackviewer.reader import Reader
  9. from slackviewer.archive import get_export_info
  10. from jinja2 import Environment, PackageLoader
  11. @click.group()
  12. def cli():
  13. pass
  14. @cli.command(help="Cleans up any temporary files (including cached output by slack-export-viewer)")
  15. @click.option("--wet", "-w", is_flag=True,
  16. default=flag_ennvar("SEV_CLEAN_WET"),
  17. help="Actually performs file deletion")
  18. def clean(wet):
  19. if wet:
  20. if os.path.exists(SLACKVIEWER_TEMP_PATH):
  21. print("Removing {}...".format(SLACKVIEWER_TEMP_PATH))
  22. shutil.rmtree(SLACKVIEWER_TEMP_PATH)
  23. else:
  24. print("Nothing to remove! {} does not exist.".format(SLACKVIEWER_TEMP_PATH))
  25. else:
  26. print("Run with -w to remove {}".format(SLACKVIEWER_TEMP_PATH))
  27. @cli.command(help="Generates a single-file printable export for an archive file or directory")
  28. @click.argument('archive_dir')
  29. def export(archive_dir):
  30. css = pkgutil.get_data('slackviewer', 'static/viewer.css').decode('utf-8')
  31. tmpl = Environment(loader=PackageLoader('slackviewer')).get_template("export_single.html")
  32. export_file_info = get_export_info(archive_dir)
  33. r = Reader(export_file_info["readable_path"])
  34. channel_list = sorted(
  35. [{"channel_name": k, "messages": v} for (k, v) in r.compile_channels().items()],
  36. key=lambda d: d["channel_name"]
  37. )
  38. html = tmpl.render(
  39. css=css,
  40. generated_on=datetime.now(),
  41. workspace_name=export_file_info["workspace_name"],
  42. source_file=export_file_info["basename"],
  43. channels=channel_list
  44. )
  45. outfile = open(export_file_info["stripped_name"] + '.html', 'w')
  46. outfile.write(html.encode('utf-8'))