threehappypenguins

scheduler.py

Jul 9th, 2024
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.96 KB | None | 0 0
  1. from google.oauth2.credentials import Credentials
  2. from google_auth_oauthlib.flow import InstalledAppFlow
  3. from google.auth.transport.requests import Request
  4. from googleapiclient.discovery import build
  5. import os
  6.  
  7. # Define the scopes required for managing live broadcasts
  8. SCOPES = ['https://www.googleapis.com/auth/youtube',
  9. 'https://www.googleapis.com/auth/youtube.force-ssl']
  10.  
  11. #Text files with metadata
  12. metadata_text_AM = "/srv/dev-disk-by-uuid-49e4aa1a-279a-45ce-b23e-467c2b2a4162/AppData/jobson/specs/youtube-livestream.spec/metadata-AM.txt"
  13. metadata_text_PM = "/srv/dev-disk-by-uuid-49e4aa1a-279a-45ce-b23e-467c2b2a4162/AppData/jobson/specs/youtube-livestream.spec/metadata-PM.txt"
  14.  
  15. # Function to read metadata from the AM file
  16. def read_metadata_AM(filename):
  17. with open(filename, "r") as f:
  18. metadata_AM = {}
  19. for line in f:
  20. key, value = line.strip().split("=")
  21. metadata_AM[key.strip()] = value.strip().replace("\\n", "\n")
  22. return metadata_AM
  23.  
  24. # Function to read metadata from the PM file
  25. def read_metadata_PM(filename):
  26. with open(metadata_text_PM, "r") as f:
  27. metadata_PM = {}
  28. for line in f:
  29. key, value = line.strip().split("=")
  30. metadata_PM[key.strip()] = value.strip().replace("\\n", "\n")
  31. return metadata_PM
  32.  
  33. # Read metadata from the files
  34. metadata_AM = read_metadata_AM(metadata_text_AM)
  35. metadata_PM = read_metadata_PM(metadata_text_PM)
  36.  
  37. #authentication filepaths and files
  38. ls_token = '/srv/dev-disk-by-uuid-49e4aa1a-279a-45ce-b23e-467c2b2a4162/AppData/youtubelivestream/token.json'
  39. ls_credentials = '/srv/dev-disk-by-uuid-49e4aa1a-279a-45ce-b23e-467c2b2a4162/AppData/youtubelivestream/credentials.json'
  40.  
  41. #video ids filepaths and files
  42. video_id_text = "/srv/dev-disk-by-uuid-49e4aa1a-279a-45ce-b23e-467c2b2a4162/AppData/jobson/specs/youtube-livestream.spec/video_id.txt"
  43.  
  44. #AM service metadata
  45. ls_title_AM = metadata_AM.get("ls_title_AM")
  46. ls_description_AM = metadata_AM.get("ls_description_AM")
  47. ls_date_AM = metadata_AM.get("ls_date_AM")
  48. ls_privacy_AM = "public"
  49. thumbnail_AM = "/srv/dev-disk-by-uuid-49e4aa1a-279a-45ce-b23e-467c2b2a4162/WorkFolder/Images/Thumbnails/AMServiceThumbnail.png"
  50. ls_category_AM = "29" # Category ID for Nonprofits & Activism
  51.  
  52. #PM service metadata
  53. ls_title_PM = metadata_PM.get("ls_title_PM")
  54. ls_description_PM = metadata_PM.get("ls_description_PM")
  55. ls_date_PM = metadata_PM.get("ls_date_PM")
  56. ls_privacy_PM = "public"
  57. thumbnail_PM = "/srv/dev-disk-by-uuid-49e4aa1a-279a-45ce-b23e-467c2b2a4162/WorkFolder/Images/Thumbnails/PMServiceThumbnail.png"
  58. ls_category_PM = "29" # Category ID for Nonprofits & Activism
  59.  
  60. #temporary stream key to change the PM service to in order to not conflict with the AM service
  61. desired_stream_key = "main_stream_key_example"
  62.  
  63. # Function to authenticate and build the YouTube API client
  64. def get_authenticated_service():
  65. creds = None
  66. if os.path.exists(ls_token):
  67. creds = Credentials.from_authorized_user_file(ls_token)
  68. if not creds or not creds.valid:
  69. if creds and creds.expired and creds.refresh_token:
  70. creds.refresh(Request())
  71. else:
  72. flow = InstalledAppFlow.from_client_secrets_file(
  73. ls_credentials, SCOPES, access_type='offline')
  74. creds = flow.run_local_server(port=0)
  75. with open(ls_token, 'w') as token:
  76. token.write(creds.to_json())
  77. return build('youtube', 'v3', credentials=creds)
  78.  
  79. # Function to schedule a live video on YouTube
  80. def schedule_live_video(youtube, title, description, start_time, privacy_status):
  81. request_body = {
  82. "snippet": {
  83. "title": title,
  84. "description": description,
  85. "scheduledStartTime": start_time,
  86. },
  87. "status": {
  88. "privacyStatus": privacy_status
  89. },
  90. "contentDetails": {
  91. "enableAutoStart": True,
  92. "enableAutoStop": True,
  93. "enableLowLatency": True,
  94. "enableDvr": True,
  95. "madeForKids": "false",
  96. "selfDeclaredMadeForKids": "false"
  97. }
  98. }
  99. live_broadcast = youtube.liveBroadcasts().insert(
  100. part="snippet,status,contentDetails",
  101. body=request_body
  102. ).execute()
  103.  
  104. return live_broadcast['id']
  105.  
  106. from googleapiclient.http import MediaFileUpload
  107.  
  108. def upload_thumbnail(youtube, video_id, thumbnail_filename):
  109. # Create a MediaFileUpload object for the thumbnail
  110. media = MediaFileUpload(thumbnail_filename, chunksize=-1, resumable=True)
  111.  
  112. # Call the YouTube API to set the thumbnail for the video
  113. request = youtube.thumbnails().set(
  114. videoId=video_id,
  115. media_body=media
  116. )
  117. response = request.execute()
  118. return response
  119.  
  120. def get_live_stream_id_by_key(youtube, stream_key):
  121. request = youtube.liveStreams().list(
  122. part="id,cdn",
  123. mine=True,
  124. fields="items(id,cdn/ingestionInfo/streamName)",
  125. maxResults=50
  126. )
  127. response = request.execute()
  128. for item in response.get('items', []):
  129. stream_id = item.get('id')
  130. cdn_info = item.get('cdn', {})
  131. ingestion_info = cdn_info.get('ingestionInfo', {})
  132. if ingestion_info.get('streamName') == stream_key:
  133. return stream_id
  134. return None
  135.  
  136. # Function to modify the category of a live video
  137. def modify_video_category(youtube, video_id, category_id):
  138. video = youtube.videos().list(
  139. part="snippet",
  140. id=video_id
  141. ).execute()
  142. snippet = video['items'][0]['snippet']
  143. snippet['categoryId'] = category_id
  144.  
  145. request_body = {
  146. "id": video_id,
  147. "snippet": snippet
  148. }
  149. youtube.videos().update(
  150. part="snippet",
  151. body=request_body
  152. ).execute()
  153.  
  154. def main():
  155. youtube = get_authenticated_service()
  156.  
  157. # Schedule the first live video
  158. video_id1 = schedule_live_video(youtube, ls_title_AM, ls_description_AM,
  159. ls_date_AM, ls_privacy_AM)
  160. print("First live video scheduled with ID:", video_id1)
  161.  
  162. # Upload AMServiceThumbnail.png for the first live video
  163. thumbnail_filename1 = thumbnail_AM
  164. thumbnail_response1 = upload_thumbnail(youtube, video_id1, thumbnail_filename1)
  165. thumbnail_url1 = thumbnail_response1["items"][0]["default"]["url"]
  166.  
  167. # Modify the category of the first live video
  168. modify_video_category(youtube, video_id1, ls_category_AM)
  169. print("Modified video category of AM service.")
  170.  
  171. # Retrieve the ID of the live stream associated with the desired stream key
  172. desired_stream_id = get_live_stream_id_by_key(youtube, desired_stream_key)
  173.  
  174. if desired_stream_id:
  175. print("Using temporary live stream key for PM service.")
  176. else:
  177. print("Temporary live stream key not found.")
  178. return
  179.  
  180. # Schedule the second live video and associate it with the existing live stream
  181. video_id2 = schedule_live_video(youtube, ls_title_PM, ls_description_PM,
  182. ls_date_PM, ls_privacy_PM)
  183. print("Second live video scheduled with ID:", video_id2)
  184.  
  185. # Associate the second live video with the existing live stream
  186. youtube.liveBroadcasts().bind(
  187. part="id,contentDetails",
  188. id=video_id2,
  189. streamId=desired_stream_id
  190. ).execute()
  191.  
  192. # Upload PMServiceThumbnail.png for the second live video
  193. thumbnail_filename2 = thumbnail_PM
  194. thumbnail_response2 = upload_thumbnail(youtube, video_id2, thumbnail_filename2)
  195. thumbnail_url2 = thumbnail_response2["items"][0]["default"]["url"]
  196.  
  197. # Modify the category of the second live video
  198. modify_video_category(youtube, video_id2, ls_category_PM)
  199. print("Modified video category of PM service.")
  200.  
  201. # Write the video ids to a file to be used in modifystreamkey.py script
  202. with open(video_id_text, "w") as f:
  203. f.write(f"video_id1 = {video_id1}\n")
  204. f.write(f"video_id2 = {video_id2}\n")
  205.  
  206. if __name__ == "__main__":
  207. main()
Advertisement
Add Comment
Please, Sign In to add comment