-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathyoutube.py
55 lines (45 loc) · 1.71 KB
/
youtube.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
# coding=utf-8
# (c) Jim Blackler
# Offered as free software under the GNU General Public License v3
import httplib2
from googleapiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import flow_from_clientsecrets, AccessTokenRefreshError
from oauth2client.tools import run
class YouTubeInfo(object):
"""
Authenticates users to the YouTube API via the Google API Client library.
Provides information services about supplied videos.
"""
@staticmethod
def get_authenticated_service():
scope = "https://www.googleapis.com/auth/youtube.readonly"
storage = Storage("tokens/google.json")
credentials = storage.get()
if credentials is None or credentials.invalid:
flow = flow_from_clientsecrets("secrets/google_client_secrets.json",
scope=scope)
credentials = run(flow, storage)
return build("youtube", "v3", http=credentials.authorize(httplib2.Http()))
def category_name(self, id):
if id in self.categoryNames:
return self.categoryNames[id]
info = self.youtube.videoCategories().list(part="id,snippet",id=id).execute()
try:
name = info['items'][0]['snippet']['title']
self.categoryNames[id] = name
return name
except (KeyError, AccessTokenRefreshError):
return None
def info(self, _id, parts):
try :
response = self.youtube.videos().list(part=parts, id=_id).execute()
# Only one result is expected,
if len(response['items']) != 1:
return None
return response['items'][0]
except (KeyError, AccessTokenRefreshError):
return None
def __init__(self):
self.categoryNames = {}
self.youtube = self.get_authenticated_service()