-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathyoutubeAPI.py
More file actions
173 lines (120 loc) · 4.67 KB
/
youtubeAPI.py
File metadata and controls
173 lines (120 loc) · 4.67 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import json
import logging
import time
from html import unescape
import requests
from urllib.parse import parse_qs, urlparse
import googleapiclient.discovery
import click
import cache
import functions
with open('./config/token.json', 'r') as f:
token = json.load(f)
if token['youtube_data_API_v3_key'] != '':
youtube = googleapiclient.discovery.build("youtube", "v3", developerKey = token['youtube_data_API_v3_key'])
else:
click.secho('No YouTube data API v3 key: search will use slower method, playlist importing will not work',fg='yellow')
def search(search):
"""Returns a youtube video title and a url from a search term"""
start_time = time.time()
jsn = []
c = cache.load(search,0)
if c == None:
try:
request = youtube.search().list(
part="snippet",
maxResults=1,
q=search
)
response = request.execute()
except Exception as e:
logging.error("Youtube API v3 Error - falling back to youtube_search() - "+str(e))
return functions.youtube_search(search)
if len(response["items"]) == 0:
logging.info("No results found")
return None
try:
jsn = [{
"source": "https://www.youtube.com/watch?v="+response['items'][0]['id']['videoId'],
"title": unescape(response['items'][0]['snippet']['title'])
}]
except Exception as e:
logging.error("Youtube API v3 Error - falling back to youtube_search() - "+str(e))
return functions.youtube_search(search)
cache.save(search,jsn[0]["source"],jsn[0]["title"],0)
else:
jsn.extend(c)
t = str(round((time.time()-start_time)*1000))+'ms'
logging.info("Found: \x1B[4m"+jsn[0]["title"]+"\x1B[0m in "+t)
return jsn
def playlist(url):
"""Returns a list of urls from a youtube playlist"""
start_time = time.time()
query = parse_qs(urlparse(url).query, keep_blank_values=True)
playlist_id = query["list"][0]
jsn = []
c = cache.load(playlist_id,1)
if c == None:
try:
request = youtube.playlistItems().list(
part = "snippet",
playlistId = playlist_id,
maxResults = 1
)
except:
logging.error('To use playlist import add a YouTube API v3 key')
return None
try:
response = request.execute()
except Exception as e:
logging.error("Error in request - "+str(e))
return []
playlist_items = []
while request is not None:
response = request.execute()
playlist_items += response["items"]
request = youtube.playlistItems().list_next(request, response)
#still gotta use this until I change cache.save()
urls = []
titles = []
for t in playlist_items:
jsn.append(
{
"source": 'https://www.youtube.com/watch?v='+t["snippet"]["resourceId"]["videoId"],
"title": t["snippet"]["title"],
"playlist": url
})
urls.append('https://www.youtube.com/watch?v='+t["snippet"]["resourceId"]["videoId"])
titles.append(t["snippet"]["title"])
cache.save(playlist_id,urls,titles,1)
else:
for i in c:
jsn.append(i)
t = str(round((time.time()-start_time)*1000))+'ms'
logging.info("Got {} items from {} in {}".format(len(jsn),playlist_id,t))
return jsn
def related(url,amount=10):
'''Returns related music videos'''
if 'youtube' in url:
url = url.split('watch?v=')[-1]
else:
return None
URL = 'https://youtube.googleapis.com/youtube/v3/search?part=snippet&relatedToVideoId={}&maxResults={}&type=video&key={}&topicId=%2Fm%2F04rlf'.format(url,amount,token['youtube_data_API_v3_key'])
data = requests.get(URL)
if data.status_code != 200:
logging.error('Error in request: '+str(data))
raise 'Error in request'
d = json.loads(data.text)
jsn = []
for item in d['items']:
url = 'https://www.youtube.com/watch?v='+item['id']['videoId']
try:
title = item['snippet']['title']
except:
#some results are deleted videos they keep id's but dont contain snippets
continue
jsn.append({
"source": url,
"title": title,
})
return jsn