youtube_model.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. import os
  2. import json
  3. import google.oauth2.credentials
  4. import googleapiclient.discovery
  5. SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl']
  6. API_SERVICE_NAME = 'youtube'
  7. API_VERSION = 'v3'
  8. VIDEO_PARTS = 'snippet,contentDetails,liveStreamingDetails,statistics,recordingDetails'.split(',')
  9. def get_youtube_builder (youtube_user = None):
  10. if youtube_user:
  11. credentials = google.oauth2.credentials.Credentials(
  12. **youtube_user['credentials'])
  13. youtube = googleapiclient.discovery.build(
  14. API_SERVICE_NAME, API_VERSION, credentials=credentials)
  15. else:
  16. print('using developer key for YT api')
  17. developer_key = os.environ.get('GOOGLE_DEVELOPER_KEY')
  18. youtube = googleapiclient.discovery.build(
  19. API_SERVICE_NAME, API_VERSION, developerKey=developer_key)
  20. return youtube
  21. def get_youtube_user (channel_id):
  22. session_path = f'.data/session_{channel_id}.json'
  23. if os.path.exists(session_path):
  24. with open(session_path, 'rt', encoding='utf-8') as f:
  25. return json.load(f)
  26. else:
  27. print(f'No config for channel {channel_id}')
  28. return None
  29. def fetch_video_infos (video_ids, video_parts=VIDEO_PARTS, max_results=50, youtube_user=None):
  30. youtube = get_youtube_builder(youtube_user)
  31. # FIXME add pagination
  32. if len(video_ids) > max_results or max_results > 50:
  33. raise Exception('requesting more videos than max results or supported and pagination is not supported.')
  34. videos = youtube.videos().list(id=video_ids,
  35. part=','.join(video_parts),
  36. maxResults=max_results
  37. ).execute()
  38. return videos['items']