organize.py 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import os
  2. import shutil
  3. try:
  4. import pil
  5. import logger
  6. except ImportError:
  7. from . import pil
  8. from . import logger
  9. def organize_videos():
  10. try:
  11. # Make a variable equal to the names of the files in the current directory.
  12. current_dir_files = os.listdir(pil.dl_path)
  13. # Count the amount of files moved and not moved because they already exist etc.
  14. not_moved = 0
  15. has_moved = 0
  16. # The downloaded livestream(s) are in MP4 format.
  17. video_format = ['mp4']
  18. # Find the MP4 files and save them in a variable called 'filenames'.
  19. filenames = [os.path.join(pil.dl_path, filename) for filename in current_dir_files
  20. if filename.split('.')[-1] in video_format]
  21. if len(filenames) == 0:
  22. logger.binfo("No files were found to organize.")
  23. logger.separator()
  24. return
  25. # We want a dictionary where the filenames are the keys
  26. # and the usernames are the values.
  27. filenames_to_usernames = {}
  28. # Populate the dictionary by going through each filename and removing the
  29. # undesired characters, leaving just the usernames.
  30. for filename in filenames:
  31. filename_parts = filename.split('_')[1:-3]
  32. usernames = '_'.join(filename_parts)
  33. filenames_to_usernames[filename] = usernames
  34. # The usernames are the values of the filenames_to_usernames dictionary.
  35. usernames = set(filenames_to_usernames.values())
  36. # Make a folder for each username.
  37. for username in usernames:
  38. username_path = os.path.join(pil.dl_path, username)
  39. if not os.path.isdir(username_path):
  40. os.mkdir(username_path)
  41. # Move the videos into the folders
  42. for filename, username in filenames_to_usernames.items():
  43. filename_base = os.path.basename(filename)
  44. destination_path = os.path.join(pil.dl_path, username, filename_base)
  45. if not os.path.isfile(destination_path):
  46. try:
  47. shutil.move(filename, destination_path)
  48. logger.info("Moved '{:s}' successfully.".format(filename_base))
  49. has_moved += 1
  50. except OSError as oe:
  51. logger.warn("Could not move {:s}: {:s}".format(filename_base, str(oe)))
  52. not_moved += 1
  53. else:
  54. logger.binfo("Did not move '{:s}' because it already exists.".format(filename_base))
  55. not_moved += 1
  56. logger.separator()
  57. logger.info("{} {} moved.".format(has_moved, "file was" if has_moved == 1 else "files were"))
  58. if not_moved:
  59. logger.binfo("{} {} not moved.".format(not_moved, "file was" if not_moved == 1 else "files were"))
  60. logger.separator()
  61. except Exception as e:
  62. logger.error("Could not organize files: {:s}".format(str(e)))