예제 #1
0
 def handle_events(self, results):
     places = ItemList()
     if not isinstance(results, list):
         results = [results]
     for venue in results:
         venuename = venue['venue_name']
         lat = venue['latitude']
         lon = venue['longitude']
         googlemap = googlemaps.get_static_map(lat=lat,
                                               lon=lon)
         photo = venue["image"]["large"]["url"] if venue.get("image") else ""
         if venue["start_time"] == venue["stop_time"] or not venue["stop_time"]:
             date = venue["start_time"]
         elif venue["start_time"][:10] == venue["stop_time"][:10]:
             date = venue["start_time"] + " - " + venue["stop_time"][:10]
             date = re.sub(r"\d{2}:\d{2}:\d{2}", "", date)
         else:
             date = venue["start_time"] + " - " + venue["stop_time"]
             date = re.sub(r"\d{2}:\d{2}:\d{2}", "", date)
         item = VideoItem(label=venuename,
                          label2=date.replace("00:00:00", ""))
         item.set_properties({"id": str(venue['id']),
                              "eventful_id": str(venue['venue_id']),
                              "eventname": venue['title'],
                              "description": venue['description'],
                              "name": venuename,
                              "date": date,
                              "address": venue["venue_address"],
                              "lat": lat,
                              "lon": lon})
         item.set_artwork({"thumb": photo,
                           "googlemap": googlemap})
         places.append(item)
     return places
예제 #2
0
def get_icon_panel(number):
    """
    get icon panel with index *number, returns dict list based on skin strings
    """
    items = ItemList()
    offset = number * 5 - 5
    for i in xrange(1, 6):
        infopanel_path = utils.get_skin_string("IconPanelItem%i.Path" %
                                               (i + offset))
        item = ListItem(label=utils.get_skin_string("IconPanelItem%i.Label" %
                                                    (i + offset)),
                        path="plugin://script.extendedinfo/?info=action&&id=" +
                        infopanel_path)
        item.set_artwork({
            'thumb':
            utils.get_skin_string("IconPanelItem%i.Icon" % (i + offset))
        })
        item.set_properties({
            'type':
            utils.get_skin_string("IconPanelItem%i.Type" % (i + offset)),
            'id':
            "IconPanelitem%i" % (i + offset)
        })
        items.append(item)
    return items
예제 #3
0
def handle_events(results):
    events = ItemList()
    for event in results:
        venue = event['venue']
        item = VideoItem(label=venue['name'])
        item.set_properties({
            'date':
            event['datetime'].replace("T", " - ").replace(":00", "", 1),
            'city':
            venue['city'],
            'lat':
            venue['latitude'],
            'lon':
            venue['longitude'],
            'id':
            venue['id'],
            'url':
            venue['url'],
            'region':
            venue['region'],
            'country':
            venue['country'],
            'artists':
            " / ".join([art for art in event["artists"]])
        })
        events.append(item)
    return events
예제 #4
0
def handle_channels(results):
    """
    process channel api result to ItemList
    """
    channels = ItemList(content_type="videos")
    for item in results:
        snippet = item["snippet"]
        thumb = snippet["thumbnails"]["high"]["url"] if "thumbnails" in snippet else ""
        try:
            channel_id = item["id"]["channelId"]
        except Exception:
            channel_id = snippet["resourceId"]["channelId"]
        channel = VideoItem(label=snippet["title"],
                            path=PLUGIN_BASE + 'youtubechannel&&id=%s' % channel_id)
        channel.set_infos({'plot': snippet["description"],
                           'mediatype': "video",
                           'premiered': snippet["publishedAt"][:10]})
        channel.set_art("thumb", thumb)
        channel.set_properties({"youtube_id": channel_id,
                                "type": "channel"})
        channels.append(channel)
    channel_ids = [item.get_property("youtube_id") for item in channels]
    params = {"id": ",".join(channel_ids),
              "part": "contentDetails,statistics,brandingSettings"}
    ext_results = get_data(method="channels",
                           params=params)
    for item, ext_item in itertools.product(channels, ext_results["items"]):
        if item.get_property("youtube_id") == ext_item['id']:
            item.set_property("itemcount", ext_item['statistics']['videoCount'])
            item.set_art("fanart", ext_item["brandingSettings"]["image"].get("bannerTvMediumImageUrl"))
    return channels
예제 #5
0
def get_movies(movie_type):
    movies = ItemList(content_type="movies")
    url = '%s.json?apikey=%s' % (movie_type, RT_KEY)
    results = utils.get_JSON_response(BASE_URL + url, folder="RottenTomatoes")
    if "error" in results:
        utils.notify("Error", results["error"])
    if not results or "movies" not in results:
        return []
    for item in results["movies"]:
        if "alternate_ids" not in item:
            continue
        imdb_id = str(item["alternate_ids"]["imdb"])
        if addon.bool_setting("infodialog_onclick"):
            path = PLUGIN_BASE + 'extendedinfo&&imdb_id=%s' % imdb_id
        else:
            search_string = "%s %s trailer" % (item["title"], item["year"])
            path = PLUGIN_BASE + "playtrailer&&title=%s&&imdb_id=%s" % (search_string, imdb_id)
        movie = VideoItem(label=item.get('title'),
                          path=path)
        movie.set_infos({'title': item["title"],
                         'mediatype': "movie",
                         'duration': item["runtime"] * 60,
                         'year': item["year"],
                         'premiered': item["release_dates"].get("theater", ""),
                         'rating': item["ratings"]["audience_score"] / 10.0,
                         'plot': item["synopsis"],
                         'imdbnumber': imdb_id,
                         'mpaa': item["mpaa_rating"]})
        movie.set_properties({'imdb_id': imdb_id})
        movie.set_artwork({'thumb': item["posters"]["original"],
                           'poster': item["posters"]["original"]})
        movies.append(movie)
    return local_db.merge_with_local(media_type="movie",
                                     items=movies,
                                     library_first=False)
예제 #6
0
def handle_playlists(results):
    """
    process playlist api result to ItemList
    """
    playlists = ItemList(content_type="videos")
    for item in results:
        snippet = item["snippet"]
        thumb = snippet["thumbnails"]["high"]["url"] if "thumbnails" in snippet else ""
        try:
            playlist_id = item["id"]["playlistId"]
        except Exception:
            playlist_id = snippet["resourceId"]["playlistId"]
        playlist = VideoItem(label=snippet["title"],
                             path=PLUGIN_BASE + 'youtubeplaylist&&id=%s' % playlist_id)
        playlist.set_infos({'plot': snippet["description"],
                            "mediatype": "video",
                            'premiered': snippet["publishedAt"][:10]})
        playlist.set_art("thumb", thumb)
        playlist.set_properties({'youtube_id': playlist_id,
                                 'channel_title': snippet["channelTitle"],
                                 'type': "playlist",
                                 'live': snippet["liveBroadcastContent"].replace("none", "")})
        playlists.append(playlist)
    params = {"id": ",".join([i.get_property("youtube_id") for i in playlists]),
              "part": "contentDetails"}
    ext_results = get_data(method="playlists",
                           params=params)
    for item, ext_item in itertools.product(playlists, ext_results["items"]):
        if item.get_property("youtube_id") == ext_item['id']:
            item.set_property("itemcount", ext_item['contentDetails']['itemCount'])
    return playlists
예제 #7
0
 def get_locations(self, lat, lon, radius, locationtype):
     params = {"key": GOOGLE_PLACES_KEY,
               "radius": min(30000, radius),
               "location": "%s,%s" % (lat, lon),
               "types": locationtype}
     base_url = BASE_URL + 'nearbysearch/json?'
     results = Utils.get_JSON_response(base_url + urllib.urlencode(params))
     places = ItemList()
     if "meta" in results and results['meta']['code'] == 400:
         utils.log("LIMIT EXCEEDED")
         return "", []
     if "results" not in results:
         return "", []
     for place in results['results']:
         try:
             params = {"maxwidth": 400,
                       "photoreference": place['photos'][0]['photo_reference'],
                       "key": GOOGLE_PLACES_KEY}
             photo = BASE_URL + 'photo?' + urllib.urlencode(params)
         except:
             photo = ""
         description = place['vicinity'] if "vicinity" in place else place.get('formatted_address', "")
         item = VideoItem(label=place['name'],
                          label2=" / ".join(place['types']))
         item.set_artwork({"thumb": photo,
                           "icon": place['icon']})
         item.set_info("rating", place['rating'] * 2.0 if "rating" in place else "")
         item.set_properties({'description': description,
                              "lat": place['geometry']['location']['lat'],
                              "lon": place['geometry']['location']['lng']})
         places.append(item)
     return places
예제 #8
0
def handle_movies(results):
    movies = ItemList(content_type="movies")
    path = 'extendedinfo&&id=%s' if addon.bool_setting(
        "infodialog_onclick") else "playtrailer&&id=%s"
    for i in results:
        item = i["movie"] if "movie" in i else i
        trailer = "%syoutubevideo&&id=%s" % (
            PLUGIN_BASE, utils.extract_youtube_id(item["trailer"]))
        movie = VideoItem(label=item["title"],
                          path=PLUGIN_BASE + path % item["ids"]["tmdb"])
        movie.set_infos({
            'title':
            item["title"],
            'duration':
            item["runtime"] * 60 if item["runtime"] else "",
            'tagline':
            item["tagline"],
            'mediatype':
            "movie",
            'trailer':
            trailer,
            'year':
            item["year"],
            'mpaa':
            item["certification"],
            'plot':
            item["overview"],
            'imdbnumber':
            item["ids"]["imdb"],
            'premiered':
            item["released"],
            'rating':
            round(item["rating"], 1),
            'votes':
            item["votes"],
            'genre':
            " / ".join(item["genres"])
        })
        movie.set_properties({
            'id': item["ids"]["tmdb"],
            'imdb_id': item["ids"]["imdb"],
            'trakt_id': item["ids"]["trakt"],
            'watchers': item.get("watchers"),
            'language': item.get("language"),
            'homepage': item.get("homepage")
        })
        art_info = tmdb.get_movie(item["ids"]["tmdb"], light=True)
        movie.set_artwork(
            tmdb.get_image_urls(poster=art_info.get("poster_path"),
                                fanart=art_info.get("backdrop_path")))
        movies.append(movie)
    movies = local_db.merge_with_local(media_type="movie",
                                       items=movies,
                                       library_first=False)
    movies.set_sorts(["mpaa", "duration"])
    return movies
예제 #9
0
def get_episodes(content):
    shows = ItemList(content_type="episodes")
    url = ""
    if content == "shows":
        url = 'calendars/shows/%s/14' % datetime.date.today()
    elif content == "premieres":
        url = 'calendars/shows/premieres/%s/14' % datetime.date.today()
    results = get_data(url=url,
                       params={"extended": "full,images"},
                       cache_days=0.3)
    count = 1
    if not results:
        return None
    for day in results.iteritems():
        for episode in day[1]:
            ep = episode["episode"]
            tv = episode["show"]
            title = ep["title"] if ep["title"] else ""
            label = u"{0} - {1}x{2}. {3}".format(tv["title"],
                                                 ep["season"],
                                                 ep["number"],
                                                 title)
            show = VideoItem(label=label,
                             path=PLUGIN_BASE + 'extendedtvinfo&&tvdb_id=%s' % tv["ids"]["tvdb"])
            show.set_infos({'title': title,
                            'aired': ep["first_aired"],
                            'season': ep["season"],
                            'episode': ep["number"],
                            'tvshowtitle': tv["title"],
                            'mediatype': "episode",
                            'year': tv.get("year"),
                            'duration': tv["runtime"] * 60,
                            'studio': tv["network"],
                            'plot': tv["overview"],
                            'country': tv["country"],
                            'status': tv["status"],
                            'trailer': tv["trailer"],
                            'imdbnumber': ep["ids"]["imdb"],
                            'rating': tv["rating"],
                            'genre': " / ".join(tv["genres"]),
                            'mpaa': tv["certification"]})
            show.set_properties({'tvdb_id': ep["ids"]["tvdb"],
                                 'id': ep["ids"]["tvdb"],
                                 'imdb_id': ep["ids"]["imdb"],
                                 'homepage': tv["homepage"]})
            show.set_artwork({'thumb': ep["images"]["screenshot"]["thumb"],
                              'poster': tv["images"]["poster"]["full"],
                              'banner': tv["images"]["banner"]["full"],
                              'clearart': tv["images"]["clearart"]["full"],
                              'clearlogo': tv["images"]["logo"]["full"],
                              'fanart': tv["images"]["fanart"]["full"]})
            shows.append(show)
            count += 1
            if count > 20:
                break
    return shows
예제 #10
0
def handle_videos(results, extended=False):
    """
    process vidoe api result to ItemList
    """
    videos = ItemList(content_type="videos")
    for item in results:
        snippet = item["snippet"]
        thumb = snippet["thumbnails"]["high"]["url"] if "thumbnails" in snippet else ""
        try:
            video_id = item["id"]["videoId"]
        except Exception:
            video_id = snippet["resourceId"]["videoId"]
        video = VideoItem(label=snippet["title"],
                          path=PLUGIN_BASE + 'youtubevideo&&id=%s' % video_id)
        video.set_infos({'plot': snippet["description"],
                         'mediatype': "video",
                         'premiered': snippet["publishedAt"][:10]})
        video.set_artwork({'thumb': thumb})
        video.set_playable(True)
        video.set_properties({'channel_title': snippet["channelTitle"],
                              'channel_id': snippet["channelId"],
                              'type': "video",
                              'youtube_id': video_id})
        videos.append(video)
    if not extended:
        return videos
    params = {"part": "contentDetails,statistics",
              "id": ",".join([i.get_property("youtube_id") for i in videos])}
    ext_results = get_data(method="videos",
                           params=params)
    if not ext_results:
        return videos
    for item in videos:
        for ext_item in ext_results["items"]:
            if not item.get_property("youtube_id") == ext_item['id']:
                continue
            details = ext_item['contentDetails']
            stats = ext_item['statistics']
            likes = stats.get('likeCount')
            dislikes = stats.get('dislikeCount')
            item.update_infos({"duration": get_duration_in_seconds(details['duration'])})
            props = {"duration": details['duration'][2:].lower(),
                     "formatted_duration": get_formatted_duration(details['duration']),
                     "dimension": details['dimension'],
                     "definition": details['definition'],
                     "caption": details['caption'],
                     "viewcount": utils.millify(stats['viewCount']),
                     "likes": likes,
                     "dislikes": dislikes}
            item.update_properties(props)
            if likes and dislikes:
                vote_count = int(likes) + int(dislikes)
                if vote_count > 0:
                    item.set_info("rating", round(float(likes) / vote_count * 10, 1))
            break
    return videos
예제 #11
0
def get_episodes(content):
    shows = ItemList(content_type="episodes")
    url = ""
    if content == "shows":
        url = 'calendars/shows/%s/14' % datetime.date.today()
    elif content == "premieres":
        url = 'calendars/shows/premieres/%s/14' % datetime.date.today()
    results = get_data(url=url,
                       params={"extended": "full"},
                       cache_days=0.3)
    count = 1
    if not results:
        return None
    for day in results.iteritems():
        for episode in day[1]:
            ep = episode["episode"]
            tv = episode["show"]
            title = ep["title"] if ep["title"] else ""
            label = u"{0} - {1}x{2}. {3}".format(tv["title"],
                                                 ep["season"],
                                                 ep["number"],
                                                 title)
            show = VideoItem(label=label,
                             path=PLUGIN_BASE + 'extendedtvinfo&&tvdb_id=%s' % tv["ids"]["tvdb"])
            show.set_infos({'title': title,
                            'aired': ep["first_aired"],
                            'season': ep["season"],
                            'episode': ep["number"],
                            'tvshowtitle': tv["title"],
                            'mediatype': "episode",
                            'year': tv.get("year"),
                            'duration': tv["runtime"] * 60 if tv["runtime"] else "",
                            'studio': tv["network"],
                            'plot': tv["overview"],
                            'country': tv["country"],
                            'status': tv["status"],
                            'trailer': tv["trailer"],
                            'imdbnumber': ep["ids"]["imdb"],
                            'rating': tv["rating"],
                            'genre': " / ".join(tv["genres"]),
                            'mpaa': tv["certification"]})
            show.set_properties({'tvdb_id': ep["ids"]["tvdb"],
                                 'id': ep["ids"]["tvdb"],
                                 'imdb_id': ep["ids"]["imdb"],
                                 'homepage': tv["homepage"]})
            if tv["ids"].get("tmdb"):
                art_info = tmdb.get_tvshow(tv["ids"]["tmdb"], light=True)
                show.set_artwork(tmdb.get_image_urls(poster=art_info.get("poster_path"),
                                                     fanart=art_info.get("backdrop_path")))
            shows.append(show)
            count += 1
            if count > 20:
                break
    return shows
예제 #12
0
def handle_albums(results):
    albums = ItemList(content_type="albums")
    if results and 'topalbums' in results and "album" in results['topalbums']:
        for album in results['topalbums']['album']:
            albums.append({'artist': album['artist']['name'],
                           'mbid': album.get('mbid', ""),
                           'mediatype': "album",
                           'thumb': album['image'][-1]['#text'],
                           'label': "%s - %s" % (album['artist']['name'], album['name']),
                           'title': album['name']})
            albums.append(album)
    return albums
예제 #13
0
 def get_similar_movies(self, dbid):
     """
     get list of movies from db which are similar to movie with *dbid
     based on metadata-centric ranking
     """
     movie = kodijson.get_json(method="VideoLibrary.GetMovieDetails",
                               params={"properties": ["genre", "director", "country", "year", "mpaa"], "movieid": dbid})
     if "moviedetails" not in movie['result']:
         return []
     comp_movie = movie['result']['moviedetails']
     genres = comp_movie['genre']
     data = kodijson.get_json(method="VideoLibrary.GetMovies",
                              params={"properties": ["genre", "director", "mpaa", "country", "year"], "sort": {"method": "random"}})
     if "movies" not in data['result']:
         return []
     quotalist = []
     for item in data['result']['movies']:
         item["mediatype"] = "movie"
         diff = abs(int(item['year']) - int(comp_movie['year']))
         hit = 0.0
         miss = 0.00001
         quota = 0.0
         for genre in genres:
             if genre in item['genre']:
                 hit += 1.0
             else:
                 miss += 1.0
         if hit > 0.0:
             quota = float(hit) / float(hit + miss)
         if genres and item['genre'] and genres[0] == item['genre'][0]:
             quota += 0.3
         if diff < 3:
             quota += 0.3
         elif diff < 6:
             quota += 0.15
         if comp_movie['country'] and item['country'] and comp_movie['country'][0] == item['country'][0]:
             quota += 0.4
         if comp_movie['mpaa'] and item['mpaa'] and comp_movie['mpaa'] == item['mpaa']:
             quota += 0.4
         if comp_movie['director'] and item['director'] and comp_movie['director'][0] == item['director'][0]:
             quota += 0.6
         quotalist.append((quota, item["movieid"]))
     quotalist = sorted(quotalist,
                        key=lambda quota: quota[0],
                        reverse=True)
     movies = ItemList(content_type="movies")
     for i, list_movie in enumerate(quotalist):
         if comp_movie['movieid'] is not list_movie[1]:
             newmovie = self.get_movie(list_movie[1])
             movies.append(newmovie)
             if i == 20:
                 break
     return movies
예제 #14
0
def handle_tvshows(results):
    shows = ItemList(content_type="tvshows")
    for i in results:
        item = i["show"] if "show" in i else i
        airs = item.get("airs", {})
        show = VideoItem(label=item["title"],
                         path='%sextendedtvinfo&&tvdb_id=%s' %
                         (PLUGIN_BASE, item['ids']["tvdb"]))
        show.set_infos({
            'mediatype': "tvshow",
            'title': item["title"],
            'duration': item["runtime"] * 60,
            'year': item["year"],
            'premiered': item["first_aired"][:10],
            'country': item["country"],
            'rating': round(item["rating"], 1),
            'votes': item["votes"],
            'imdbnumber': item['ids']["imdb"],
            'mpaa': item["certification"],
            'trailer': item["trailer"],
            'status': item.get("status"),
            'studio': item["network"],
            'genre': " / ".join(item["genres"]),
            'plot': item["overview"]
        })
        show.set_properties({
            'id': item['ids']["tmdb"],
            'tvdb_id': item['ids']["tvdb"],
            'imdb_id': item['ids']["imdb"],
            'trakt_id': item['ids']["trakt"],
            'language': item["language"],
            'aired_episodes': item["aired_episodes"],
            'homepage': item["homepage"],
            'airday': airs.get("day"),
            'airshorttime': airs.get("time"),
            'watchers': item.get("watchers")
        })
        show.set_artwork({
            'poster': item["images"]["poster"]["full"],
            'banner': item["images"]["banner"]["full"],
            'clearart': item["images"]["clearart"]["full"],
            'clearlogo': item["images"]["logo"]["full"],
            'fanart': item["images"]["fanart"]["full"],
            'thumb': item["images"]["poster"]["thumb"]
        })
        shows.append(show)
    shows = local_db.merge_with_local(media_type="tvshow",
                                      items=shows,
                                      library_first=False)
    shows.set_sorts(["mpaa", "duration"])
    return shows
예제 #15
0
def handle_albums(results):
    albums = ItemList(content_type="albums")
    if not results:
        return []
    if 'topalbums' in results and "album" in results['topalbums']:
        for album in results['topalbums']['album']:
            albums.append({'artist': album['artist']['name'],
                           'mbid': album.get('mbid', ""),
                           'mediatype': "album",
                           'thumb': album['image'][-1]['#text'],
                           'label': "%s - %s" % (album['artist']['name'], album['name']),
                           'title': album['name']})
            albums.append(album)
    return albums
예제 #16
0
def handle_musicvideos(results):
    mvids = ItemList(content_type="musicvideos")
    if not results.get('mvids'):
        return mvids
    for item in results['mvids']:
        youtube_id = utils.extract_youtube_id(item.get('strMusicVid', ''))
        mvid = VideoItem(label=item['strTrack'],
                         path="%syoutubevideo&&id=%s" % (PLUGIN_BASE, youtube_id))
        mvid.set_infos({'title': item['strTrack'],
                        'plot': item['strDescriptionEN'],
                        'mediatype': "musicvideo"})
        mvid.set_properties({'id': item['idTrack']})
        mvid.set_artwork({'thumb': "http://i.ytimg.com/vi/%s/0.jpg" % youtube_id})
        mvids.append(mvid)
    return mvids
예제 #17
0
def get_icon_panel(number):
    """
    get icon panel with index *number, returns dict list based on skin strings
    """
    items = ItemList()
    offset = number * 5 - 5
    for i in range(1, 6):
        infopanel_path = utils.get_skin_string("IconPanelItem%i.Path" % (i + offset))
        item = ListItem(label=utils.get_skin_string("IconPanelItem%i.Label" % (i + offset)),
                        path="plugin://script.extendedinfo/?info=action&&id=" + infopanel_path)
        item.set_artwork({'thumb': utils.get_skin_string("IconPanelItem%i.Icon" % (i + offset))})
        item.set_properties({'type': utils.get_skin_string("IconPanelItem%i.Type" % (i + offset)),
                             'id': "IconPanelitem%i" % (i + offset)})
        items.append(item)
    return items
def handle_videos(results):
    listitems = ItemList(content_type="videos")
    for item in results:
        listitem = VideoItem(label=item.get('title'),
                             artwork={'thumb': item.get("thumbnail_720_url")})
        date = datetime.datetime.fromtimestamp(int(item.get('created_time'))).strftime('%Y-%m-%d')
        listitem.set_infos({'mediatype': "video",
                            "duration": item.get("duration"),
                            "premiered": date})
        listitem.set_properties({'genre': item.get('genre'),
                                 'youtube_id': item.get('key'),
                                 'duration': utils.format_seconds(item.get("duration")),
                                 'id': item.get('embed_url')})
        listitems.append(listitem)
    return listitems
예제 #19
0
def handle_artists(results):
    artists = ItemList(content_type="artists")
    if not results:
        return []
    for artist in results['artist']:
        if 'name' not in artist:
            continue
        artist = {'title': artist['name'],
                  'label': artist['name'],
                  'mediatype': "artist",
                  'mbid': artist.get('mbid'),
                  'thumb': artist['image'][-1]['#text'],
                  'Listeners': format(int(artist.get('listeners', 0)), ",d")}
        artists.append(artist)
    return artists
예제 #20
0
def handle_albums(results):
    albums = ItemList(content_type="albums")
    if not results.get('album'):
        return albums
    local_desc = 'strDescription' + xbmc.getLanguage(xbmc.ISO_639_1).upper()
    for item in results['album']:
        desc = ""
        if local_desc in item and item[local_desc]:
            desc = item.get(local_desc, "")
        elif item.get('strDescriptionEN'):
            desc = item['strDescriptionEN']
        elif item.get('strDescription'):
            desc = item['strDescription']
        if item.get('strReview'):
            desc += "[CR][CR][B]%s:[/B][CR][CR]%s" % (addon.LANG(185),
                                                      item['strReview'])
        album = AudioItem(label=item['strAlbum'], path="")
        album.set_infos({
            'artist': item['strArtist'],
            'album': item['strAlbum'],
            'mediatype': "album",
            'genre': item['strGenre'],
            'year': item['intYearReleased']
        })
        album.set_properties({
            'mbid': item['strMusicBrainzID'],
            'id': item['idAlbum'],
            'audiodb_id': item['idAlbum'],
            'album_description': desc,
            'album_mood': item['strMood'],
            'album_style': item['strStyle'],
            'speed': item['strSpeed'],
            'album_Theme': item['strTheme'],
            'type': item['strReleaseFormat'],
            'loved': item['intLoved'],
            'location': item['strLocation'],
            'itunes_id': item['strItunesID'],
            'amazon_id': item['strAmazonID'],
            'sales': item['intSales']
        })
        album.set_artwork({
            'thumb': item['strAlbumThumb'],
            'spine': item['strAlbumSpine'],
            'cdart': item['strAlbumCDart'],
            'thumbback': item['strAlbumThumbBack']
        })
        albums.append(album)
    return local_db.compare_album_with_library(albums)
예제 #21
0
def handle_tracks(results):
    tracks = ItemList(content_type="songs")
    if not results.get('track'):
        return tracks
    for item in results['track']:
        youtube_id = utils.extract_youtube_id(item.get('strMusicVid', ''))
        track = AudioItem(label=item['strTrack'],
                          path="%syoutubevideo&&id=%s" % (PLUGIN_BASE, youtube_id))
        track.set_infos({'title': item['strTrack'],
                         'album': item['strAlbum'],
                         'artist': item['strArtist'],
                         'mediatype': "song"})
        track.set_properties({'mbid': item['strMusicBrainzID']})
        track.set_artwork({'thumb': "http://i.ytimg.com/vi/%s/0.jpg" % youtube_id})
        tracks.append(track)
    return tracks
예제 #22
0
def get_favs():
    """
    returns dict list containing favourites
    """
    items = ItemList()
    data = kodijson.get_favourites()
    if "result" not in data or data["result"]["limits"]["total"] == 0:
        return []
    for fav in data["result"]["favourites"]:
        path = get_fav_path(fav)
        item = ListItem(label=fav["title"],
                        path="plugin://script.extendedinfo/?info=action&&id=" + path)
        item.set_artwork({'thumb': fav["thumbnail"]})
        item.set_properties({'type': fav["type"],
                             'builtin': path})
        items.append(item)
    return items
예제 #23
0
def get_addons_by_author(author_name, installed="all"):
    """
    get a list of addons from *author_name
    *installed: "all", True, False
    """
    repo_addons = kodijson.get_addons(installed=installed,
                                      properties=["installed", "author", "name", "thumbnail", "fanart"])
    addons = [item for item in repo_addons if item["author"] == author_name]
    items = ItemList()
    for item in addons:
        path = 'InstallAddon(%s)' % item["id"]
        item = ListItem(label=item["name"],
                        path="plugin://script.extendedinfo/?info=action&&id=" + path)
        item.set_artwork({'thumb': item["thumbnail"],
                          "fanart": item["fanart"]})
        item.set_properties({'installed': item["installed"]})
        items.append(item)
예제 #24
0
def handle_tvshows(results):
    shows = ItemList(content_type="tvshows")
    for i in results:
        item = i["show"] if "show" in i else i
        airs = item.get("airs", {})
        show = VideoItem(label=item["title"],
                         path='%sextendedtvinfo&&tvdb_id=%s' % (PLUGIN_BASE, item['ids']["tvdb"]))
        show.set_infos({'mediatype': "tvshow",
                        'title': item["title"],
                        'duration': item["runtime"] * 60,
                        'year': item["year"],
                        'premiered': item["first_aired"][:10],
                        'country': item["country"],
                        'rating': round(item["rating"], 1),
                        'votes': item["votes"],
                        'imdbnumber': item['ids']["imdb"],
                        'mpaa': item["certification"],
                        'trailer': item["trailer"],
                        'status': item.get("status"),
                        'studio': item["network"],
                        'genre': " / ".join(item["genres"]),
                        'plot': item["overview"]})
        show.set_properties({'id': item['ids']["tmdb"],
                             'tvdb_id': item['ids']["tvdb"],
                             'imdb_id': item['ids']["imdb"],
                             'trakt_id': item['ids']["trakt"],
                             'language': item["language"],
                             'aired_episodes': item["aired_episodes"],
                             'homepage': item["homepage"],
                             'airday': airs.get("day"),
                             'airshorttime': airs.get("time"),
                             'watchers': item.get("watchers")})
        show.set_artwork({'poster': item["images"]["poster"]["full"],
                          'banner': item["images"]["banner"]["full"],
                          'clearart': item["images"]["clearart"]["full"],
                          'clearlogo': item["images"]["logo"]["full"],
                          'fanart': item["images"]["fanart"]["full"],
                          'thumb': item["images"]["poster"]["thumb"]})
        shows.append(show)
    shows = local_db.merge_with_local(media_type="tvshow",
                                      items=shows,
                                      library_first=False)
    shows.set_sorts(["mpaa", "duration"])
    return shows
예제 #25
0
def handle_playlists(results):
    """
    process playlist api result to ItemList
    """
    playlists = ItemList(content_type="videos")
    for item in results:
        snippet = item["snippet"]
        thumb = snippet["thumbnails"]["high"][
            "url"] if "thumbnails" in snippet else ""
        try:
            playlist_id = item["id"]["playlistId"]
        except Exception:
            playlist_id = snippet["resourceId"]["playlistId"]
        playlist = VideoItem(label=snippet["title"],
                             path=PLUGIN_BASE +
                             'youtubeplaylist&&id=%s' % playlist_id)
        playlist.set_infos({
            'plot': snippet["description"],
            "mediatype": "video",
            'premiered': snippet["publishedAt"][:10]
        })
        playlist.set_art("thumb", thumb)
        playlist.set_properties({
            'youtube_id':
            playlist_id,
            'channel_title':
            snippet["channelTitle"],
            'type':
            "playlist",
            'live':
            snippet["liveBroadcastContent"].replace("none", "")
        })
        playlists.append(playlist)
    params = {
        "id": ",".join([i.get_property("youtube_id") for i in playlists]),
        "part": "contentDetails"
    }
    ext_results = get_data(method="playlists", params=params)
    for item, ext_item in itertools.product(playlists, ext_results["items"]):
        if item.get_property("youtube_id") == ext_item['id']:
            item.set_property("itemcount",
                              ext_item['contentDetails']['itemCount'])
    return playlists
예제 #26
0
def handle_albums(results):
    albums = ItemList(content_type="albums")
    if not results.get('album'):
        return albums
    local_desc = 'strDescription' + xbmc.getLanguage(xbmc.ISO_639_1).upper()
    for item in results['album']:
        desc = ""
        if local_desc in item and item[local_desc]:
            desc = item.get(local_desc, "")
        elif item.get('strDescriptionEN'):
            desc = item['strDescriptionEN']
        elif item.get('strDescription'):
            desc = item['strDescription']
        if item.get('strReview'):
            desc += "[CR][CR][B]%s:[/B][CR][CR]%s" % (addon.LANG(185), item['strReview'])
        album = AudioItem(label=item['strAlbum'],
                          path="")
        album.set_infos({'artist': item['strArtist'],
                         'album': item['strAlbum'],
                         'mediatype': "album",
                         'genre': item['strGenre'],
                         'year': item['intYearReleased']})
        album.set_properties({'mbid': item['strMusicBrainzID'],
                              'id': item['idAlbum'],
                              'audiodb_id': item['idAlbum'],
                              'album_description': desc,
                              'album_mood': item['strMood'],
                              'album_style': item['strStyle'],
                              'speed': item['strSpeed'],
                              'album_Theme': item['strTheme'],
                              'type': item['strReleaseFormat'],
                              'loved': item['intLoved'],
                              'location': item['strLocation'],
                              'itunes_id': item['strItunesID'],
                              'amazon_id': item['strAmazonID'],
                              'sales': item['intSales']})
        album.set_artwork({'thumb': item['strAlbumThumb'],
                           'spine': item['strAlbumSpine'],
                           'cdart': item['strAlbumCDart'],
                           'thumbback': item['strAlbumThumbBack']})
        albums.append(album)
    return local_db.compare_album_with_library(albums)
예제 #27
0
def get_incidents(lat, lon, zoom):
    lat_high, lon_high, lat_low, lon_low = Utils.get_bounding_box(lat, lon, zoom)
    params = {"key": MAPQUEST_KEY,
              "inFormat": "kvp",
              "boundingBox": "%s,%s,%s,%s" % (lat_high, lon_high, lat_low, lon_low)}
    url = BASE_URL + 'incidents?' + urllib.urlencode(params)
    results = Utils.get_JSON_response(url)
    places = ItemList()
    if results['info']['statuscode'] == 400:
        utils.notify("Error", " - ".join(results['info']['messages']), time=10000)
        return []
    elif "incidents" not in results:
        utils.notify("Error", "Could not fetch results")
        return []
    for place in results['incidents'][:MAX_LIMIT]:
        lat = str(place['lat'])
        lon = str(place['lng'])
        params = {"key": MAPQUEST_KEY,
                  "mapLat": place['lat'],
                  "mapLng": place['lng'],
                  "mapHeight": 400,
                  "mapWidth": 400,
                  "mapScale": 433342}
        url = BASE_URL + "flow?" + urllib.urlencode(params)
        item = VideoItem(label=place['shortDesc'],
                         label2=place['startTime'])
        item.set_properties({'name': place['shortDesc'],
                             'description': place['fullDesc'],
                             'distance': str(place['distance']),
                             'delaytypical': str(place['delayFromTypical']),
                             'delayfreeflow': str(place['delayFromFreeFlow']),
                             'date': place['startTime'],
                             'severity': str(place['severity']),
                             'type': incident_types.get(place['type'], ""),
                             "lat": lat,
                             "lon": lon})
        item.set_artwork({"thumb": url,
                          "icon": place['iconURL'],
                          "googlemap": googlemaps.get_static_map(lat=lat, lon=lon)})
        places.append(item)
    return places
예제 #28
0
def handle_movies(results):
    movies = ItemList(content_type="movies")
    path = 'extendedinfo&&id=%s' if addon.bool_setting("infodialog_onclick") else "playtrailer&&id=%s"
    for i in results:
        item = i["movie"] if "movie" in i else i
        trailer = "%syoutubevideo&&id=%s" % (PLUGIN_BASE, utils.extract_youtube_id(item["trailer"]))
        movie = VideoItem(label=item["title"],
                          path=PLUGIN_BASE + path % item["ids"]["tmdb"])
        movie.set_infos({'title': item["title"],
                         'duration': item["runtime"] * 60,
                         'tagline': item["tagline"],
                         'mediatype': "movie",
                         'trailer': trailer,
                         'year': item["year"],
                         'mpaa': item["certification"],
                         'plot': item["overview"],
                         'imdbnumber': item["ids"]["imdb"],
                         'premiered': item["released"],
                         'rating': round(item["rating"], 1),
                         'votes': item["votes"],
                         'genre': " / ".join(item["genres"])})
        movie.set_properties({'id': item["ids"]["tmdb"],
                              'imdb_id': item["ids"]["imdb"],
                              'trakt_id': item["ids"]["trakt"],
                              'watchers': item.get("watchers"),
                              'language': item.get("language"),
                              'homepage': item.get("homepage")})
        movie.set_artwork({'poster': item["images"]["poster"]["full"],
                           'fanart': item["images"]["fanart"]["full"],
                           'clearlogo': item["images"]["logo"]["full"],
                           'clearart': item["images"]["clearart"]["full"],
                           'banner': item["images"]["banner"]["full"],
                           'thumb': item["images"]["poster"]["thumb"]})
        movies.append(movie)
    movies = local_db.merge_with_local(media_type="movie",
                                       items=movies,
                                       library_first=False)
    movies.set_sorts(["mpaa", "duration"])
    return movies
예제 #29
0
 def get_similar_artists(self, artist_id):
     """
     get list of artists from db which are similar to artist with *artist_id
     based on LastFM online data
     """
     import LastFM
     simi_artists = LastFM.get_similar_artists(artist_id)
     if simi_artists is None:
         utils.log('Last.fm didn\'t return proper response')
         return None
     if not self.artists:
         self.artists = self.get_artists()
     artists = ItemList(content_type="artists")
     for simi_artist, kodi_artist in itertools.product(simi_artists, self.artists):
         if kodi_artist['musicbrainzartistid'] and kodi_artist['musicbrainzartistid'] == simi_artist['mbid']:
             artists.append(kodi_artist)
         elif kodi_artist['artist'] == simi_artist['name']:
             data = kodijson.get_json(method="AudioLibrary.GetArtistDetails",
                                      params={"properties": ["genre", "description", "mood", "style", "born", "died", "formed", "disbanded", "yearsactive", "instrument", "fanart", "thumbnail"], "artistid": kodi_artist['artistid']})
             item = data["result"]["artistdetails"]
             artwork = {"thumb": item['thumbnail'],
                        "fanart": item['fanart']}
             artists.append({"label": item['label'],
                             "artwork": artwork,
                             "title": item['label'],
                             "genre": " / ".join(item['genre']),
                             "artist_description": item['description'],
                             "userrating": item['userrating'],
                             "born": item['born'],
                             "died": item['died'],
                             "formed": item['formed'],
                             "disbanded": item['disbanded'],
                             "yearsactive": " / ".join(item['yearsactive']),
                             "style": " / ".join(item['style']),
                             "mood": " / ".join(item['mood']),
                             "instrument": " / ".join(item['instrument']),
                             "librarypath": 'musicdb://artists/%s/' % item['artistid']})
     utils.log('%i of %i artists found in last.FM are in Kodi database' % (len(artists), len(simi_artists)))
     return artists
예제 #30
0
def handle_channels(results):
    """
    process channel api result to ItemList
    """
    channels = ItemList(content_type="videos")
    for item in results:
        snippet = item["snippet"]
        thumb = snippet["thumbnails"]["high"][
            "url"] if "thumbnails" in snippet else ""
        try:
            channel_id = item["id"]["channelId"]
        except Exception:
            channel_id = snippet["resourceId"]["channelId"]
        channel = VideoItem(label=snippet["title"],
                            path=PLUGIN_BASE +
                            'youtubechannel&&id=%s' % channel_id)
        channel.set_infos({
            'plot': snippet["description"],
            'mediatype': "video",
            'premiered': snippet["publishedAt"][:10]
        })
        channel.set_art("thumb", thumb)
        channel.set_properties({"youtube_id": channel_id, "type": "channel"})
        channels.append(channel)
    channel_ids = [item.get_property("youtube_id") for item in channels]
    params = {
        "id": ",".join(channel_ids),
        "part": "contentDetails,statistics,brandingSettings"
    }
    ext_results = get_data(method="channels", params=params)
    for item, ext_item in itertools.product(channels, ext_results["items"]):
        if item.get_property("youtube_id") == ext_item['id']:
            item.set_property("itemcount",
                              ext_item['statistics']['videoCount'])
            item.set_art(
                "fanart", ext_item["brandingSettings"]["image"].get(
                    "bannerTvMediumImageUrl"))
    return channels
예제 #31
0
 def handle_places(self, results):
     places = ItemList()
     for venue in results:
         try:
             photo = venue['venue']['photos']['groups'][0]['items'][0]
             photo = "%s%s%s" % (photo['prefix'], photo['height'], photo['suffix'])
         except:
             photo = ""
         if "name" not in venue:
             venue = venue["venue"]
         if venue['categories']:
             icon = venue['categories'][0]['icon']
             icon = "%s88%s" % (icon['prefix'], icon['suffix'])
         else:
             icon = ""
         if 'formattedAddress' in venue['location']:
             formattedAddress = "[CR]".join(filter(None, venue['location']['formattedAddress']))
         lat = venue['location']['lat']
         lon = venue['location']['lng']
         item = VideoItem(label=venue['name'],
                          label2=venue['name'])
         item.set_properties({"id": venue['id'],
                              "foursquare_id": venue['id'],
                              "distance": venue['location']['distance'],
                              "visited": venue['stats']['usersCount'],
                              "twitter": venue['contact'].get('twitter', ""),
                              "eventname": venue['location']['address'],
                              "description": formattedAddress,
                              "name": venue['name'],
                              "lat": lat,
                              "lon": lon,
                              "phone": venue['contact'].get('phone', ""),
                              "comments": venue['stats']['tipCount']})
         item.set_artwork({"thumb": photo,
                           "icon": icon,
                           "googlemap": googlemaps.get_static_map(lat=lat, lon=lon)})
         places.append(item)
     return places
예제 #32
0
파일: localdb.py 프로젝트: camster1/RTOTV
 def get_similar_movies(self, dbid):
     """
     get list of movies from db which are similar to movie with *dbid
     based on metadata-centric ranking
     """
     movie = kodijson.get_json(
         method="VideoLibrary.GetMovieDetails",
         params={
             "properties": ["genre", "director", "country", "year", "mpaa"],
             "movieid": dbid
         })
     if "moviedetails" not in movie['result']:
         return []
     comp_movie = movie['result']['moviedetails']
     genres = comp_movie['genre']
     data = kodijson.get_json(
         method="VideoLibrary.GetMovies",
         params={
             "properties": ["genre", "director", "mpaa", "country", "year"],
             "sort": {
                 "method": "random"
             }
         })
     if "movies" not in data['result']:
         return []
     quotalist = []
     for item in data['result']['movies']:
         item["mediatype"] = "movie"
         diff = abs(int(item['year']) - int(comp_movie['year']))
         hit = 0.0
         miss = 0.00001
         quota = 0.0
         for genre in genres:
             if genre in item['genre']:
                 hit += 1.0
             else:
                 miss += 1.0
         if hit > 0.0:
             quota = float(hit) / float(hit + miss)
         if genres and item['genre'] and genres[0] == item['genre'][0]:
             quota += 0.3
         if diff < 3:
             quota += 0.3
         elif diff < 6:
             quota += 0.15
         if comp_movie['country'] and item['country'] and comp_movie[
                 'country'][0] == item['country'][0]:
             quota += 0.4
         if comp_movie['mpaa'] and item['mpaa'] and comp_movie[
                 'mpaa'] == item['mpaa']:
             quota += 0.4
         if comp_movie['director'] and item['director'] and comp_movie[
                 'director'][0] == item['director'][0]:
             quota += 0.6
         quotalist.append((quota, item["movieid"]))
     quotalist = sorted(quotalist, key=lambda quota: quota[0], reverse=True)
     movies = ItemList(content_type="movies")
     for i, list_movie in enumerate(quotalist):
         if comp_movie['movieid'] is not list_movie[1]:
             newmovie = self.get_movie(list_movie[1])
             movies.append(newmovie)
             if i == 20:
                 break
     return movies
예제 #33
0
파일: localdb.py 프로젝트: camster1/RTOTV
 def get_similar_artists(self, artist_id):
     """
     get list of artists from db which are similar to artist with *artist_id
     based on LastFM online data
     """
     import LastFM
     simi_artists = LastFM.get_similar_artists(artist_id)
     if simi_artists is None:
         utils.log('Last.fm didn\'t return proper response')
         return None
     if not self.artists:
         self.artists = self.get_artists()
     artists = ItemList(content_type="artists")
     for simi_artist, kodi_artist in itertools.product(
             simi_artists, self.artists):
         if kodi_artist['musicbrainzartistid'] and kodi_artist[
                 'musicbrainzartistid'] == simi_artist['mbid']:
             artists.append(kodi_artist)
         elif kodi_artist['artist'] == simi_artist['name']:
             data = kodijson.get_json(
                 method="AudioLibrary.GetArtistDetails",
                 params={
                     "properties": [
                         "genre", "description", "mood", "style", "born",
                         "died", "formed", "disbanded", "yearsactive",
                         "instrument", "fanart", "thumbnail"
                     ],
                     "artistid":
                     kodi_artist['artistid']
                 })
             item = data["result"]["artistdetails"]
             artwork = {
                 "thumb": item['thumbnail'],
                 "fanart": item['fanart']
             }
             artists.append({
                 "label":
                 item['label'],
                 "artwork":
                 artwork,
                 "title":
                 item['label'],
                 "genre":
                 " / ".join(item['genre']),
                 "artist_description":
                 item['description'],
                 "userrating":
                 item['userrating'],
                 "born":
                 item['born'],
                 "died":
                 item['died'],
                 "formed":
                 item['formed'],
                 "disbanded":
                 item['disbanded'],
                 "yearsactive":
                 " / ".join(item['yearsactive']),
                 "style":
                 " / ".join(item['style']),
                 "mood":
                 " / ".join(item['mood']),
                 "instrument":
                 " / ".join(item['instrument']),
                 "librarypath":
                 'musicdb://artists/%s/' % item['artistid']
             })
     utils.log('%i of %i artists found in last.FM are in Kodi database' %
               (len(artists), len(simi_artists)))
     return artists
예제 #34
0
def handle_videos(results, extended=False):
    """
    process vidoe api result to ItemList
    """
    videos = ItemList(content_type="videos")
    for item in results:
        snippet = item["snippet"]
        thumb = snippet["thumbnails"]["high"][
            "url"] if "thumbnails" in snippet else ""
        try:
            video_id = item["id"]["videoId"]
        except Exception:
            video_id = snippet["resourceId"]["videoId"]
        video = VideoItem(label=snippet["title"],
                          path=PLUGIN_BASE + 'youtubevideo&&id=%s' % video_id)
        video.set_infos({
            'plot': snippet["description"],
            'mediatype': "video",
            'premiered': snippet["publishedAt"][:10]
        })
        video.set_artwork({'thumb': thumb})
        video.set_playable(True)
        video.set_properties({
            'channel_title': snippet["channelTitle"],
            'channel_id': snippet["channelId"],
            'type': "video",
            'youtube_id': video_id
        })
        videos.append(video)
    if not extended:
        return videos
    params = {
        "part": "contentDetails,statistics",
        "id": ",".join([i.get_property("youtube_id") for i in videos])
    }
    ext_results = get_data(method="videos", params=params)
    if not ext_results:
        return videos
    for item in videos:
        for ext_item in ext_results["items"]:
            if not item.get_property("youtube_id") == ext_item['id']:
                continue
            details = ext_item['contentDetails']
            stats = ext_item.get('statistics')
            likes = stats.get('likeCount') if stats else None
            dislikes = stats.get('dislikeCount') if stats else None
            item.update_infos(
                {"duration": get_duration_in_seconds(details['duration'])})
            props = {
                "duration": details['duration'][2:].lower(),
                "formatted_duration":
                get_formatted_duration(details['duration']),
                "dimension": details['dimension'],
                "definition": details['definition'],
                "caption": details['caption'],
                "viewcount": utils.millify(stats['viewCount']),
                "likes": likes,
                "dislikes": dislikes
            }
            item.update_properties(props)
            if likes and dislikes:
                vote_count = int(likes) + int(dislikes)
                if vote_count > 0:
                    item.set_info("rating",
                                  round(float(likes) / vote_count * 10, 1))
            break
    return videos