You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.8 KiB
51 lines
1.8 KiB
import googleapiclient
|
|
import googleapiclient.discovery
|
|
|
|
|
|
BASE_URL = 'https://www.youtube.com'
|
|
|
|
|
|
class Youtube(object):
|
|
def __init__(self, api_key, log=None):
|
|
self.client = googleapiclient.discovery.build('youtube', 'v3', developerKey=api_key)
|
|
self.log = log
|
|
|
|
def _search(self, channel_id, query, playlists, limit):
|
|
result = []
|
|
count = limit
|
|
token = ''
|
|
while True:
|
|
resp = self.client.search().list(
|
|
channelId=channel_id,
|
|
q=query,
|
|
safeSearch='none',
|
|
type='playlist' if playlists else 'video',
|
|
maxResults=min(count, 50),
|
|
part='id,snippet',
|
|
pageToken=token).execute()
|
|
for item in resp.get('items', []):
|
|
kind = item['id']['kind'].split('youtube#')[1]
|
|
if kind == 'playlist':
|
|
url = '{0}/view_play_list?p={1}'.format(BASE_URL, item['id']['playlistId'])
|
|
else:
|
|
url = '{0}/watch?v={1}'.format(BASE_URL, item['id']['videoId'])
|
|
result.append(dict(
|
|
kind=kind,
|
|
url=url,
|
|
title=item['snippet']['title']))
|
|
count -= resp['pageInfo']['resultsPerPage']
|
|
if count <= 0:
|
|
break
|
|
token = resp.get('nextPageToken')
|
|
if not token:
|
|
break
|
|
return result
|
|
|
|
def search(self, channel_id, query, playlists=True, limit=None):
|
|
try:
|
|
return self._search(channel_id, query, playlists, limit)
|
|
except googleapiclient.errors.HttpError as e:
|
|
if self.log:
|
|
self.log.error('Failed to query Youtube API: %s', str(e))
|
|
return None
|