Esempio n. 1
0
    def test_get_images_returns_images(self):
        self.library1.get_images.return_value.get.return_value = {
            'dummy1:track': [Image(uri='uri')]
        }

        result = self.core.library.get_images(['dummy1:track'])
        self.assertEqual({'dummy1:track': (Image(uri='uri'), )}, result)
Esempio n. 2
0
    def test_get_images_returns_images(self):
        self.library1.get_images.return_value.get.return_value = {
            "dummy1:track": [Image(uri="uri")]
        }

        result = self.core.library.get_images(["dummy1:track"])
        assert {"dummy1:track": (Image(uri="uri"), )} == result
Esempio n. 3
0
def _images(field):
    images = []
    for uri in field.split() if field else []:
        m = _IMAGE_SIZE_RE.match(uri)
        if m:
            width = int(m.group(1))
            height = int(m.group(2))
            images.append(Image(uri=uri, width=width, height=height))
        else:
            images.append(Image(uri=uri))
    return images
Esempio n. 4
0
 def add_thumbnail(self,jsdict,uri):
     pics = []
     if 'pictures' in jsdict:
         if 'medium' in jsdict['pictures']:
             pics.append(Image(uri=jsdict['pictures']['medium'])) 
         elif 'large' in jsdict['pictures']:
             pics.append(Image(uri=jsdict['pictures']['large'])) 
         elif 'thumbnail' in jsdict['pictures']:
             pics.append(Image(uri=jsdict['pictures']['thumbnail'])) 
     if len(pics)>0:
         self.images.add(uri,pics) 
     return pics    
Esempio n. 5
0
    def test_get_images_size(self, mock_get_images):
        from mopidy.models import Image
        mock_get_images.return_value = {
            b'local:track:foo.mp3': [Image(uri='/images/foo-640x480.jpeg')],
            b'local:track:bar.mp3': [Image(uri='bar.png', width=10, height=20)]
        }

        images = self.library.get_images([b'local:track:foo.mp3'])
        self.assertEqual(640, images[b'local:track:foo.mp3'][0].width)
        self.assertEqual(480, images[b'local:track:foo.mp3'][0].height)
        self.assertEqual(10, images[b'local:track:bar.mp3'][0].width)
        self.assertEqual(20, images[b'local:track:bar.mp3'][0].height)
Esempio n. 6
0
def test_get_metadata_use_library_image_as_art_url(backend, core, player):
    backend.library.dummy_get_images_result = {
        "dummy:a": [
            Image(uri="http://example.com/small.jpg", width=100, height=100),
            Image(uri="http://example.com/large.jpg", width=200, height=200),
            Image(uri="http://example.com/unsized.jpg"),
        ],
    }
    core.tracklist.add([Track(uri="dummy:a")])
    core.playback.play().get()

    result = player.Metadata

    assert result["mpris:artUrl"] == GLib.Variant(
        "s", "http://example.com/large.jpg")
Esempio n. 7
0
def test_get_images_for_multiple_uris(tmp_path, caplog):
    make_album(tmp_path / "media" / "a1", EXAMPLE_ALBUM)
    make_image(tmp_path / "media" / "a1" / "cover.jpg")
    provider = KitchenLibraryProvider(backend={}, config=make_config(tmp_path))
    track1_uri = provider.browse(str(AlbumsUri()))[0].uri + ":1:1"
    track2_uri = provider.browse(str(AlbumsUri()))[0].uri + ":1:2"
    album_id = parse_uri(track1_uri).album_id

    result = provider.get_images([track1_uri, track2_uri])

    assert caplog.text == ""
    assert result == {
        track1_uri: [Image(uri=f"/kitchen/albums/{album_id}/cover.jpg")],
        track2_uri: [Image(uri=f"/kitchen/albums/{album_id}/cover.jpg")],
    }
Esempio n. 8
0
 def loadTrackRefsFromUser(self, uri):
   refs=[]
   user = uri.strip(mc_uri)
   logger.info("Loading tracks of user " + user)
   r =requests.get(mx_api + user + 'cloudcasts/',timeout=10)
   jsono = json.loads(r.text)
   trackNo = 0
   for p in jsono['data']:
     trackNo += 1      
     trackuri=mc_uri + p['url']
     ref=Ref.track(name=p['name'], uri=trackuri)
     refs.append(ref)
     self.imageCache[trackuri] = Image(uri=p['pictures']['320wx320h'])
     len=int(p['audio_length'])*1000
     album=Album(name='Mixcloud')
     artist=Artist(uri='none',name=p['user']['name'])
     dateString = p['created_time']
     # date format from mixcloud is "2019-12-06T14:21:13Z"
     dateObj = datetime.strptime(dateString, '%Y-%m-%dT%H:%M:%SZ')
     dateStringMop = dateObj.strftime("%Y-%m-%d")
     # synthetic name for proper sorting in Iris UI
     synName = str(trackNo).zfill(2) + '. ' + p['name']
     track=Track(uri=trackuri,name=synName,album=album,artists=[artist],length=len,date=dateStringMop,track_no=trackNo)
     self.trackCache[trackuri] = track
   self.refCache[uri] = refs
   return refs
Esempio n. 9
0
    def test_get_images_merges_results(self):
        self.library1.get_images.return_value.get.return_value = {
            'dummy1:track': [Image(uri='uri1')]
        }
        self.library2.get_images.return_value.get.return_value = {
            'dummy2:track': [Image(uri='uri2')]
        }

        result = self.core.library.get_images(
            ['dummy1:track', 'dummy2:track', 'dummy3:track', 'dummy4:track'])
        expected = {
            'dummy1:track': (Image(uri='uri1'), ),
            'dummy2:track': (Image(uri='uri2'), ),
            'dummy3:track': tuple(),
            'dummy4:track': tuple()
        }
        self.assertEqual(expected, result)
Esempio n. 10
0
 def thumbnails(self):
     # make it "async" for uniformity with Playlist.thumbnails
     identifier = self.id.split(".")[-1]
     self._thumbnails = pykka.ThreadingFuture()
     self._thumbnails.set([
         Image(uri=f"https://i.ytimg.com/vi/{identifier}/{type}.jpg")
         for type in ["default", "mqdefault", "hqdefault"]
     ])
Esempio n. 11
0
    def test_get_images_merges_results(self):
        self.library1.get_images.return_value.get.return_value = {
            "dummy1:track": [Image(uri="uri1")]
        }
        self.library2.get_images.return_value.get.return_value = {
            "dummy2:track": [Image(uri="uri2")]
        }

        result = self.core.library.get_images(
            ["dummy1:track", "dummy2:track", "dummy3:track", "dummy4:track"])
        expected = {
            "dummy1:track": (Image(uri="uri1"), ),
            "dummy2:track": (Image(uri="uri2"), ),
            "dummy3:track": (),
            "dummy4:track": (),
        }
        assert expected == result
Esempio n. 12
0
    def get_images(self, uris):
        result = {}
        for uri in uris:
            result[uri] = []

            variant, identifier = translator.parse_uri(uri)
            if variant != 'station' or not identifier:
                continue

            station = self.backend.dirble.station(identifier)
            if not station or 'image' not in station:
                continue
            elif station['image'].get('url'):
                result[uri].append(Image(uri=station['image']['url']))
            elif station['image'].get('thumb', {}).get('url'):
                result[uri].append(Image(uri=station['image']['thumb']['url']))

        return result
Esempio n. 13
0
    def test_local_library_get_images(self, mock_get_images):
        library = actor.LocalBackend(config=self.config, audio=None).library

        image = Image(uri='imageuri')
        track = Track(uri='trackuri')
        mock_get_images.return_value = {track.uri: [image]}

        result = library.get_images([track.uri])
        self.assertEqual(result, {track.uri: [image]})
Esempio n. 14
0
    def get_images(self, uris):
        result = {}
        for uri in uris:
            images = None
            if uri.startswith('audioteka:album:'):
                images = [Image(uri=self.albums_img[uri])]
            result[uri] = images or ()

        return result
Esempio n. 15
0
    def test_default_get_images_impl_single_track(self, mock_lookup):
        library = actor.LocalBackend(config=self.config, audio=None).library

        image = Image(uri='imageuri')
        album = Album(images=[image.uri])
        track = Track(uri='trackuri', album=album)
        mock_lookup.return_value = track

        result = library.get_images([track.uri])
        self.assertEqual(result, {track.uri: [image]})
Esempio n. 16
0
    def get_images(self, uris):

        images = {}

        for uri in uris:
            channel_name = extract_somafm_channel_name_from_uri(uri)
            if channel_name is not None:
                image = Image(uri=self.backend.somafm.images[channel_name])
                images[uri] = [image]

        return images
Esempio n. 17
0
    def get_images(self, uris):

        images = []

        for uri in uris:
            if uri.startswith("somafm:"):
                channel_name = uri[uri.index("/") + 1:]

                image = Image(uri=self.backend.somafm.images[channel_name])
                images.append(image)

        return images
Esempio n. 18
0
    def loadRootAlbumRefs(self):
        refs = []
        # get the user details
        payload = {'client_id': self.clientId}

        r = requests.get(sc_api + '/users/' + self.userId,
                         params=payload,
                         headers=defaultHeaders,
                         timeout=10)
        jsono = json.loads(r.text)
        # get stream node
        streamUri = scs_uri_stream
        ref = Ref.album(name=myStreamLabel, uri=streamUri)
        imguri = jsono['avatar_url']
        imguri = imguri.replace("large.jpg", imageSelector)
        self.imageCache[streamUri] = Image(uri=imguri)
        refs.append(ref)

        # get followings
        logger.info("Loading followings for user " + self.userId)
        payload = {'client_id': self.clientId, 'limit': limit}
        r = requests.get(sc_api + '/users/' + self.userId + '/followings',
                         params=payload,
                         headers=defaultHeaders,
                         timeout=10)

        if r.status_code != 200:
            logger.warn("Got HTTP " + str(r.status_code))

        jsono = json.loads(r.text)

        for follow in jsono['collection']:
            followingUri = scs_uri_user + str(follow['id'])
            ref = Ref.album(name=follow['username'], uri=followingUri)
            imguri = follow['avatar_url']
            imguri = imguri.replace("large.jpg", imageSelector)
            self.imageCache[followingUri] = Image(uri=imguri)
            refs.append(ref)
        self.refCache[scs_uri_root] = refs
        return refs
Esempio n. 19
0
 def get_images(self, uris):
     results = {}
     for uri in uris:
         variant, identifier = self.parse_uri(uri)
         if variant != "track":
             continue
         chan_data = self.backend.calmradio.get_channel_by_id(identifier)
         url = self.backend.calmradio.urls['calm_arts_host'] + chan_data[
             'image']
         image = Image(uri=url)
         if image is not None:
             results[uri] = [image]
     return results
Esempio n. 20
0
 def get_images(self, uris):
     images = {}
     for uri in uris:
         kitchen_uri = parse_uri(uri)
         if isinstance(kitchen_uri, (AlbumUri, AlbumTrackUri)):
             album_id = kitchen_uri.album_id
             album = self._albums.get(album_id)
             if album:
                 img_path = album.path / "cover.jpg"
                 if img_path.exists():
                     image_uri = f"/kitchen/albums/{album_id}/cover.jpg"
                     images[uri] = [Image(uri=image_uri)]
     return images
Esempio n. 21
0
    def get_images(self, uris):
        logger.debug("Searching Tidal for images for %r" % uris)
        session = self.backend._session
        images = {}
        for uri in uris:
            uri_images = None
            if uri.startswith('tidal:'):
                parts = uri.split(':')
                if parts[1] == 'artist':
                    artist_id = parts[2]
                    img_uri = self.lru_artist_img.hit(artist_id)
                    if img_uri is None:
                        artist = session.get_artist(artist_id)
                        img_uri = artist.image
                        self.lru_artist_img[artist.id] = img_uri

                    uri_images = [Image(uri=img_uri, width=512, height=512)]
                elif parts[1] == 'album':
                    album_id = parts[2]
                    img_uri = self.lru_album_img.hit(album_id)
                    if img_uri is None:
                        album = session.get_album(album_id)
                        img_uri = album.image
                        self.lru_album_img[album_id] = img_uri

                    uri_images = [Image(uri=img_uri, width=512, height=512)]
                elif parts[1] == 'track':
                    album_id = parts[3]
                    img_uri = self.lru_album_img.hit(album_id)
                    if img_uri is None:
                        album = session.get_album(album_id)
                        img_uri = album.image
                        self.lru_album_img[album_id] = img_uri

                    uri_images = [Image(uri=img_uri, width=512, height=512)]
                    pass

            images[uri] = uri_images or ()
        return images
Esempio n. 22
0
 def get_images(self, uris):
     ret = {}
     for uri in uris:
         ret[uri] = []
         component = uri.split(":")
         if re.match(r"^(my)?(track|album|artist)", component[1], re.I):
             bcId = uri.split(":")[2]
             if bcId in self.images:
                 i = self.images[bcId]
                 img = f"https://f4.bcbits.com/img/{i}"
                 for s in self.backend.image_sizes:
                     if s in self.backend.bandcamp.IMAGE_SIZE:
                         d = self.backend.bandcamp.IMAGE_SIZE[s]
                         ret[uri].append(
                             Image(uri=img + f"_{s}.jpg",
                                   width=d[0],
                                   height=d[1]))
                     else:
                         ret[uri].append(Image(uri=img + f"_{s}.jpg"))
         else:
             name = ""
             if len(component) == 3:
                 name = component[2]
             elif len(component) == 2:
                 name = component[
                     1] if component[1] != "browse" else "bandcamp"
             m = hashlib.md5(name.encode("utf-8")).hexdigest()
             for s in self.backend.image_sizes:
                 if s in self.backend.bandcamp.IMAGE_SIZE:
                     d = self.backend.bandcamp.IMAGE_SIZE[s]
                     ret[uri].append(
                         Image(
                             uri=
                             f"https://dummyimage.com/{d[0]}x{d[1]}/{m[0:3]}/{m[3:6]}&text={quote(name)}",
                             width=d[0],
                             height=d[1],
                         ))
     return ret
Esempio n. 23
0
 def loadRootAlbumRefs(self):
   refs=[]
   
   # latest shows
   r =requests.get(mx_api + "/" + self.mxaccount,timeout=10)
   logger.info("Loading root")
   jsono = json.loads(r.text)
   ref = Ref.album(name=latestShowsLabel, uri=mc_uri_stream)
   imguri = jsono['pictures']['320wx320h']
   self.imageCache[mc_uri_stream] = Image(uri=imguri)
   refs.append(ref)
   
   # following's tracks
   r =requests.get(mx_api + "/" + self.mxaccount + '/following/',timeout=10)
   logger.info("Loading followings")
   jsono = json.loads(r.text)
   for p in jsono['data']:
     accounturi = mc_uri + p['key']
     ref = Ref.album(name=p['name'], uri=accounturi)
     self.imageCache[accounturi] = Image(uri=p['pictures']['320wx320h'])
     refs.append(ref)
   self.refCache[mc_uri_root] = refs
   return refs
Esempio n. 24
0
 def _get_images(self, uri):
     parts = uri.split(':')
     if parts[1] == 'track':
         uri = '{0}:album:{2}:{3}'.format(*parts)
         parts = uri.split(':')
     uri_image = image_cache.hit(uri)
     if uri_image is None and self.backend.image_search:
         logger.info('CACHE HIT MISS: %s', uri)
         if parts[1] == 'artist':
             uri_image = self.backend.session.get_artist(artist_id=parts[2]).image
         elif parts[1] == 'album':
             uri_image = self.backend.session.get_album(album_id=parts[3]).image
         logger.info("Setting image cache (%s) with %s = %s", len(image_cache), uri, uri_image)
         image_cache[uri] = uri_image
     return [Image(uri=uri_image, width=512, height=512)] if uri_image else ()
    def get_images(self, uris):
        logger.debug('RadioBrowser: Start backend.RadioBrowserLibrary.get_images')

        result = {}
        for uri in uris:
            variant, identifier = translator.parse_uri(uri)
            if variant != 'station':
                continue

            station = self.backend.radiobrowser.getStation(identifier)
            if not station:
                continue
            
            result[uri] = [Image(uri=station.get('favicon'))]
        return result
Esempio n. 26
0
 def get_images(self, uris):
     result = {}
     for uri in uris:
         uri_images = None
         if uri.startswith('yle:track:'):
             item_url = uri.split(':')
             program_id = item_url[2]
             image_url = self.__yleapi.get_yle_image_url(program_id)
             if image_url:
                 uri_images = [Image(uri=image_url)]
         elif uri.startswith('yle:series:'):
             item_url = uri.split(':')
             series_id = item_url[2]
             album = self.__yleapi.get_yle_album(series_id)
             if album:
                 image_url = self.__yleapi.get_yle_image_url(program_id)
                 if image_url:
                     uri_images = [Image(uri=image_url)]
         elif uri.startswith('yle:liveradio:'):
             image_url = self.__yleapi.get_yle_logo()
             if image_url:
                 uri_images = [Image(uri=image_url)]
         result[uri] = uri_images or ()
     return result
Esempio n. 27
0
 def addThumbnails(self, bId, data, addTracks=True):
     images = []
     if bId not in self.IMAGES and "thumbnails" in data:
         for th in data["thumbnails"]:
             if "url" in th:
                 images.append(
                     Image(
                         uri=th["url"],
                         width=th["width"],
                         height=th["height"],
                     ))
         images.reverse()
         self.IMAGES[bId] = images
         if addTracks and "tracks" in data:
             for song in data["tracks"]:
                 if song["videoId"] not in self.IMAGES:
                     self.IMAGES[song["videoId"]] = images
     return images
Esempio n. 28
0
 def getTrackFromJSON(self, trackJSON, trackNo, trackuri):
     if (trackJSON['artwork_url']):
         artwork = trackJSON['artwork_url']
         artwork = artwork.replace("large.jpg", imageSelector)
         self.imageCache[trackuri] = Image(uri=artwork)
     album = Album(name=trackJSON['user']['username'])
     artist = Artist(uri='none', name=trackJSON['user']['username'])
     dateString = trackJSON['created_at']
     # date information in JSON: "created_at":"2012-06-25T12:03:44Z"
     dateObj = datetime.strptime(dateString, '%Y-%m-%dT%H:%M:%SZ')
     dateStringMop = dateObj.strftime("%Y-%m-%d")
     track = Track(uri=trackuri,
                   name=str(trackNo).zfill(2) + '. ' + trackJSON['title'],
                   album=album,
                   artists=[artist],
                   date=dateStringMop,
                   length=trackJSON['duration'],
                   track_no=trackNo)
     return track
Esempio n. 29
0
def station_to_image(station):
    if station is not None and "image" in station:
        return Image(uri=station["image"])
Esempio n. 30
0
 def raw_imageuri_to_image(self, imageuri):
     return Image(
         uri=imageuri)
Esempio n. 31
0
 def test_height(self):
     image = Image(height=100)
     self.assertEqual(image.height, 100)
     with self.assertRaises(AttributeError):
         image.height = None
Esempio n. 32
0
 def test_width(self):
     image = Image(width=100)
     self.assertEqual(image.width, 100)
     with self.assertRaises(AttributeError):
         image.width = None
Esempio n. 33
0
 def test_uri(self):
     uri = 'an_uri'
     image = Image(uri=uri)
     self.assertEqual(image.uri, uri)
     with self.assertRaises(AttributeError):
         image.uri = None