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
Esempio n. 2
0
def get_images(path=""):
    images = []
    for filename in xbmcvfs.listdir(path)[-1]:
        try:
            img = Image.open(path + filename)
            exif_data = ImageTags.get_exif_data(img)
            lat, lon = ImageTags.get_lat_lon(exif_data)
            if not lat or not lon:
                continue
            if "DateTimeOriginal" in exif_data:
                date = exif_data["DateTimeOriginal"]
            elif "DateTime" in exif_data:
                date = exif_data["DateTime"]
            else:
                date = ""
            image = VideoItem(label=filename)
            image.set_properties({"lat": str(lat),
                                  "lon": str(lon),
                                  "date": date,
                                  "description": date})
            image.set_art("thumb", path + filename)
            images.append(image)
        except Exception:
            pass
    return images
Esempio n. 3
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
Esempio n. 4
0
 def handle_tvshow(self, tvshow):
     """
     convert tvshow data to listitems
     """
     if addon.setting("infodialog_onclick") != "false":
         path = PLUGIN_BASE + 'extendedtvinfo&&dbid=%s' % tvshow['tvshowid']
     else:
         path = PLUGIN_BASE + 'action&&id=ActivateWindow(videos,videodb://tvshows/titles/%s/,return)' % tvshow['tvshowid']
     db_tvshow = VideoItem(label=tvshow.get("label"),
                           path=path)
     db_tvshow.set_infos({'title': tvshow.get('label'),
                          'dbid': tvshow['tvshowid'],
                          'genre': " / ".join(tvshow.get('genre')),
                          'rating': round(float(tvshow['rating']), 1),
                          'mediatype': "tvshow",
                          'mpaa': tvshow.get("mpaa"),
                          'plot': tvshow.get("plot"),
                          'votes': tvshow.get("votes"),
                          'studio': " / ".join(tvshow.get('studio')),
                          'premiered': tvshow.get("premiered"),
                          'playcount': tvshow.get("playcount"),
                          'imdbnumber': tvshow.get("imdbnumber"),
                          'userrating': tvshow.get("userrating"),
                          'duration': tvshow.get("duration"),
                          # "tag": " / ".join(movie['tag']),
                          'year': tvshow.get('year'),
                          'originaltitle': tvshow.get('originaltitle')})
     db_tvshow.set_properties({'imdb_id': tvshow.get('imdbnumber'),
                               'file': tvshow.get('file'),
                               'watchedepisodes': tvshow.get('watchedepisodes'),
                               'totalepisodes': tvshow.get('episode')})
     db_tvshow.set_artwork(tvshow['art'])
     db_tvshow.set_cast(tvshow.get("cast"))
     return db_tvshow
Esempio n. 5
0
 def __init__(self, *args, **kwargs):
     super(DialogBaseInfo, self).__init__(*args, **kwargs)
     self.logged_in = tmdb.Login.check_login()
     self.bouncing = False
     self.last_focus = None
     self.lists = None
     self.states = False
     self.yt_listitems = []
     self.info = VideoItem()
     self.last_control = None
     self.last_position = None
Esempio n. 6
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
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
Esempio n. 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
 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
Esempio n. 10
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
Esempio n. 11
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
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)
Esempio n. 13
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
Esempio n. 14
0
 def handle_tvshow(self, tvshow):
     """
     convert tvshow data to listitems
     """
     if addon.setting("infodialog_onclick") != "false":
         path = PLUGIN_BASE + 'extendedtvinfo&&dbid=%s' % tvshow['tvshowid']
     else:
         path = PLUGIN_BASE + 'action&&id=ActivateWindow(videos,videodb://tvshows/titles/%s/,return)' % tvshow[
             'tvshowid']
     db_tvshow = VideoItem(label=tvshow.get("label"), path=path)
     db_tvshow.set_infos({
         'title': tvshow.get('label'),
         'dbid': tvshow['tvshowid'],
         'genre': " / ".join(tvshow.get('genre')),
         'rating': round(float(tvshow['rating']), 1),
         'mediatype': "tvshow",
         'mpaa': tvshow.get("mpaa"),
         'plot': tvshow.get("plot"),
         'votes': tvshow.get("votes"),
         'studio': " / ".join(tvshow.get('studio')),
         'premiered': tvshow.get("premiered"),
         'playcount': tvshow.get("playcount"),
         'imdbnumber': tvshow.get("imdbnumber"),
         'userrating': tvshow.get("userrating"),
         'duration': tvshow.get("duration"),
         # "tag": " / ".join(movie['tag']),
         'year': tvshow.get('year'),
         'originaltitle': tvshow.get('originaltitle')
     })
     db_tvshow.set_properties({
         'imdb_id':
         tvshow.get('imdbnumber'),
         'file':
         tvshow.get('file'),
         'watchedepisodes':
         tvshow.get('watchedepisodes'),
         'totalepisodes':
         tvshow.get('episode')
     })
     db_tvshow.set_artwork(tvshow['art'])
     db_tvshow.set_cast(tvshow.get("cast"))
     return db_tvshow
 def __init__(self, *args, **kwargs):
     super(DialogBaseInfo, self).__init__(*args, **kwargs)
     self.logged_in = tmdb.Login.check_login()
     self.bouncing = False
     self.last_focus = None
     self.lists = None
     self.states = False
     self.yt_listitems = []
     self.info = VideoItem()
     self.last_control = None
     self.last_position = None
Esempio n. 16
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
Esempio n. 17
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
Esempio n. 18
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
Esempio n. 19
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
Esempio n. 20
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
Esempio n. 21
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
Esempio n. 22
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
Esempio n. 23
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
Esempio n. 24
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
Esempio n. 25
0
class DialogBaseInfo(windows.DialogXML):
    ACTION_PREVIOUS_MENU = [92, 9]
    ACTION_EXIT_SCRIPT = [13, 10]

    def __init__(self, *args, **kwargs):
        super(DialogBaseInfo, self).__init__(*args, **kwargs)
        self.logged_in = tmdb.Login.check_login()
        self.bouncing = False
        self.last_focus = None
        self.lists = None
        self.states = False
        self.yt_listitems = []
        self.info = VideoItem()
        self.last_control = None
        self.last_position = None

    def onInit(self, *args, **kwargs):
        super(DialogBaseInfo, self).onInit()
        # self.set_buttons()
        self.info.to_windowprops(window_id=self.window_id)
        for container_id, key in self.LISTS:
            try:
                self.getControl(container_id).reset()
                items = [i.get_listitem() for i in self.lists[key]]
                self.getControl(container_id).addItems(items)
            except Exception:
                utils.log("Notice: No container with id %i available" %
                          container_id)
        if self.last_control:
            self.setFocusId(self.last_control)
        if self.last_control and self.last_position:
            try:
                self.getControl(self.last_control).selectItem(
                    self.last_position)
            except Exception:
                pass
        addon.set_global("ImageColor", self.info.get_property('ImageColor'))
        addon.set_global("infobackground", self.info.get_art('fanart_small'))
        self.setProperty("type", self.TYPE)
        self.setProperty("tmdb_logged_in", "true" if self.logged_in else "")

    def onAction(self, action):
        ch.serve_action(action, self.getFocusId(), self)

    def onClick(self, control_id):
        super(DialogBaseInfo, self).onClick(control_id)
        ch.serve(control_id, self)

    def onFocus(self, control_id):
        if control_id == ID_BUTTON_BOUNCEUP:
            if not self.bouncing:
                self.bounce("up")
            self.setFocusId(self.last_focus)
        elif control_id == ID_BUTTON_BOUNCEDOWN:
            if not self.bouncing:
                self.bounce("down")
            self.setFocusId(self.last_focus)
        self.last_focus = control_id

    def close(self):
        try:
            self.last_position = self.getFocus().getSelectedPosition()
        except Exception:
            self.last_position = None
        addon.set_global("infobackground", "")
        self.last_control = self.getFocusId()
        super(DialogBaseInfo, self).close()

    @utils.run_async
    def bounce(self, identifier):
        self.bouncing = True
        self.setProperty("Bounce.%s" % identifier, "true")
        xbmc.sleep(200)
        self.clearProperty("Bounce.%s" % identifier)
        self.bouncing = False

    @ch.click_by_type("music")
    # hack: use "music" until "pictures" got added to core
    def open_image(self, control_id):
        key = [
            key for container_id, key in self.LISTS
            if container_id == control_id
        ][0]
        pos = slideshow.open(
            listitems=self.lists[key],
            index=self.getControl(control_id).getSelectedPosition())
        self.getControl(control_id).selectItem(pos)

    @ch.click_by_type("video")
    def play_youtube_video(self, control_id):
        wm.play_youtube_video(
            youtube_id=self.FocusedItem(control_id).getProperty("youtube_id"),
            listitem=self.FocusedItem(control_id))

    @ch.click_by_type("artist")
    def open_actor_info(self, control_id):
        wm.open_actor_info(
            actor_id=self.FocusedItem(control_id).getProperty("id"))

    @ch.click_by_type("movie")
    def open_movie_info(self, control_id):
        wm.open_movie_info(
            movie_id=self.FocusedItem(control_id).getProperty("id"),
            dbid=self.FocusedItem(control_id).getVideoInfoTag().getDbId())

    @ch.click_by_type("tvshow")
    def open_tvshow_info(self, control_id):
        wm.open_tvshow_info(
            tmdb_id=self.FocusedItem(control_id).getProperty("id"),
            dbid=self.FocusedItem(control_id).getVideoInfoTag().getDbId())

    @ch.click_by_type("episode")
    def open_episode_info(self, control_id):
        info = self.FocusedItem(control_id).getVideoInfoTag()
        wm.open_episode_info(tvshow=self.info.get_info("tvshowtitle"),
                             tvshow_id=self.tvshow_id,
                             season=info.getSeason(),
                             episode=info.getEpisode())

    @ch.context("music")
    def thumbnail_options(self, control_id):
        listitem = self.FocusedItem(control_id)
        art_type = listitem.getProperty("type")
        options = []
        if self.info.get_info("dbid") and art_type == "poster":
            options.append(("db_art", addon.LANG(32006)))
        if self.info.get_info("dbid") and art_type == "fanart":
            options.append(("db_art", addon.LANG(32007)))
        movie_id = listitem.getProperty("movie_id")
        if movie_id:
            options.append(("movie_info", addon.LANG(10524)))
        if not options:
            return None
        action = utils.contextmenu(options=options)
        if action == "db_art":
            kodijson.set_art(media_type=self.getProperty("type"),
                             art={art_type: listitem.get_art("original")},
                             dbid=self.info.get_info("dbid"))
        elif action == "movie_info":
            wm.open_movie_info(movie_id=listitem.getProperty("movie_id"),
                               dbid=listitem.getVideoInfoTag().getDbId())

    @ch.context("video")
    def video_context_menu(self, control_id):
        index = xbmcgui.Dialog().contextmenu(list=[addon.LANG(33003)])
        if index == 0:
            utils.download_video(
                self.FocusedItem(control_id).getProperty("youtube_id"))

    @ch.context("movie")
    def movie_context_menu(self, control_id):
        movie_id = self.FocusedItem(control_id).getProperty("id")
        dbid = self.FocusedItem(control_id).getVideoInfoTag().getDbId()
        options = [addon.LANG(32113)]
        if self.logged_in:
            options.append(addon.LANG(32083))
        index = xbmcgui.Dialog().contextmenu(list=options)
        if index == 0:
            rating = utils.input_userrating()
            if rating == -1:
                return None
            tmdb.set_rating(media_type="movie",
                            media_id=movie_id,
                            rating=rating,
                            dbid=dbid)
            xbmc.sleep(2000)
            tmdb.get_movie(movie_id=movie_id, cache_days=0)
        elif index == 1:
            account_lists = tmdb.get_account_lists()
            if not account_lists:
                return False
            listitems = [
                "%s (%i)" % (i["name"], i["item_count"]) for i in account_lists
            ]
            i = xbmcgui.Dialog().select(addon.LANG(32136), listitems)
            if i > -1:
                tmdb.change_list_status(list_id=account_lists[i]["id"],
                                        movie_id=movie_id,
                                        status=True)

    @ch.context("artist")
    def person_context_menu(self, control_id):
        listitem = self.FocusedItem(control_id)
        options = [addon.LANG(32009), addon.LANG(32070)]
        credit_id = listitem.getProperty("credit_id")
        if credit_id and self.TYPE == "TVShow":
            options.append(addon.LANG(32147))
        index = xbmcgui.Dialog().contextmenu(list=options)
        if index == 0:
            wm.open_actor_info(actor_id=listitem.getProperty("id"))
        if index == 1:
            filters = [{
                "id": listitem.getProperty("id"),
                "type": "with_people",
                "label": listitem.getLabel().decode("utf-8")
            }]
            wm.open_video_list(filters=filters)
        if index == 2:
            self.open_credit_dialog(credit_id)

    @ch.context("tvshow")
    def tvshow_context_menu(self, control_id):
        tvshow_id = self.FocusedItem(control_id).getProperty("id")
        dbid = self.FocusedItem(control_id).getVideoInfoTag().getDbId()
        credit_id = self.FocusedItem(control_id).getProperty("credit_id")
        options = [addon.LANG(32169)]
        if credit_id:
            options.append(addon.LANG(32147))
        index = xbmcgui.Dialog().contextmenu(list=options)
        if index == 0:
            rating = utils.input_userrating()
            if rating == -1:
                return None
            tmdb.set_rating(media_type="tvshow",
                            media_id=tvshow_id,
                            rating=rating,
                            dbid=dbid)
            xbmc.sleep(2000)
            tmdb.get_tvshow(tvshow_id=tvshow_id, cache_days=0)
        if index == 1:
            self.open_credit_dialog(credit_id=credit_id)

    @ch.action("parentdir", "*")
    @ch.action("parentfolder", "*")
    def previous_menu(self, control_id):
        onback = self.getProperty("%i_onback" % control_id)
        if onback:
            xbmc.executebuiltin(onback)
        else:
            self.close()

    @ch.action("previousmenu", "*")
    def exit_script(self, control_id):
        self.exit()

    @utils.run_async
    def get_youtube_vids(self, search_str):
        try:
            youtube_list = self.getControl(ID_LIST_YOUTUBE)
        except Exception:
            return None
        if not self.yt_listitems:
            self.yt_listitems = youtube.search(search_str, limit=15)
        vid_ids = [item.get_property("key") for item in self.lists["videos"]
                   ] if "videos" in self.lists else []
        youtube_list.reset()
        youtube_list.addItems([
            i.get_listitem() for i in self.yt_listitems
            if i.get_property("youtube_id") not in vid_ids
        ])

    def open_credit_dialog(self, credit_id):
        info = tmdb.get_credit_info(credit_id)
        listitems = []
        if "seasons" in info["media"]:
            listitems += tmdb.handle_seasons(info["media"]["seasons"])
        if "episodes" in info["media"]:
            listitems += tmdb.handle_episodes(info["media"]["episodes"])
        if not listitems:
            listitems += [{"label": addon.LANG(19055)}]
        index = selectdialog.open(header=addon.LANG(32151),
                                  listitems=listitems)
        if index == -1:
            return None
        listitem = listitems[index]
        if listitem["mediatype"] == "episode":
            wm.open_episode_info(season=listitem["season"],
                                 episode=listitem["episode"],
                                 tvshow_id=info["media"]["id"])
        elif listitem["mediatype"] == "season":
            wm.open_season_info(season=listitem["season"],
                                tvshow_id=info["media"]["id"])

    def update_states(self):
        if not self.states:
            return None
        utils.dict_to_windowprops(data=tmdb.get_account_props(self.states),
                                  window_id=self.window_id)
Esempio n. 26
0
 def handle_movie(self, movie):
     """
     convert movie data to listitems
     """
     trailer = PLUGIN_BASE + "playtrailer&&dbid=%s" % movie['movieid']
     if addon.setting("infodialog_onclick") != "false":
         path = PLUGIN_BASE + 'extendedinfo&&dbid=%s' % movie['movieid']
     else:
         path = PLUGIN_BASE + 'playmovie&&dbid=%i' % movie['movieid']
     resume = movie['resume']
     if (resume['position'] and resume['total']) > 0:
         resumable = "true"
         played = int((float(resume['position']) / float(resume['total'])) * 100)
     else:
         resumable = "false"
         played = 0
     db_movie = VideoItem(label=movie.get('label'),
                          path=path)
     db_movie.set_infos({'title': movie.get('label'),
                         'dbid': movie['movieid'],
                         'file': movie.get('file'),
                         'year': movie.get('year'),
                         'writer': " / ".join(movie['writer']),
                         'mediatype': "movie",
                         'set': movie.get("set"),
                         'playcount': movie.get("playcount"),
                         'setid': movie.get("setid"),
                         'top250': movie.get("top250"),
                         'imdbnumber': movie.get("imdbnumber"),
                         'userrating': movie.get('userrating'),
                         'trailer': trailer,
                         'rating': round(float(movie['rating']), 1),
                         'director': " / ".join(movie.get('director')),
                         'writer': " / ".join(movie.get('writer')),
                         # "tag": " / ".join(movie['tag']),
                         "genre": " / ".join(movie['genre']),
                         'plot': movie.get('plot'),
                         'plotoutline': movie.get('plotoutline'),
                         'studio': " / ".join(movie.get('studio')),
                         'mpaa': movie.get('mpaa'),
                         'originaltitle': movie.get('originaltitle')})
     db_movie.set_properties({'imdb_id': movie.get('imdbnumber'),
                              'showlink': " / ".join(movie['showlink']),
                              'percentplayed': played,
                              'resume': resumable})
     db_movie.set_artwork(movie['art'])
     db_movie.set_videoinfos(movie['streamdetails']["video"])
     db_movie.set_audioinfos(movie['streamdetails']["audio"])
     stream_info = media_streamdetails(movie['file'].encode('utf-8').lower(),
                                       movie['streamdetails'])
     db_movie.update_properties(stream_info)
     db_movie.set_cast(movie.get("cast"))
     return db_movie
Esempio n. 27
0
 def handle_movie(self, movie):
     """
     convert movie data to listitems
     """
     trailer = PLUGIN_BASE + "playtrailer&&dbid=%s" % movie['movieid']
     if addon.setting("infodialog_onclick") != "false":
         path = PLUGIN_BASE + 'extendedinfo&&dbid=%s' % movie['movieid']
     else:
         path = PLUGIN_BASE + 'playmovie&&dbid=%i' % movie['movieid']
     resume = movie['resume']
     if (resume['position'] and resume['total']) > 0:
         resumable = "true"
         played = int(
             (float(resume['position']) / float(resume['total'])) * 100)
     else:
         resumable = "false"
         played = 0
     db_movie = VideoItem(label=movie.get('label'), path=path)
     db_movie.set_infos({
         'title': movie.get('label'),
         'dbid': movie['movieid'],
         'file': movie.get('file'),
         'year': movie.get('year'),
         'writer': " / ".join(movie['writer']),
         'mediatype': "movie",
         'set': movie.get("set"),
         'playcount': movie.get("playcount"),
         'setid': movie.get("setid"),
         'top250': movie.get("top250"),
         'imdbnumber': movie.get("imdbnumber"),
         'userrating': movie.get('userrating'),
         'trailer': trailer,
         'rating': round(float(movie['rating']), 1),
         'director': " / ".join(movie.get('director')),
         'writer': " / ".join(movie.get('writer')),
         # "tag": " / ".join(movie['tag']),
         "genre": " / ".join(movie['genre']),
         'plot': movie.get('plot'),
         'plotoutline': movie.get('plotoutline'),
         'studio': " / ".join(movie.get('studio')),
         'mpaa': movie.get('mpaa'),
         'originaltitle': movie.get('originaltitle')
     })
     db_movie.set_properties({
         'imdb_id': movie.get('imdbnumber'),
         'showlink': " / ".join(movie['showlink']),
         'percentplayed': played,
         'resume': resumable
     })
     db_movie.set_artwork(movie['art'])
     db_movie.set_videoinfos(movie['streamdetails']["video"])
     db_movie.set_audioinfos(movie['streamdetails']["audio"])
     stream_info = media_streamdetails(
         movie['file'].encode('utf-8').lower(), movie['streamdetails'])
     db_movie.update_properties(stream_info)
     db_movie.set_cast(movie.get("cast"))
     return db_movie
class DialogBaseInfo(windows.DialogXML):
    ACTION_PREVIOUS_MENU = [92, 9]
    ACTION_EXIT_SCRIPT = [13, 10]

    def __init__(self, *args, **kwargs):
        super(DialogBaseInfo, self).__init__(*args, **kwargs)
        self.logged_in = tmdb.Login.check_login()
        self.bouncing = False
        self.last_focus = None
        self.lists = None
        self.states = False
        self.yt_listitems = []
        self.info = VideoItem()
        self.last_control = None
        self.last_position = None

    def onInit(self, *args, **kwargs):
        super(DialogBaseInfo, self).onInit()
        # self.set_buttons()
        self.info.to_windowprops(window_id=self.window_id)
        for container_id, key in self.LISTS:
            try:
                self.getControl(container_id).reset()
                items = [i.get_listitem() for i in self.lists[key]]
                self.getControl(container_id).addItems(items)
            except Exception:
                utils.log("Notice: No container with id %i available" % container_id)
        if self.last_control:
            self.setFocusId(self.last_control)
        if self.last_control and self.last_position:
            try:
                self.getControl(self.last_control).selectItem(self.last_position)
            except Exception:
                pass
        addon.set_global("ImageColor", self.info.get_property('ImageColor'))
        addon.set_global("infobackground", self.info.get_art('fanart_small'))
        self.setProperty("type", self.TYPE)
        self.setProperty("tmdb_logged_in", "true" if self.logged_in else "")

    def onAction(self, action):
        ch.serve_action(action, self.getFocusId(), self)

    def onClick(self, control_id):
        super(DialogBaseInfo, self).onClick(control_id)
        ch.serve(control_id, self)

    def onFocus(self, control_id):
        if control_id == ID_BUTTON_BOUNCEUP:
            if not self.bouncing:
                self.bounce("up")
            self.setFocusId(self.last_focus)
        elif control_id == ID_BUTTON_BOUNCEDOWN:
            if not self.bouncing:
                self.bounce("down")
            self.setFocusId(self.last_focus)
        self.last_focus = control_id

    def close(self):
        try:
            self.last_position = self.getFocus().getSelectedPosition()
        except Exception:
            self.last_position = None
        addon.set_global("infobackground", "")
        self.last_control = self.getFocusId()
        super(DialogBaseInfo, self).close()

    @utils.run_async
    def bounce(self, identifier):
        self.bouncing = True
        self.setProperty("Bounce.%s" % identifier, "true")
        xbmc.sleep(200)
        self.clearProperty("Bounce.%s" % identifier)
        self.bouncing = False

    @ch.click_by_type("music")
    # hack: use "music" until "pictures" got added to core
    def open_image(self, control_id):
        key = [key for container_id, key in self.LISTS if container_id == control_id][0]
        pos = slideshow.open(listitems=self.lists[key],
                             index=self.getControl(control_id).getSelectedPosition())
        self.getControl(control_id).selectItem(pos)

    @ch.click_by_type("video")
    def play_youtube_video(self, control_id):
        wm.play_youtube_video(youtube_id=self.FocusedItem(control_id).getProperty("youtube_id"),
                              listitem=self.FocusedItem(control_id))

    @ch.click_by_type("artist")
    def open_actor_info(self, control_id):
        wm.open_actor_info(actor_id=self.FocusedItem(control_id).getProperty("id"))

    @ch.click_by_type("movie")
    def open_movie_info(self, control_id):
        wm.open_movie_info(movie_id=self.FocusedItem(control_id).getProperty("id"),
                           dbid=self.FocusedItem(control_id).getVideoInfoTag().getDbId())

    @ch.click_by_type("tvshow")
    def open_tvshow_info(self, control_id):
        wm.open_tvshow_info(tmdb_id=self.FocusedItem(control_id).getProperty("id"),
                            dbid=self.FocusedItem(control_id).getVideoInfoTag().getDbId())

    @ch.click_by_type("episode")
    def open_episode_info(self, control_id):
        info = self.FocusedItem(control_id).getVideoInfoTag()
        wm.open_episode_info(tvshow=self.info.get_info("tvshowtitle"),
                             tvshow_id=self.tvshow_id,
                             season=info.getSeason(),
                             episode=info.getEpisode())

    @ch.context("music")
    def thumbnail_options(self, control_id):
        listitem = self.FocusedItem(control_id)
        art_type = listitem.getProperty("type")
        options = []
        if self.info.get_info("dbid") and art_type == "poster":
            options.append(("db_art", addon.LANG(32006)))
        if self.info.get_info("dbid") and art_type == "fanart":
            options.append(("db_art", addon.LANG(32007)))
        movie_id = listitem.getProperty("movie_id")
        if movie_id:
            options.append(("movie_info", addon.LANG(10524)))
        if not options:
            return None
        action = utils.contextmenu(options=options)
        if action == "db_art":
            kodijson.set_art(media_type=self.getProperty("type"),
                             art={art_type: listitem.get_art("original")},
                             dbid=self.info.get_info("dbid"))
        elif action == "movie_info":
            wm.open_movie_info(movie_id=listitem.getProperty("movie_id"),
                               dbid=listitem.getVideoInfoTag().getDbId())

    @ch.context("video")
    def video_context_menu(self, control_id):
        index = xbmcgui.Dialog().contextmenu(list=[addon.LANG(33003)])
        if index == 0:
            utils.download_video(self.FocusedItem(control_id).getProperty("youtube_id"))

    @ch.context("movie")
    def movie_context_menu(self, control_id):
        movie_id = self.FocusedItem(control_id).getProperty("id")
        dbid = self.FocusedItem(control_id).getVideoInfoTag().getDbId()
        options = [addon.LANG(32113)]
        if self.logged_in:
            options.append(addon.LANG(32083))
        index = xbmcgui.Dialog().contextmenu(list=options)
        if index == 0:
            rating = utils.input_userrating()
            if rating == -1:
                return None
            tmdb.set_rating(media_type="movie",
                            media_id=movie_id,
                            rating=rating,
                            dbid=dbid)
            xbmc.sleep(2000)
            tmdb.get_movie(movie_id=movie_id,
                           cache_days=0)
        elif index == 1:
            account_lists = tmdb.get_account_lists()
            if not account_lists:
                return False
            listitems = ["%s (%i)" % (i["name"], i["item_count"]) for i in account_lists]
            i = xbmcgui.Dialog().select(addon.LANG(32136), listitems)
            if i > -1:
                tmdb.change_list_status(list_id=account_lists[i]["id"],
                                        movie_id=movie_id,
                                        status=True)

    @ch.context("artist")
    def person_context_menu(self, control_id):
        listitem = self.FocusedItem(control_id)
        options = [addon.LANG(32009), addon.LANG(32070)]
        credit_id = listitem.getProperty("credit_id")
        if credit_id and self.TYPE == "TVShow":
            options.append(addon.LANG(32147))
        index = xbmcgui.Dialog().contextmenu(list=options)
        if index == 0:
            wm.open_actor_info(actor_id=listitem.getProperty("id"))
        if index == 1:
            filters = [{"id": listitem.getProperty("id"),
                        "type": "with_people",
                        "label": listitem.getLabel().decode("utf-8")}]
            wm.open_video_list(filters=filters)
        if index == 2:
            self.open_credit_dialog(credit_id)

    @ch.context("tvshow")
    def tvshow_context_menu(self, control_id):
        tvshow_id = self.FocusedItem(control_id).getProperty("id")
        dbid = self.FocusedItem(control_id).getVideoInfoTag().getDbId()
        credit_id = self.FocusedItem(control_id).getProperty("credit_id")
        options = [addon.LANG(32169)]
        if credit_id:
            options.append(addon.LANG(32147))
        index = xbmcgui.Dialog().contextmenu(list=options)
        if index == 0:
            rating = utils.input_userrating()
            if rating == -1:
                return None
            tmdb.set_rating(media_type="tvshow",
                            media_id=tvshow_id,
                            rating=rating,
                            dbid=dbid)
            xbmc.sleep(2000)
            tmdb.get_tvshow(tvshow_id=tvshow_id,
                            cache_days=0)
        if index == 1:
            self.open_credit_dialog(credit_id=credit_id)

    @ch.action("parentdir", "*")
    @ch.action("parentfolder", "*")
    def previous_menu(self, control_id):
        onback = self.getProperty("%i_onback" % control_id)
        if onback:
            xbmc.executebuiltin(onback)
        else:
            self.close()

    @ch.action("previousmenu", "*")
    def exit_script(self, control_id):
        self.exit()

    @utils.run_async
    def get_youtube_vids(self, search_str):
        try:
            youtube_list = self.getControl(ID_LIST_YOUTUBE)
        except Exception:
            return None
        if not self.yt_listitems:
            self.yt_listitems = youtube.search(search_str, limit=15)
        vid_ids = [item.get_property("key") for item in self.lists["videos"]] if "videos" in self.lists else []
        youtube_list.reset()
        youtube_list.addItems([i.get_listitem() for i in self.yt_listitems if i.get_property("youtube_id") not in vid_ids])

    def open_credit_dialog(self, credit_id):
        info = tmdb.get_credit_info(credit_id)
        listitems = []
        if "seasons" in info["media"]:
            listitems += tmdb.handle_seasons(info["media"]["seasons"])
        if "episodes" in info["media"]:
            listitems += tmdb.handle_episodes(info["media"]["episodes"])
        if not listitems:
            listitems += [{"label": addon.LANG(19055)}]
        index = selectdialog.open(header=addon.LANG(32151),
                                  listitems=listitems)
        if index == -1:
            return None
        listitem = listitems[index]
        if listitem["mediatype"] == "episode":
            wm.open_episode_info(season=listitem["season"],
                                 episode=listitem["episode"],
                                 tvshow_id=info["media"]["id"])
        elif listitem["mediatype"] == "season":
            wm.open_season_info(season=listitem["season"],
                                tvshow_id=info["media"]["id"])

    def update_states(self):
        if not self.states:
            return None
        utils.dict_to_windowprops(data=tmdb.get_account_props(self.states),
                                  window_id=self.window_id)
Esempio n. 29
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