def get_artist_bio(self):
        """
        Returns tuple of summary and full bio
        """
        cl = CoverLocale()
        lang = cl.get_locale()[:2]

        def get_bio(lang):
            data = self.artist["info_" + lang]["data"]
            if data is None:
                return None

            if not self.artist["info_" + lang]["parsed"]:
                content = data["artist"]["bio"]["content"]
                summary = data["artist"]["bio"]["summary"]
                return summary, content

            if lang != "en":
                return None
            else:
                return self.artist["info_" + lang]["data"]["bio"]

        arg = get_bio(lang)
        if not arg or arg[0] == "":
            arg = get_bio("en")

        return arg
    def get_similar_info(self):
        """
        Returns the dictionary { 'images', 'bio' }
        """
        cl = CoverLocale()
        lang = cl.get_locale()[:2]

        try:
            if not self.artist['similar_' + lang]['parsed']:
                json_artists_data = self.artist['similar_' +
                                                lang]['data']['similarartists']

                results = []
                print(json_artists_data)
                for json_artist in json_artists_data["artist"]:
                    print(json_artist)
                    name = json_artist["name"]
                    image_url = json_artist["image"][1]["#text"]
                    similarity = int(100 * float(json_artist["match"]))

                    results.append({
                        'name': name,
                        'image_url': image_url,
                        'similarity': similarity
                    })

                self.artist['similar_' + lang]['data'] = results
                self.artist['similar_' + lang]['parsed'] = True

            return self.artist['similar_' + lang]['data']
        except Exception as e:
            print("Error parsing similar_infot: %s" % e)
            return ""
    def fetch_album_info(self, artist, album, index):
        print("start fetch_album_info")
        cl = CoverLocale()
        lang = cl.get_locale()[:2]
        qartist = urllib.parse.quote_plus(artist)
        qalbum = urllib.parse.quote_plus(album)
        self.fetched = 2

        def fetch_information(lang):
            cachekey = "lastfm:album:getinfojson:%s:%s:%s" % (qartist, qalbum, lang)
            url = "%s?method=album.getinfo&artist=%s&album=%s&api_key=%s&format=json&lang=%s" % (
                LastFM.API_URL,
                qartist,
                qalbum,
                LastFM.API_KEY,
                lang,
            )
            print(url)

            self.info_cache.fetch(cachekey, url, self.parse_album_info, album, index, lang)

        self.album_data = {}
        fetch_information("en")
        fetch_information(lang)
        print("end fetch_album_info")
    def get_similar_info(self):
        """
        Returns the dictionary { 'images', 'bio' }
        """
        cl = CoverLocale()
        lang = cl.get_locale()[:2]

        try:
            if not self.artist["similar_" + lang]["parsed"]:
                json_artists_data = self.artist["similar_" + lang]["data"]["similarartists"]

                results = []
                print(json_artists_data)
                for json_artist in json_artists_data["artist"]:
                    print(json_artist)
                    name = json_artist["name"]
                    image_url = json_artist["image"][1]["#text"]
                    similarity = int(100 * float(json_artist["match"]))

                    results.append({"name": name, "image_url": image_url, "similarity": similarity})

                self.artist["similar_" + lang]["data"] = results
                self.artist["similar_" + lang]["parsed"] = True

            return self.artist["similar_" + lang]["data"]
        except Exception as e:
            print("Error parsing similar_infot: %s" % e)
            return ""
    def get_artist_bio(self):
        """
        Returns tuple of summary and full bio
        """
        cl = CoverLocale()
        lang = cl.get_locale()[:2]

        def get_bio(lang):
            data = self.artist['info_' + lang]['data']
            if data is None:
                return None

            if not self.artist['info_' + lang]['parsed']:
                content = data['artist']['bio']['content']
                summary = data['artist']['bio']['summary']
                return summary, content

            if lang != 'en':
                return None
            else:
                return self.artist['info_' + lang]['data']['bio']

        arg = get_bio(lang)
        if not arg or arg[0] == '':
            arg = get_bio('en')

        return arg
    def __init__(self, plugin, sprite_name, size=None):
        popups = rb.find_plugin_file(plugin, 'img/popups.xml')
        root = ET.parse(open(popups)).getroot()
        base = 'theme/theme[@folder_name="' + Theme(plugin).current \
               + '"]/spritesheet[@name="' + sprite_name + '"]/'
        image = rb.find_plugin_file(plugin, 'img/' + Theme(plugin).current \
                                    + '/' + root.xpath(base + 'image')[0].text)
        icon_width = int(root.xpath(base + 'icon')[0].attrib['width'])
        icon_height = int(root.xpath(base + 'icon')[0].attrib['height'])
        x_spacing = int(root.xpath(base + 'spacing')[0].attrib['x'])
        y_spacing = int(root.xpath(base + 'spacing')[0].attrib['y'])
        x_start = int(root.xpath(base + 'start-position')[0].attrib['x'])
        y_start = int(root.xpath(base + 'start-position')[0].attrib['y'])
        across_dimension = int(
            root.xpath(base + 'dimension')[0].attrib['across'])
        down_dimension = int(root.xpath(base + 'dimension')[0].attrib['down'])

        try:
            alpha_color = list(
                map(int,
                    root.xpath(base + 'alpha')[0].text.split(' ')))
        except:
            alpha_color = None

        self.names = []
        self.locale_names = {}

        cl = CoverLocale()
        lang = cl.get_locale()

        base = sprite_name + '/' + sprite_name + \
               '[@spritesheet="' + sprite_name + '"]'

        for elem in root.xpath(base + '[not(@xml:lang)]'):
            self.names.append(elem.text)

        for elem in root.xpath(base + '[@xml:lang="' + lang + '"]'):
            self.locale_names[elem.text] = elem.attrib['name']

        if (not self.locale_names) and len(lang) > 2:
            for elem in root.xpath(base + '[@xml:lang="' + \
                    lang[0:2] + '"]'):
                self.locale_names[elem.text] = elem.attrib['name']

        self._sheet = SpriteSheet(image, icon_width, icon_height, x_spacing,
                                  y_spacing, x_start, y_start,
                                  across_dimension, down_dimension,
                                  alpha_color, size)

        self._genre_db = RB.ExtDB(name='cb_genre')
    def parse_album_info(self, data, album, index, lang):
        print('parse_album_info %s' % lang)
        self.fetched = self.fetched - 1
        self.album_data[lang] = data
        if self.fetched > 0:
            print('return %d' % self.fetched)
            return

        cl = CoverLocale()
        lang = cl.get_locale()[:2]
        rv = True
        try:
            print('decoding')
            parsed = json.loads(self.album_data[lang].decode('utf-8'))
            print('decoded')
            self.albums[index]['id'] = parsed['album']['id']
            for k in ('releasedate', 'summary'):
                self.albums[index][k] = parsed['album'].get(k)
            tracklist = []
            print(parsed['album'])
            tracks = parsed['album']['tracks'].get('track', [])
            for i, t in enumerate(tracks):
                title = t['name']
                duration = int(t['duration'])
                tracklist.append((i, title, duration))
            self.albums[index]['tracklist'] = tracklist
            self.albums[index]['duration'] = sum([t[2] for t in tracklist])

            if 'wiki' in parsed['album']:
                self.albums[index]['wiki-summary'] = parsed['album']['wiki'][
                    'summary']
                self.albums[index]['wiki-content'] = parsed['album']['wiki'][
                    'content']
            elif lang != 'en':
                parsed = json.loads(self.album_data['en'].decode('utf-8'))
                if 'wiki' in parsed['album']:
                    self.albums[index]['wiki-summary'] = parsed['album'][
                        'wiki']['summary']
                    self.albums[index]['wiki-content'] = parsed['album'][
                        'wiki']['content']
        except Exception as e:
            print("Error parsing album tracklist: %s" % e)
            rv = False

        self.fetching -= 1
        print("%s albums left to process" % self.fetching)
        if self.fetching == 0:
            self.emit('albums-ready')
        return rv
    def __init__(self, plugin, sprite_name, size=None):
        popups = rb.find_plugin_file(plugin, 'img/popups.xml')
        root = ET.parse(open(popups)).getroot()
        base = 'theme/theme[@folder_name="' + Theme(plugin).current \
               + '"]/spritesheet[@name="' + sprite_name + '"]/'
        image = rb.find_plugin_file(plugin, 'img/' + Theme(plugin).current \
                                    + '/' + root.xpath(base + 'image')[0].text)
        icon_width = int(root.xpath(base + 'icon')[0].attrib['width'])
        icon_height = int(root.xpath(base + 'icon')[0].attrib['height'])
        x_spacing = int(root.xpath(base + 'spacing')[0].attrib['x'])
        y_spacing = int(root.xpath(base + 'spacing')[0].attrib['y'])
        x_start = int(root.xpath(base + 'start-position')[0].attrib['x'])
        y_start = int(root.xpath(base + 'start-position')[0].attrib['y'])
        across_dimension = int(root.xpath(base + 'dimension')[0].attrib['across'])
        down_dimension = int(root.xpath(base + 'dimension')[0].attrib['down'])

        try:
            alpha_color = list(map(int,
                                   root.xpath(base + 'alpha')[0].text.split(' ')))
        except:
            alpha_color = None

        self.names = []
        self.locale_names = {}

        cl = CoverLocale()
        lang = cl.get_locale()

        base = sprite_name + '/' + sprite_name + \
               '[@spritesheet="' + sprite_name + '"]'

        for elem in root.xpath(base + '[not(@xml:lang)]'):
            self.names.append(elem.text)

        for elem in root.xpath(base + '[@xml:lang="' + lang + '"]'):
            self.locale_names[elem.text] = elem.attrib['name']

        if (not self.locale_names) and len(lang) > 2:
            for elem in root.xpath(base + '[@xml:lang="' + \
                    lang[0:2] + '"]'):
                self.locale_names[elem.text] = elem.attrib['name']

        self._sheet = SpriteSheet(image, icon_width, icon_height, x_spacing,
                                  y_spacing, x_start, y_start, across_dimension, down_dimension,
                                  alpha_color, size)

        self._genre_db = RB.ExtDB(name='cb_genre')
    def _parse_popups(self, plugin, root, genre_type):
        icon_names = {}
        cl = CoverLocale()
        lang = cl.get_locale()

        base = self._sprite_name + '/alt'
        for elem in root.xpath(base + '[not(@xml:lang)]/alt'):
            self.genre_alternate[GenreType(name=elem.text, genre_type=genre_type)] = elem.attrib['genre']

        for elem in root.xpath(base + '[@xml:lang="' + lang + '"]/alt'):
            self.genre_alternate[GenreType(name=elem.text, genre_type=self.GENRE_LOCALE)] = elem.attrib['genre']

        # if (not self.locale_alternate) and len(lang) > 2:
        if len(lang) > 2:
            for elem in root.xpath(base + '[@xml:lang="' + \
                    lang[0:2] + '"]/alt'):
                self.genre_alternate[GenreType(name=elem.text, genre_type=self.GENRE_LOCALE)] = elem.attrib['genre']
    def fetch_album_list(self, artist):
        if LastFM.user_has_account() is False:
            self.error = LASTFM_NO_ACCOUNT_ERROR
            self.emit('albums-ready')
            return

        cl = CoverLocale()
        lang = cl.get_locale()[:2]

        self.artist = artist
        qartist = urllib.parse.quote_plus(artist)
        self.error = None
        url = "%s?method=artist.gettopalbums&artist=%s&api_key=%s&format=json&lang=%s" % (
            LastFM.API_URL, qartist, LastFM.API_KEY, lang)
        print(url)
        cachekey = 'lastfm:artist:gettopalbumsjson:%s' % qartist
        self.ranking_cache.fetch(cachekey, url, self.parse_album_list, artist)
    def parse_album_info(self, data, album, index, lang):
        print("parse_album_info %s" % lang)
        self.fetched = self.fetched - 1
        self.album_data[lang] = data
        if self.fetched > 0:
            print("return %d" % self.fetched)
            return

        cl = CoverLocale()
        lang = cl.get_locale()[:2]
        rv = True
        try:
            print("decoding")
            parsed = json.loads(self.album_data[lang].decode("utf-8"))
            print("decoded")
            self.albums[index]["id"] = parsed["album"]["id"]
            for k in ("releasedate", "summary"):
                self.albums[index][k] = parsed["album"].get(k)
            tracklist = []
            print(parsed["album"])
            tracks = parsed["album"]["tracks"].get("track", [])
            for i, t in enumerate(tracks):
                title = t["name"]
                duration = int(t["duration"])
                tracklist.append((i, title, duration))
            self.albums[index]["tracklist"] = tracklist
            self.albums[index]["duration"] = sum([t[2] for t in tracklist])

            if "wiki" in parsed["album"]:
                self.albums[index]["wiki-summary"] = parsed["album"]["wiki"]["summary"]
                self.albums[index]["wiki-content"] = parsed["album"]["wiki"]["content"]
            elif lang != "en":
                parsed = json.loads(self.album_data["en"].decode("utf-8"))
                if "wiki" in parsed["album"]:
                    self.albums[index]["wiki-summary"] = parsed["album"]["wiki"]["summary"]
                    self.albums[index]["wiki-content"] = parsed["album"]["wiki"]["content"]
        except Exception as e:
            print("Error parsing album tracklist: %s" % e)
            rv = False

        self.fetching -= 1
        print("%s albums left to process" % self.fetching)
        if self.fetching == 0:
            self.emit("albums-ready")
        return rv
    def __init__(self, info_cache, ranking_cache):
        GObject.GObject.__init__(self)

        self.current_artist = None
        self.error = None
        cl = CoverLocale()
        lang = cl.get_locale()[:2]

        self.artist = {
            'info_en': {
                'data': None,
                'function': 'getinfo',
                'cache': info_cache,
                'signal': 'artist-info-ready',
                'parsed': False,
                'lang': 'en'
            },
            'similar_en': {
                'data': None,
                'function': 'getsimilar',
                'cache': info_cache,
                'signal': 'artist-info-ready',
                'parsed': False,
                'lang': 'en'
            }
        }

        if lang != 'en':
            self.artist['info_' + lang] = {
                'data': None,
                'function': 'getinfo',
                'cache': info_cache,
                'signal': 'artist-info-ready',
                'parsed': False,
                'lang': lang
            }
            self.artist['similar_' + lang] = {
                'data': None,
                'function': 'getsimilar',
                'cache': info_cache,
                'signal': 'artist-info-ready',
                'parsed': False,
                'lang': lang
            }
    def __init__(self, info_cache, ranking_cache):
        GObject.GObject.__init__(self)

        self.current_artist = None
        self.error = None
        cl = CoverLocale()
        lang = cl.get_locale()[:2]

        self.artist = {
            "info_en": {
                "data": None,
                "function": "getinfo",
                "cache": info_cache,
                "signal": "artist-info-ready",
                "parsed": False,
                "lang": "en",
            },
            "similar_en": {
                "data": None,
                "function": "getsimilar",
                "cache": info_cache,
                "signal": "artist-info-ready",
                "parsed": False,
                "lang": "en",
            },
        }

        if lang != "en":
            self.artist["info_" + lang] = {
                "data": None,
                "function": "getinfo",
                "cache": info_cache,
                "signal": "artist-info-ready",
                "parsed": False,
                "lang": lang,
            }
            self.artist["similar_" + lang] = {
                "data": None,
                "function": "getsimilar",
                "cache": info_cache,
                "signal": "artist-info-ready",
                "parsed": False,
                "lang": lang,
            }
    def get_artist_info(self):
        """
        Returns the dictionary { 'images', 'bio' }
        """
        cl = CoverLocale()
        lang = cl.get_locale()[:2]

        images = self.get_artist_images()

        def fill_info(lang):
            if not self.artist["info_" + lang]["parsed"]:
                bio = self.get_artist_bio()
                self.artist["info_" + lang]["data"] = {"images": images, "bio": bio}
                self.artist["info_" + lang]["parsed"] = True

            return self.artist["info_" + lang]["data"]

        fill_info("en")
        return fill_info(lang)
    def fetch_album_list(self, artist):
        if LastFM.user_has_account() is False:
            self.error = LASTFM_NO_ACCOUNT_ERROR
            self.emit("albums-ready")
            return

        cl = CoverLocale()
        lang = cl.get_locale()[:2]

        self.artist = artist
        qartist = urllib.parse.quote_plus(artist)
        self.error = None
        url = "%s?method=artist.gettopalbums&artist=%s&api_key=%s&format=json&lang=%s" % (
            LastFM.API_URL,
            qartist,
            LastFM.API_KEY,
            lang,
        )
        print(url)
        cachekey = "lastfm:artist:gettopalbumsjson:%s" % qartist
        self.ranking_cache.fetch(cachekey, url, self.parse_album_list, artist)
示例#16
0
    def _parse_popups(self, plugin, root, genre_type):
        icon_names = {}
        cl = CoverLocale()
        lang = cl.get_locale()

        base = self._sprite_name + '/alt'
        for elem in root.xpath(base + '[not(@xml:lang)]/alt'):
            self.genre_alternate[GenreType(
                name=elem.text, genre_type=genre_type)] = elem.attrib['genre']

        for elem in root.xpath(base + '[@xml:lang="' + lang + '"]/alt'):
            self.genre_alternate[GenreType(
                name=elem.text,
                genre_type=self.GENRE_LOCALE)] = elem.attrib['genre']

        # if (not self.locale_alternate) and len(lang) > 2:
        if len(lang) > 2:
            for elem in root.xpath(base + '[@xml:lang="' + \
                    lang[0:2] + '"]/alt'):
                self.genre_alternate[GenreType(
                    name=elem.text,
                    genre_type=self.GENRE_LOCALE)] = elem.attrib['genre']
    def get_artist_info(self):
        """
        Returns the dictionary { 'images', 'bio' }
        """
        cl = CoverLocale()
        lang = cl.get_locale()[:2]

        images = self.get_artist_images()

        def fill_info(lang):
            if not self.artist['info_' + lang]['parsed']:
                bio = self.get_artist_bio()
                self.artist['info_' + lang]['data'] = {
                    'images': images,
                    'bio': bio
                }
                self.artist['info_' + lang]['parsed'] = True

            return self.artist['info_' + lang]['data']

        fill_info('en')
        return fill_info(lang)
    def fetch_album_info(self, artist, album, index):
        print('start fetch_album_info')
        cl = CoverLocale()
        lang = cl.get_locale()[:2]
        qartist = urllib.parse.quote_plus(artist)
        qalbum = urllib.parse.quote_plus(album)
        self.fetched = 2

        def fetch_information(lang):
            cachekey = "lastfm:album:getinfojson:%s:%s:%s" % (qartist, qalbum,
                                                              lang)
            url = "%s?method=album.getinfo&artist=%s&album=%s&api_key=%s&format=json&lang=%s" % (
                LastFM.API_URL, qartist, qalbum, LastFM.API_KEY, lang)
            print(url)

            self.info_cache.fetch(cachekey, url, self.parse_album_info, album,
                                  index, lang)

        self.album_data = {}
        fetch_information('en')
        fetch_information(lang)
        print('end fetch_album_info')