def __init__(self, *args, **kwargs):
     super(DialogBaseInfo, self).__init__(*args, **kwargs)
     self.logged_in = tmdb.Login.check_login()
     self.dbid = kwargs.get('dbid')
     self.bouncing = False
     self.last_focus = None
     self.lists = None
     self.yt_listitems = []
     self.info = ListItem()
Ejemplo n.º 2
0
def handle_channels(results):
    channels = []
    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 = ListItem(label=snippet["title"],
                           path=PLUGIN_BASE +
                           'youtubechannel&&id=%s' % channel_id)
        channel.set_infos({
            'plot': snippet["description"],
            'premiered': snippet["publishedAt"][:10]
        })
        channel.set_art("thumb", thumb)
        channel.set_property("youtube_id", channel_id)
        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
Ejemplo n.º 3
0
def handle_channels(results):
    channels = []
    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 = ListItem(label=snippet["title"],
                           path=PLUGIN_BASE + 'youtubechannel&&id=%s' % channel_id)
        channel.set_infos({'plot': snippet["description"],
                           'premiered': snippet["publishedAt"][:10]})
        channel.set_art("thumb", thumb)
        channel.set_property("youtube_id", channel_id)
        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
Ejemplo n.º 4
0
def get_movies(movie_type):
    movies = []
    url = '%s.json?apikey=%s' % (movie_type, RT_KEY)
    results = utils.get_JSON_response(BASE_URL + url, folder="RottenTomatoes")
    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 = ListItem(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,
                              'duration(h)': utils.format_time(item["runtime"], "h"),
                              'duration(m)': utils.format_time(item["runtime"], "m")})
        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)
Ejemplo n.º 5
0
def handle_playlists(results):
    playlists = []
    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 = ListItem(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"],
                                 '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
Ejemplo n.º 6
0
 def __init__(self, *args, **kwargs):
     super(DialogBaseInfo, self).__init__(*args, **kwargs)
     self.logged_in = tmdb.Login.check_login()
     self.dbid = kwargs.get('dbid')
     self.bouncing = False
     self.last_focus = None
     self.lists = None
     self.yt_listitems = []
     self.info = ListItem()
Ejemplo n.º 7
0
def handle_movies(results):
    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
        movie = ListItem(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': utils.convert_youtube_url(item["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"),
            'duration(h)':
            utils.format_time(item["runtime"], "h"),
            'duration(m)':
            utils.format_time(item["runtime"], "m")
        })
        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)
    return movies
Ejemplo n.º 8
0
def get_episodes(content):
    shows = []
    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]:
            title = episode["episode"]["title"] if episode["episode"]["title"] else ""
            label = u"{0} - {1}x{2}. {3}".format(episode["show"]["title"],
                                                 episode["episode"]["season"],
                                                 episode["episode"]["number"],
                                                 title)
            show = ListItem(label=label,
                            path=PLUGIN_BASE + 'extendedtvinfo&&tvdb_id=%s' % episode["show"]["ids"]["tvdb"])
            show.set_infos({'title': title,
                            'aired': episode["episode"]["first_aired"],
                            'season': episode["episode"]["season"],
                            'episode': episode["episode"]["number"],
                            'tvshowtitle': episode["show"]["title"],
                            'mediatype': "episode",
                            'year': episode["show"].get("year"),
                            'duration': episode["show"]["runtime"] * 60,
                            'studio': episode["show"]["network"],
                            'plot': episode["show"]["overview"],
                            'country': episode["show"]["country"],
                            'status': episode["show"]["status"],
                            'trailer': episode["show"]["trailer"],
                            'imdbnumber': episode["episode"]["ids"]["imdb"],
                            'rating': episode["show"]["rating"],
                            'genre': " / ".join(episode["show"]["genres"]),
                            'mpaa': episode["show"]["certification"]})
            show.set_properties({'tvdb_id': episode["episode"]["ids"]["tvdb"],
                                 'id': episode["episode"]["ids"]["tvdb"],
                                 'imdb_id': episode["episode"]["ids"]["imdb"],
                                 'homepage': episode["show"]["homepage"],
                                 'duration(h)': utils.format_time(episode["show"]["runtime"], "h"),
                                 'duration(m)': utils.format_time(episode["show"]["runtime"], "m")})
            show.set_artwork({'thumb': episode["episode"]["images"]["screenshot"]["thumb"],
                              'poster': episode["show"]["images"]["poster"]["full"],
                              'banner': episode["show"]["images"]["banner"]["full"],
                              'clearart': episode["show"]["images"]["clearart"]["full"],
                              'clearlogo': episode["show"]["images"]["logo"]["full"],
                              'fanart': episode["show"]["images"]["fanart"]["full"]})
            shows.append(show)
            count += 1
            if count > 20:
                break
    return shows
Ejemplo n.º 9
0
def handle_videos(results, extended=False):
    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 = ListItem(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_properties({'channel_title': snippet["channelTitle"],
                              'channel_id': snippet["channelId"],
                              'youtube_id': video_id,
                              'Play': PLUGIN_BASE + 'youtubevideo&&id=%s' % 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']
            duration = details['duration']
            likes = ext_item['statistics'].get('likeCount')
            dislikes = ext_item['statistics'].get('dislikeCount')
            item.set_infos({"duration": duration,
                            "mediatype": "video"})
            props = {"duration": details['duration'][2:].lower(),
                     "dimension": details['dimension'],
                     "definition": details['definition'],
                     "caption": details['caption'],
                     "viewcount": utils.millify(ext_item['statistics']['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", format(float(likes) / vote_count * 10, '.2f'))
            break
    return videos
def get_movies(movie_type):
    movies = []
    url = '%s.json?apikey=%s' % (movie_type, RT_KEY)
    results = utils.get_JSON_response(BASE_URL + url, folder="RottenTomatoes")
    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 = ListItem(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,
            'duration(h)':
            utils.format_time(item["runtime"], "h"),
            'duration(m)':
            utils.format_time(item["runtime"], "m")
        })
        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)
Ejemplo n.º 11
0
def handle_tvshows(results):
    shows = []
    for i in results:
        item = i["show"] if "show" in i else i
        airs = item.get("airs", {})
        show = ListItem(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"],
                             'duration(h)': utils.format_time(item["runtime"], "h"),
                             'duration(m)': utils.format_time(item["runtime"], "m"),
                             '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)
    return shows
Ejemplo n.º 12
0
def handle_playlists(results):
    playlists = []
    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 = ListItem(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"],
            '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
Ejemplo n.º 13
0
def handle_movies(results):
    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
        movie = ListItem(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': utils.convert_youtube_url(item["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"),
                              'duration(h)': utils.format_time(item["runtime"], "h"),
                              'duration(m)': utils.format_time(item["runtime"], "m")})
        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)
    return movies
class DialogBaseInfo(object):
    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.dbid = kwargs.get('dbid')
        self.bouncing = False
        self.last_focus = None
        self.lists = None
        self.yt_listitems = []
        self.info = ListItem()

    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)
        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):
        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

    @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_slideshow(
            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),
            window=self)

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

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

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

    @ch.context("music")
    def thumbnail_options(self, control_id):
        if not self.info.get("dbid"):
            return None
        options = [addon.LANG(32006)
                   ] if control_id == ID_LIST_IMAGES else [addon.LANG(32007)]
        selection = xbmcgui.Dialog().contextmenu(list=options)
        if selection == 0:
            listitem = self.FocusedItem(control_id)
            kodijson.set_art(media_type=self.getProperty("type"),
                             art={
                                 listitem.getProperty("type"):
                                 listitem.get_art("original")
                             },
                             dbid=self.info.get_info("dbid"))

    @ch.context("video")
    def video_context_menu(self, control_id):
        selection = xbmcgui.Dialog().contextmenu(list=[addon.LANG(33003)])
        if selection == 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))
        selection = xbmcgui.Dialog().contextmenu(list=options)
        if selection == 0:
            rating = utils.input_userrating()
            tmdb.set_rating(media_type="movie",
                            media_id=movie_id,
                            rating=rating,
                            dbid=dbid)
            xbmc.sleep(2000)
            tmdb.extended_movie_info(movie_id=movie_id,
                                     dbid=dbid,
                                     cache_time=0)
        elif selection == 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))
        selection = xbmcgui.Dialog().contextmenu(list=options)
        if selection == 0:
            wm.open_actor_info(prev_window=self,
                               actor_id=listitem.getProperty("id"))
        if selection == 1:
            filters = [{
                "id": listitem.getProperty("id"),
                "type": "with_people",
                "typelabel": addon.LANG(32156),
                "label": listitem.getLabel().decode("utf-8")
            }]
            wm.open_video_list(prev_window=self, filters=filters)
        if selection == 2:
            self.open_credit_dialog(credit_id)

    @ch.context("tvshow")
    def tvshow_context_menu(self, control_id):
        credit_id = self.FocusedItem(control_id).getProperty("credit_id")
        options = [addon.LANG(32148)]
        if credit_id:
            options.append(addon.LANG(32147))
        selection = xbmcgui.Dialog().contextmenu(list=options)
        if selection == 0:
            wm.open_tvshow_info(
                prev_window=self,
                tmdb_id=self.FocusedItem(control_id).getProperty("id"),
                dbid=self.FocusedItem(control_id).getVideoInfoTag().getDbId())
        if selection == 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()
            wm.pop_stack()

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

    @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:
            result = YouTube.search(search_str, limit=15)
            self.yt_listitems = result.get("listitems", [])
            if "videos" in self.lists:
                vid_ids = [
                    item.get_property("key") for item in self.lists["videos"]
                ]
                self.yt_listitems = [
                    i for i in self.yt_listitems
                    if i.get_property("youtube_id") not in vid_ids
                ]
        youtube_list.reset()
        youtube_list.addItems(utils.create_listitems(self.yt_listitems))

    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)}]
        listitem, index = selectdialog.open_selectdialog(
            header=addon.LANG(32151), listitems=listitems)
        if listitem["mediatype"] == "episode":
            wm.open_episode_info(prev_window=self,
                                 season=listitems[index]["season"],
                                 episode=listitems[index]["episode"],
                                 tvshow_id=info["media"]["id"])
        elif listitem["mediatype"] == "season":
            wm.open_season_info(prev_window=self,
                                season=listitems[index]["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)
Ejemplo n.º 15
0
class DialogBaseInfo(object):
    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.dbid = kwargs.get('dbid')
        self.bouncing = False
        self.last_focus = None
        self.lists = None
        self.yt_listitems = []
        self.info = ListItem()

    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)
        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):
        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

    @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_slideshow(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),
                              window=self)

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

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

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

    @ch.context("music")
    def thumbnail_options(self, control_id):
        if not self.info.get("dbid"):
            return None
        options = [addon.LANG(32006)] if control_id == ID_LIST_IMAGES else [addon.LANG(32007)]
        selection = xbmcgui.Dialog().contextmenu(list=options)
        if selection == 0:
            listitem = self.FocusedItem(control_id)
            kodijson.set_art(media_type=self.getProperty("type"),
                             art={listitem.getProperty("type"): listitem.get_art("original")},
                             dbid=self.info.get_info("dbid"))

    @ch.context("video")
    def video_context_menu(self, control_id):
        selection = xbmcgui.Dialog().contextmenu(list=[addon.LANG(33003)])
        if selection == 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))
        selection = xbmcgui.Dialog().contextmenu(list=options)
        if selection == 0:
            rating = utils.input_userrating()
            tmdb.set_rating(media_type="movie",
                            media_id=movie_id,
                            rating=rating,
                            dbid=dbid)
            xbmc.sleep(2000)
            tmdb.extended_movie_info(movie_id=movie_id,
                                     dbid=dbid,
                                     cache_time=0)
        elif selection == 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))
        selection = xbmcgui.Dialog().contextmenu(list=options)
        if selection == 0:
            wm.open_actor_info(prev_window=self,
                               actor_id=listitem.getProperty("id"))
        if selection == 1:
            filters = [{"id": listitem.getProperty("id"),
                        "type": "with_people",
                        "typelabel": addon.LANG(32156),
                        "label": listitem.getLabel().decode("utf-8")}]
            wm.open_video_list(prev_window=self,
                               filters=filters)
        if selection == 2:
            self.open_credit_dialog(credit_id)

    @ch.context("tvshow")
    def tvshow_context_menu(self, control_id):
        credit_id = self.FocusedItem(control_id).getProperty("credit_id")
        options = [addon.LANG(32148)]
        if credit_id:
            options.append(addon.LANG(32147))
        selection = xbmcgui.Dialog().contextmenu(list=options)
        if selection == 0:
            wm.open_tvshow_info(prev_window=self,
                                tmdb_id=self.FocusedItem(control_id).getProperty("id"),
                                dbid=self.FocusedItem(control_id).getVideoInfoTag().getDbId())
        if selection == 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()
            wm.pop_stack()

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

    @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:
            result = YouTube.search(search_str, limit=15)
            self.yt_listitems = result.get("listitems", [])
            if "videos" in self.lists:
                vid_ids = [item.get_property("key") for item in self.lists["videos"]]
                self.yt_listitems = [i for i in self.yt_listitems if i.get_property("youtube_id") not in vid_ids]
        youtube_list.reset()
        youtube_list.addItems(utils.create_listitems(self.yt_listitems))

    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)}]
        listitem, index = selectdialog.open_selectdialog(header=addon.LANG(32151),
                                                         listitems=listitems)
        if listitem["mediatype"] == "episode":
            wm.open_episode_info(prev_window=self,
                                 season=listitems[index]["season"],
                                 episode=listitems[index]["episode"],
                                 tvshow_id=info["media"]["id"])
        elif listitem["mediatype"] == "season":
            wm.open_season_info(prev_window=self,
                                season=listitems[index]["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)
Ejemplo n.º 16
0
def handle_videos(results, extended=False):
    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 = ListItem(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_properties({
            'channel_title':
            snippet["channelTitle"],
            'channel_id':
            snippet["channelId"],
            'youtube_id':
            video_id,
            'Play':
            PLUGIN_BASE + 'youtubevideo&&id=%s' % 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']
            duration = details['duration']
            likes = ext_item['statistics'].get('likeCount')
            dislikes = ext_item['statistics'].get('dislikeCount')
            item.set_infos({"duration": duration, "mediatype": "video"})
            props = {
                "duration": details['duration'][2:].lower(),
                "dimension": details['dimension'],
                "definition": details['definition'],
                "caption": details['caption'],
                "viewcount":
                utils.millify(ext_item['statistics']['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",
                        format(float(likes) / vote_count * 10, '.2f'))
            break
    return videos
Ejemplo n.º 17
0
def get_episodes(content):
    shows = []
    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]:
            title = episode["episode"]["title"] if episode["episode"][
                "title"] else ""
            label = u"{0} - {1}x{2}. {3}".format(episode["show"]["title"],
                                                 episode["episode"]["season"],
                                                 episode["episode"]["number"],
                                                 title)
            show = ListItem(
                label=label,
                path=PLUGIN_BASE +
                'extendedtvinfo&&tvdb_id=%s' % episode["show"]["ids"]["tvdb"])
            show.set_infos({
                'title': title,
                'aired': episode["episode"]["first_aired"],
                'season': episode["episode"]["season"],
                'episode': episode["episode"]["number"],
                'tvshowtitle': episode["show"]["title"],
                'mediatype': "episode",
                'year': episode["show"].get("year"),
                'duration': episode["show"]["runtime"] * 60,
                'studio': episode["show"]["network"],
                'plot': episode["show"]["overview"],
                'country': episode["show"]["country"],
                'status': episode["show"]["status"],
                'trailer': episode["show"]["trailer"],
                'imdbnumber': episode["episode"]["ids"]["imdb"],
                'rating': episode["show"]["rating"],
                'genre': " / ".join(episode["show"]["genres"]),
                'mpaa': episode["show"]["certification"]
            })
            show.set_properties({
                'tvdb_id':
                episode["episode"]["ids"]["tvdb"],
                'id':
                episode["episode"]["ids"]["tvdb"],
                'imdb_id':
                episode["episode"]["ids"]["imdb"],
                'homepage':
                episode["show"]["homepage"],
                'duration(h)':
                utils.format_time(episode["show"]["runtime"], "h"),
                'duration(m)':
                utils.format_time(episode["show"]["runtime"], "m")
            })
            show.set_artwork({
                'thumb':
                episode["episode"]["images"]["screenshot"]["thumb"],
                'poster':
                episode["show"]["images"]["poster"]["full"],
                'banner':
                episode["show"]["images"]["banner"]["full"],
                'clearart':
                episode["show"]["images"]["clearart"]["full"],
                'clearlogo':
                episode["show"]["images"]["logo"]["full"],
                'fanart':
                episode["show"]["images"]["fanart"]["full"]
            })
            shows.append(show)
            count += 1
            if count > 20:
                break
    return shows
Ejemplo n.º 18
0
def handle_tvshows(results):
    shows = []
    for i in results:
        item = i["show"] if "show" in i else i
        airs = item.get("airs", {})
        show = ListItem(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"],
            'duration(h)':
            utils.format_time(item["runtime"], "h"),
            'duration(m)':
            utils.format_time(item["runtime"], "m"),
            '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)
    return shows