main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. import os
  2. import time
  3. import datetime
  4. import pickle
  5. import threading
  6. from googleapiclient.discovery import build
  7. import subprocess
  8. from google.auth.transport.requests import Request
  9. import sys
  10. # Constants
  11. OUTPUT_DIR = "/media/media/YouTube" # Change this to your Emby folder
  12. DAYS_BACK = 5 # Videos published in the last 5 days
  13. DAYS_TO_KEEP = 10 # Delete videos older than 10 days
  14. TOKEN_FILE = "youtube_token.pickle" # Token file from the OAuth script
  15. EXIT_TIME = datetime.time(6, 0) # Exit the script at 06:00
  16. POPULAR_VIDEOS_MAX_RESULTS = 10 # Number of popular videos to fetch (you can change this)
  17. REGION_CODES = ["US", "GB", "LU"] # Regions to fetch popular videos from
  18. def update_yt_dlp():
  19. """Update yt-dlp to the latest version."""
  20. print("Updating yt-dlp to the latest version...")
  21. subprocess.run(["pip", "install", "--upgrade", "yt-dlp"], check=True)
  22. print("yt-dlp updated successfully!")
  23. def authenticate_with_token():
  24. """Authenticate using the saved token, with automatic refresh."""
  25. if not os.path.exists(TOKEN_FILE):
  26. raise FileNotFoundError(f"Token file '{TOKEN_FILE}' not found. Please run the token retrieval script first.")
  27. # Load credentials from the token file
  28. with open(TOKEN_FILE, "rb") as token:
  29. creds = pickle.load(token)
  30. # Refresh the token if it has expired
  31. if creds and creds.expired and creds.refresh_token:
  32. print("Access token expired. Refreshing...")
  33. creds.refresh(Request())
  34. # Save the refreshed credentials back to the file
  35. with open(TOKEN_FILE, "wb") as token:
  36. pickle.dump(creds, token)
  37. print("Token refreshed successfully!")
  38. # Build the YouTube API client
  39. youtube = build("youtube", "v3", credentials=creds)
  40. return youtube
  41. def get_subscribed_channels(youtube):
  42. """Fetch the list of subscribed channels."""
  43. channels = []
  44. request = youtube.subscriptions().list(
  45. part="snippet",
  46. mine=True,
  47. maxResults=50
  48. )
  49. while request:
  50. response = request.execute()
  51. for item in response["items"]:
  52. channels.append(item["snippet"]["resourceId"]["channelId"])
  53. request = youtube.subscriptions().list_next(request, response)
  54. return channels
  55. def get_recent_videos(youtube, channel_id):
  56. """Fetch videos from a channel published in the last `DAYS_BACK` days."""
  57. recent_videos = []
  58. published_after = (datetime.datetime.now() - datetime.timedelta(days=DAYS_BACK)).isoformat("T") + "Z"
  59. request = youtube.search().list(
  60. part="snippet",
  61. channelId=channel_id,
  62. publishedAfter=published_after,
  63. maxResults=50,
  64. type="video",
  65. order="date"
  66. )
  67. response = request.execute()
  68. for item in response["items"]:
  69. recent_videos.append({
  70. "video_id": item["id"]["videoId"],
  71. "title": item["snippet"]["title"],
  72. "description": item["snippet"]["description"],
  73. "published_at": item["snippet"]["publishedAt"],
  74. "channel_title": item["snippet"]["channelTitle"]
  75. })
  76. return recent_videos
  77. def get_popular_videos(youtube, region_code):
  78. """Fetch the most popular videos for a given region."""
  79. popular_videos = []
  80. request = youtube.videos().list(
  81. part="snippet,statistics",
  82. chart="mostPopular",
  83. regionCode=region_code, # Region code passed here
  84. maxResults=POPULAR_VIDEOS_MAX_RESULTS
  85. )
  86. response = request.execute()
  87. for item in response["items"]:
  88. popular_videos.append({
  89. "video_id": item["id"],
  90. "title": item["snippet"]["title"],
  91. "description": item["snippet"]["description"],
  92. "published_at": item["snippet"]["publishedAt"],
  93. "channel_title": item["snippet"]["channelTitle"]
  94. })
  95. return popular_videos
  96. def download_video(video_id, output_path):
  97. """Download a YouTube video in the best quality, handling errors gracefully."""
  98. try:
  99. command = [
  100. "yt-dlp",
  101. "-f", "bestvideo+bestaudio/best", # Best available format
  102. f"https://www.youtube.com/watch?v={video_id}",
  103. "-o", os.path.join(output_path, "%(title)s.%(ext)s")
  104. ]
  105. subprocess.run(command, check=True)
  106. except subprocess.CalledProcessError as e:
  107. print(f"Error downloading video {video_id}: {e}")
  108. return False # Return False to indicate failure
  109. return True # Return True if download is successful
  110. # Temporarily commented out video conversion functionality
  111. # def convert_to_mp4(input_file):
  112. # """Convert a video to mp4 and delete the original file."""
  113. # mp4_file = os.path.splitext(input_file)[0] + ".mp4"
  114. # print(f"Converting {input_file} to {mp4_file}...")
  115. # command = ["ffmpeg", "-i", input_file, "-c:v", "libx264", "-preset", "fast", "-c:a", "aac", mp4_file]
  116. # subprocess.run(command, check=True)
  117. # print(f"Conversion completed: {mp4_file}")
  118. # if os.path.exists(mp4_file):
  119. # os.remove(input_file)
  120. # print(f"Original file deleted: {input_file}")
  121. def create_nfo_file(video_data, file_path):
  122. """Create an Emby-compatible NFO file."""
  123. nfo_content = f"""<?xml version="1.0" encoding="utf-8" standalone="yes"?>
  124. <movie>
  125. <title>{video_data['title']}</title>
  126. <plot>{video_data['description']}</plot>
  127. <year>{video_data['published_at'][:4]}</year>
  128. <premiered>{video_data['published_at']}</premiered>
  129. <studio>{video_data['channel_title']}</studio>
  130. </movie>
  131. """
  132. with open(file_path, "w", encoding="utf-8") as nfo_file:
  133. nfo_file.write(nfo_content)
  134. def delete_old_videos(folder, days=5):
  135. """Delete video files and their folders older than `days`."""
  136. now = time.time()
  137. cutoff = now - (days * 86400) # Convert days to seconds
  138. for root, dirs, files in os.walk(folder, topdown=False):
  139. # Delete files
  140. for file in files:
  141. file_path = os.path.join(root, file)
  142. if os.path.isfile(file_path):
  143. if os.path.getmtime(file_path) < cutoff:
  144. print(f"Deleting file: {file_path}")
  145. os.remove(file_path)
  146. # Remove empty directories
  147. for dir in dirs:
  148. dir_path = os.path.join(root, dir)
  149. if not os.listdir(dir_path): # Check if the directory is empty
  150. print(f"Deleting folder: {dir_path}")
  151. os.rmdir(dir_path)
  152. def video_exists(output_path, video_id):
  153. """Check if a video already exists in the directory."""
  154. return os.path.exists(os.path.join(output_path, video_id))
  155. def check_exit_time():
  156. """Check if the current time is past the exit time."""
  157. now = datetime.datetime.now().time()
  158. if now >= EXIT_TIME:
  159. print("Current time exceeds exit time. Terminating script.")
  160. sys.exit(0)
  161. def main():
  162. # Update yt-dlp
  163. update_yt_dlp()
  164. # Authenticate YouTube API
  165. print("Authenticating with token...")
  166. youtube = authenticate_with_token()
  167. if not os.path.exists(OUTPUT_DIR):
  168. os.makedirs(OUTPUT_DIR)
  169. # Clean up old videos
  170. print(f"Deleting videos older than {DAYS_TO_KEEP} days in {OUTPUT_DIR}...")
  171. delete_old_videos(OUTPUT_DIR, days=DAYS_TO_KEEP)
  172. # Fetch subscribed channels
  173. print("Fetching subscribed channels...")
  174. channels = get_subscribed_channels(youtube)
  175. # Fetch and process recent videos from subscribed channels
  176. for channel_id in channels:
  177. print(f"Fetching recent videos for channel: {channel_id}")
  178. videos = get_recent_videos(youtube, channel_id)
  179. for video in videos:
  180. # Check the exit time before processing each video
  181. check_exit_time()
  182. print(f"Processing video: {video['title']}")
  183. video_dir = os.path.join(OUTPUT_DIR, video["video_id"])
  184. # Check if the video already exists
  185. if os.path.exists(video_dir):
  186. print(f"Skipping download, already exists: {video['title']} ({video['video_id']})")
  187. continue
  188. os.makedirs(video_dir, exist_ok=True)
  189. # Download the video
  190. if not download_video(video["video_id"], video_dir):
  191. print(f"Skipping video {video['video_id']} due to download error.")
  192. continue # Skip this video if download failed
  193. # Temporarily comment out conversion, but keep it in the code for future use
  194. # video_file = next(
  195. # (f for f in os.listdir(video_dir) if not f.endswith(".mp4")),
  196. # None
  197. # )
  198. # if video_file:
  199. # input_path = os.path.join(video_dir, video_file)
  200. # threading.Thread(target=convert_to_mp4, args=(input_path,)).start()
  201. # Create the NFO file
  202. nfo_file_path = os.path.join(video_dir, "movie.nfo")
  203. create_nfo_file(video, nfo_file_path)
  204. # Fetch and process most popular videos worldwide (from multiple regions)
  205. for region_code in REGION_CODES:
  206. print(f"Fetching the most popular videos from {region_code}...")
  207. popular_videos = get_popular_videos(youtube, region_code)
  208. for video in popular_videos:
  209. # Check the exit time before processing each video
  210. check_exit_time()
  211. print(f"Processing popular video: {video['title']} ({region_code})")
  212. video_dir = os.path.join(OUTPUT_DIR, video["video_id"])
  213. # Check if the video already exists
  214. if os.path.exists(video_dir):
  215. print(f"Skipping download, already exists: {video['title']} ({video['video_id']})")
  216. continue
  217. os.makedirs(video_dir, exist_ok=True)
  218. # Download the popular video
  219. if not download_video(video["video_id"], video_dir):
  220. print(f"Skipping popular video {video['video_id']} due to download error.")
  221. continue # Skip this video if download failed
  222. # Temporarily comment out conversion, but keep it in the code for future use
  223. # video_file = next(
  224. # (f for f in os.listdir(video_dir) if not f.endswith(".mp4")),
  225. # None
  226. # )
  227. # if video_file:
  228. # input_path = os.path.join(video_dir, video_file)
  229. # threading.Thread(target=convert_to_mp4, args=(input_path,)).start()
  230. # Create the NFO file
  231. nfo_file_path = os.path.join(video_dir, "movie.nfo")
  232. create_nfo_file(video, nfo_file_path)
  233. print("All videos processed successfully!")
  234. if __name__ == "__main__":
  235. main()