organize.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import os
  2. import shutil
  3. from datetime import datetime
  4. import time
  5. import re
  6. try:
  7. import pil
  8. import logger
  9. except ImportError:
  10. from . import pil
  11. from . import logger
  12. def organize_files():
  13. try:
  14. files = [f for f in os.listdir(pil.dl_path) if os.path.isfile(os.path.join(pil.dl_path, f)) and not f.endswith(".lock")]
  15. not_moved = 0
  16. has_moved = 0
  17. username_regex = r'(?<=\d{8}_)(.*?)(?=_\d)'
  18. date_regex = r'^\d{8}'
  19. timestamp_regex = r'_(\d{10})_'
  20. type_regex = r'(live|replay)'
  21. raw_file_dict = {}
  22. new_file_dict = {}
  23. for file in files:
  24. try:
  25. username = re.search(username_regex, file)[0]
  26. date_ts = datetime.strptime(re.search(date_regex, file)[0], '%Y%m%d').strftime('%d-%m-%Y')
  27. time_ts = time.strftime('%I-%M-%S-%p', time.localtime(int(re.search(timestamp_regex, file)[1])))
  28. file_ext = os.path.splitext(file)[1]
  29. file_type = re.search(type_regex, file)[0]
  30. json_type = ""
  31. if file.endswith("_downloads.json"):
  32. json_type = " downloads"
  33. elif file.endswith("_comments.json"):
  34. json_type = " comments"
  35. new_file = "{:s} {:s} {:s} ({:s}){:s}{:s}".format(date_ts, time_ts, username, file_type, json_type, file_ext)
  36. raw_file_dict[file] = username
  37. new_file_dict[file] = new_file
  38. except TypeError as e:
  39. logger.warn("Could not parse filename '{:s}', skipping.".format(file))
  40. for filename, username in raw_file_dict.items():
  41. try:
  42. os.makedirs(os.path.join(pil.dl_path, username))
  43. except:
  44. pass
  45. source_path = os.path.join(pil.dl_path, filename)
  46. destination_path = os.path.join(pil.dl_path, username, new_file_dict.get(filename))
  47. if not os.path.isfile(destination_path):
  48. try:
  49. shutil.move(source_path, destination_path)
  50. logger.info("Moved and renamed '{:s}' successfully.".format(filename))
  51. has_moved += 1
  52. except OSError as oe:
  53. logger.warn("Could not move and rename {:s}: {:s}".format(filename, str(oe)))
  54. not_moved += 1
  55. else:
  56. logger.binfo("Did not move and rename '{:s}' because it already exists.".format(filename))
  57. not_moved += 1
  58. logger.separator()
  59. logger.info("{} {} moved.".format(has_moved, "file was" if has_moved == 1 else "files were"))
  60. if not_moved:
  61. logger.binfo("{} {} not moved.".format(not_moved, "file was" if not_moved == 1 else "files were"))
  62. logger.separator()
  63. except Exception as e:
  64. logger.error("Could not organize files: {:s}".format(str(e)))