[Streams] Set YouTube channel name when added by ID (#2047)

* [Streams] Set YouTube channel name when added by ID

Signed-off-by: Toby Harradine <tobyharradine@gmail.com>

* Move unset token raise to correct place

Signed-off-by: Toby Harradine <tobyharradine@gmail.com>

* Correct logic in get_stream

Signed-off-by: Toby Harradine <tobyharradine@gmail.com>

* Fetch name explicitly instead

Signed-off-by: Toby Harradine <tobyharradine@gmail.com>
This commit is contained in:
Toby Harradine 2018-08-26 23:53:47 +10:00 committed by GitHub
parent 0cf54ec9c2
commit 93138b04cb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 22 additions and 3 deletions

View File

@ -472,7 +472,7 @@ class Streams:
return stream
elif not self.check_name_or_id(name) and stream.id == name:
return stream
if stream.type == _class.__name__ and stream.name.lower() == name.lower():
elif stream.type == _class.__name__ and stream.name.lower() == name.lower():
return stream
def get_community(self, _class, name):

View File

@ -152,8 +152,14 @@ class YoutubeStream(Stream):
super().__init__(**kwargs)
async def is_online(self):
if not self._token:
raise InvalidYoutubeCredentials("YouTube API key is not set.")
if not self.id:
self.id = await self.fetch_id()
elif not self.name:
self.name = await self.fetch_name()
url = YOUTUBE_SEARCH_ENDPOINT
params = {
"key": self._token,
@ -188,7 +194,20 @@ class YoutubeStream(Stream):
return embed
async def fetch_id(self):
params = {"key": self._token, "forUsername": self.name, "part": "id"}
return await self._fetch_channel_resource("id")
async def fetch_name(self):
snippet = await self._fetch_channel_resource("snippet")
return snippet["title"]
async def _fetch_channel_resource(self, resource: str):
params = {"key": self._token, "part": resource}
if resource == "id":
params["forUsername"] = self.name
else:
params["id"] = self.id
async with aiohttp.ClientSession() as session:
async with session.get(YOUTUBE_CHANNELS_ENDPOINT, params=params) as r:
data = await r.json()
@ -202,7 +221,7 @@ class YoutubeStream(Stream):
elif "items" in data and len(data["items"]) == 0:
raise StreamNotFound()
elif "items" in data:
return data["items"][0]["id"]
return data["items"][0][resource]
raise APIError()
def __repr__(self):