organize.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import os
  2. import shutil
  3. from datetime import datetime
  4. import time
  5. try:
  6. import pil
  7. import logger
  8. except ImportError:
  9. from . import pil
  10. from . import logger
  11. def organize_videos():
  12. try:
  13. # Make a variable equal to the names of the files in the current directory.
  14. current_dir_files = os.listdir()
  15. # Count the amount of files moved and not moved because they already exist etc.
  16. not_moved = 0
  17. has_moved = 0
  18. # The downloaded livestream(s) are in MP4 format.
  19. video_format = ['mp4']
  20. # Find the MP4 files and save them in a variable called 'filenames'.
  21. filenames = [filename for filename in current_dir_files
  22. if filename.split('.')[-1] in video_format]
  23. if len(filenames) == 0:
  24. print("No MP4 files in the current directory.")
  25. return
  26. for filename in filenames:
  27. # Split the filenames into parts.
  28. filename_parts = filename.split('_')
  29. # Get the date from the filename.
  30. date = datetime.strptime(filename_parts[0], '%Y%m%d').strftime('%d-%m-%Y')
  31. # Get the username from the filename.
  32. username = '_'.join(filename_parts[1:-3])
  33. # Get the time from the unix timestamp.
  34. time_from_unix_timestamp = time.strftime('%I.%M%p', time.localtime(int(filename_parts[-2])))
  35. # # Remove the leading zero from single-digit hours.
  36. if float(time_from_unix_timestamp[0:2]) < 10:
  37. time_from_unix_timestamp = time_from_unix_timestamp[1:]
  38. # Get the last part of the filename ("live.mp4" or "replay.mp4").
  39. live_or_replay = filename_parts[-1]
  40. # Change the filenames to the format "[date] [time] [username] [live/replay].mp4"
  41. os.rename(filename, date + " " + username + " [" + time_from_unix_timestamp + "] " + live_or_replay)
  42. # Note: I added a space before ".mp4" as this will separate the username from ".mp4"
  43. # when I do .split() on line 67.
  44. # Now that the files have been renamed, we need to rescan the files in the directory.
  45. current_dir_files = os.listdir()
  46. new_filenames = [filename for filename in current_dir_files if filename.split('.')[-1] in video_format]
  47. # We want a dictionary where the filenames are the keys
  48. # and the usernames are the values.
  49. filenames_to_usernames = {}
  50. # Populate the dictionary with a loop.
  51. for filename in new_filenames:
  52. # Split the filenames into parts so we get just the usernames:
  53. filename_parts = filename.split()
  54. # This is how to get the usernames from the split filenames:
  55. username = filename_parts[1]
  56. # Filename = key and username = value:
  57. filenames_to_usernames[filename] = username
  58. # We only want one folder for each username, so convert the list into a set to remove duplicates.
  59. usernames = set(filenames_to_usernames.values())
  60. # Make a folder for each username.
  61. for username in usernames:
  62. username_path = os.path.join(pil.dl_path, username)
  63. if not os.path.isdir(username_path):
  64. os.mkdir(username_path)
  65. # Move the videos into the folders
  66. for filename, username in filenames_to_usernames.items():
  67. filename_base = os.path.basename(filename)
  68. destination_path = os.path.join(pil.dl_path, username, filename_base)
  69. if not os.path.isfile(destination_path):
  70. try:
  71. shutil.move(filename, destination_path)
  72. logger.info("Moved '{:s}' successfully.".format(filename_base))
  73. has_moved += 1
  74. except OSError as oe:
  75. logger.warn("Could not move {:s}: {:s}".format(filename_base, str(oe)))
  76. not_moved += 1
  77. else:
  78. logger.binfo("Did not move '{:s}' because it already exists.".format(filename_base))
  79. not_moved += 1
  80. logger.separator()
  81. logger.info("{} {} moved.".format(has_moved, "file was" if has_moved == 1 else "files were"))
  82. if not_moved:
  83. logger.binfo("{} {} not moved.".format(not_moved, "file was" if not_moved == 1 else "files were"))
  84. logger.separator()
  85. except Exception as e:
  86. logger.error("Could not organize files: {:s}".format(str(e)))