From 81df1505fd629ba9324258169de0f1c7e98aa956 Mon Sep 17 00:00:00 2001 From: sigma67 Date: Thu, 9 Jul 2020 19:11:47 +0200 Subject: [PATCH] Fix unsupported locale errors on Linux --- ytmusicapi/helpers.py | 3 +-- ytmusicapi/ytmusic.py | 30 +++++++++++++++++------------- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/ytmusicapi/helpers.py b/ytmusicapi/helpers.py index dfa15c6..fdb5654 100644 --- a/ytmusicapi/helpers.py +++ b/ytmusicapi/helpers.py @@ -50,8 +50,7 @@ def get_authorization(auth): return "SAPISIDHASH " + unix_timestamp + "_" + sha_1.hexdigest() -def to_int(string, language): - locale.setlocale(locale.LC_ALL, language) +def to_int(string): number = string.split(' ')[0] return locale.atoi(number) diff --git a/ytmusicapi/ytmusic.py b/ytmusicapi/ytmusic.py index ad284e4..2b2910e 100644 --- a/ytmusicapi/ytmusic.py +++ b/ytmusicapi/ytmusic.py @@ -5,6 +5,7 @@ import gettext import pkg_resources import ntpath import os +from contextlib import suppress from typing import List, Dict, Union, Tuple from ytmusicapi.helpers import * from ytmusicapi.parsers import * @@ -69,15 +70,20 @@ class YTMusic: supported_languages = [ f for f in pkg_resources.resource_listdir('ytmusicapi', 'locales') ] - if language in supported_languages: - self.language = language - self.lang = gettext.translation('base', - localedir=pkg_resources.resource_filename( - 'ytmusicapi', 'locales'), - languages=[language]) - self.parser = Parser(self.lang) - else: - raise Exception("Language not supported. Supported languages are ") + if language not in supported_languages: + raise Exception("Language not supported. Supported languages are " + ', '.join(supported_languages)) + + try: + locale.setlocale(locale.LC_ALL, language) + except locale.Error: + with suppress(locale.Error): + locale.setlocale(locale.LC_ALL, 'en_US.UTF8') + self.lang = gettext.translation('base', + localedir=pkg_resources.resource_filename( + 'ytmusicapi', 'locales'), + languages=[language]) + self.parser = Parser(self.lang) if user: self.context['context']['user']['onBehalfOfUser'] = user @@ -822,8 +828,7 @@ class YTMusic: if len(header['secondSubtitle']['runs']) > 1: song_count = to_int( - unicodedata.normalize("NFKD", header['secondSubtitle']['runs'][0]['text']), - self.language) + unicodedata.normalize("NFKD", header['secondSubtitle']['runs'][0]['text'])) playlist['duration'] = header['secondSubtitle']['runs'][2]['text'] else: playlist['duration'] = header['secondSubtitle']['runs'][0]['text'] @@ -1167,8 +1172,7 @@ class YTMusic: album['year'] = nav(header, SUBTITLE3) if len(header['secondSubtitle']['runs']) > 1: - album['trackCount'] = to_int(header['secondSubtitle']['runs'][0]['text'], - self.language) + album['trackCount'] = to_int(header['secondSubtitle']['runs'][0]['text']) album['duration'] = header['secondSubtitle']['runs'][2]['text'] else: album['duration'] = header['secondSubtitle']['runs'][0]['text']