-
Notifications
You must be signed in to change notification settings - Fork 0
/
youtube_client.py
79 lines (58 loc) · 2.29 KB
/
youtube_client.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import os
import google_auth_oauthlib.flow
import googleapiclient.discovery
import youtube_dl
class Playlist(object):
def __init__(self, id, title):
self.id = id
self.title = title
class Song(object):
def __init__(self, artist, track):
self.artist = artist
self.track = track
class YouTubeClient(object):
def __init__(self, credentials_location):
scopes = ["https://www.googleapis.com/auth/youtube.readonly"]
# Disable OAuthlib's HTTPS verification when running locally.
# *DO NOT* leave this option enabled in production.
os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"
api_service_name = "youtube"
api_version = "v3"
# Get credentials and create an API client
flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
credentials_location, scopes)
credentials = flow.run_console()
youtube_client = googleapiclient.discovery.build(
api_service_name, api_version, credentials=credentials)
self.youtube_client = youtube_client
def get_playlists(self):
request = self.youtube_client.playlists().list(
part="id, snippet",
maxResults=50,
mine=True
)
response = request.execute()
playlists = [Playlist(item['id'], item['snippet']['title']) for item in response['items']]
return playlists
def get_videos_from_playlist(self, playlist_id):
songs = []
request = self.youtube_client.playlistItems().list(
playlistId=playlist_id,
part="id, snippet",
maxResults=50
)
response = request.execute()
for item in response['items']:
video_id = item['snippet']['resourceId']['videoId']
artist, track = self.get_artist_and_track_from_video(video_id)
if artist and track:
songs.append(Song(artist, track))
return songs
def get_artist_and_track_from_video(self, video_id):
youtube_url = f"https://www.youtube.com/watch?v={video_id}"
video = youtube_dl.YoutubeDL({'quiet': True}).extract_info(
youtube_url, download=False
)
artist = video['artist']
track = video['track']
return artist, track