main.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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=10):
  135. """Delete video files and corresponding NFO files 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):
  139. for file in files:
  140. file_path = os.path.join(root, file)
  141. if os.path.isfile(file_path):
  142. # Check the file's last modification time
  143. if os.path.getmtime(file_path) < cutoff:
  144. print(f"Deleting: {file_path}")
  145. os.remove(file_path)
  146. def video_exists(output_path, video_id):
  147. """Check if a video already exists in the directory."""
  148. return os.path.exists(os.path.join(output_path, video_id))
  149. def check_exit_time():
  150. """Check if the current time is past the exit time."""
  151. now = datetime.datetime.now().time()
  152. if now >= EXIT_TIME:
  153. print("Current time exceeds exit time. Terminating script.")
  154. sys.exit(0)
  155. def main():
  156. # Update yt-dlp
  157. update_yt_dlp()
  158. # Authenticate YouTube API
  159. print("Authenticating with token...")
  160. youtube = authenticate_with_token()
  161. if not os.path.exists(OUTPUT_DIR):
  162. os.makedirs(OUTPUT_DIR)
  163. # Clean up old videos
  164. print(f"Deleting videos older than {DAYS_TO_KEEP} days in {OUTPUT_DIR}...")
  165. delete_old_videos(OUTPUT_DIR, days=DAYS_TO_KEEP)
  166. # Fetch subscribed channels
  167. print("Fetching subscribed channels...")
  168. channels = get_subscribed_channels(youtube)
  169. # Fetch and process recent videos from subscribed channels
  170. for channel_id in channels:
  171. print(f"Fetching recent videos for channel: {channel_id}")
  172. videos = get_recent_videos(youtube, channel_id)
  173. for video in videos:
  174. # Check the exit time before processing each video
  175. check_exit_time()
  176. print(f"Processing video: {video['title']}")
  177. video_dir = os.path.join(OUTPUT_DIR, video["video_id"])
  178. # Check if the video already exists
  179. if os.path.exists(video_dir):
  180. print(f"Skipping download, already exists: {video['title']} ({video['video_id']})")
  181. continue
  182. os.makedirs(video_dir, exist_ok=True)
  183. # Download the video
  184. if not download_video(video["video_id"], video_dir):
  185. print(f"Skipping video {video['video_id']} due to download error.")
  186. continue # Skip this video if download failed
  187. # Temporarily comment out conversion, but keep it in the code for future use
  188. # video_file = next(
  189. # (f for f in os.listdir(video_dir) if not f.endswith(".mp4")),
  190. # None
  191. # )
  192. # if video_file:
  193. # input_path = os.path.join(video_dir, video_file)
  194. # threading.Thread(target=convert_to_mp4, args=(input_path,)).start()
  195. # Create the NFO file
  196. nfo_file_path = os.path.join(video_dir, "movie.nfo")
  197. create_nfo_file(video, nfo_file_path)
  198. # Fetch and process most popular videos worldwide (from multiple regions)
  199. for region_code in REGION_CODES:
  200. print(f"Fetching the most popular videos from {region_code}...")
  201. popular_videos = get_popular_videos(youtube, region_code)
  202. for video in popular_videos:
  203. # Check the exit time before processing each video
  204. check_exit_time()
  205. print(f"Processing popular video: {video['title']} ({region_code})")
  206. video_dir = os.path.join(OUTPUT_DIR, video["video_id"])
  207. # Check if the video already exists
  208. if os.path.exists(video_dir):
  209. print(f"Skipping download, already exists: {video['title']} ({video['video_id']})")
  210. continue
  211. os.makedirs(video_dir, exist_ok=True)
  212. # Download the popular video
  213. if not download_video(video["video_id"], video_dir):
  214. print(f"Skipping popular video {video['video_id']} due to download error.")
  215. continue # Skip this video if download failed
  216. # Temporarily comment out conversion, but keep it in the code for future use
  217. # video_file = next(
  218. # (f for f in os.listdir(video_dir) if not f.endswith(".mp4")),
  219. # None
  220. # )
  221. # if video_file:
  222. # input_path = os.path.join(video_dir, video_file)
  223. # threading.Thread(target=convert_to_mp4, args=(input_path,)).start()
  224. # Create the NFO file
  225. nfo_file_path = os.path.join(video_dir, "movie.nfo")
  226. create_nfo_file(video, nfo_file_path)
  227. print("All videos processed successfully!")
  228. if __name__ == "__main__":
  229. main()