Пример #1
0
def set_library_window_values(force=False):
    log.debug("set_library_window_values Called forced={0}", force)
    home_window = HomeWindow()

    already_set = home_window.getProperty("view_item.0.name")
    if not force and already_set:
        return

    for index in range(0, 20):
        home_window.clearProperty("view_item.%i.name" % index)
        home_window.clearProperty("view_item.%i.id" % index)
        home_window.clearProperty("view_item.%i.type" % index)
        home_window.clearProperty("view_item.%i.thumb" % index)

    data_manager = DataManager()
    url = "{server}/emby/Users/{userid}/Views"
    result = data_manager.GetContent(url)

    if result is None:
        return

    result = result.get("Items")
    server = downloadUtils.getServer()

    index = 0
    for item in result:

        type = item.get("CollectionType")
        if type in ["movies", "boxsets", "music", "tvshows"]:
            name = item.get("Name")
            id = item.get("Id")

            # plugin.video.jellyfincon-
            prop_name = "view_item.%i.name" % index
            home_window.setProperty(prop_name, name)
            log.debug(
                "set_library_window_values: plugin.video.jellyfincon-{0}={1}",
                prop_name, name)

            prop_name = "view_item.%i.id" % index
            home_window.setProperty(prop_name, id)
            log.debug(
                "set_library_window_values: plugin.video.jellyfincon-{0}={1}",
                prop_name, id)

            prop_name = "view_item.%i.type" % index
            home_window.setProperty(prop_name, type)
            log.debug(
                "set_library_window_values: plugin.video.jellyfincon-{0}={1}",
                prop_name, type)

            thumb = downloadUtils.getArtwork(item, "Primary", server=server)
            prop_name = "view_item.%i.thumb" % index
            home_window.setProperty(prop_name, thumb)
            log.debug(
                "set_library_window_values: plugin.video.jellyfincon-{0}={1}",
                prop_name, thumb)

            index += 1
Пример #2
0
def playListOfItems(id_list, monitor):
    log.debug("Loading  all items in the list")
    data_manager = DataManager()
    items = []

    for id in id_list:
        url = "{server}/emby/Users/{userid}/Items/" + id + "?format=json"
        result = data_manager.GetContent(url)
        if result is None:
            log.debug("Playfile item was None, so can not play!")
            return
        items.append(result)

    return playAllFiles(items, monitor)
Пример #3
0
def toggle_watched(params):
    log.debug("toggle_watched: {0}", params)
    item_id = params.get("item_id", None)
    if item_id is None:
        return
    url = "{server}/emby/Users/{userid}/Items/" + item_id + "?format=json"
    data_manager = DataManager()
    result = data_manager.GetContent(url)
    log.debug("toggle_watched item info: {0}", result)

    user_data = result.get("UserData", None)
    if user_data is None:
        return

    if user_data.get("Played", False) is False:
        markWatched(item_id)
    else:
        markUnwatched(item_id)
def get_next_episode(item):

    if item.get("Type", "na") != "Episode":
        log.debug("Not an episode, can not get next")
        return None

    parendId = item.get("ParentId", "na")
    item_index = item.get("IndexNumber", -1)

    if parendId == "na":
        log.debug("No parent id, can not get next")
        return None

    if item_index == -1:
        log.debug("No episode number, can not get next")
        return None

    url = ( '{server}/emby/Users/{userid}/Items?' +
            '?Recursive=true' +
            '&ParentId=' + parendId +
            '&IsVirtualUnaired=false' +
            '&IsMissing=False' +
            '&IncludeItemTypes=Episode' +
            '&ImageTypeLimit=1' +
            '&format=json')

    data_manager = DataManager()
    items_result = data_manager.GetContent(url)
    log.debug("get_next_episode, sibling list: {0}", items_result)

    if items_result is None:
        log.debug("get_next_episode no results")
        return None

    item_list = items_result.get("Items", [])

    for item in item_list:
        index = item.get("IndexNumber", -1)
        # find the very next episode in the season
        if index == item_index + 1:
            log.debug("get_next_episode, found next episode: {0}", item)
            return item

    return None
Пример #5
0
    def cache_artwork(self, progress):
        log.debug("cache_artwork")

        # is the web server enabled
        web_query = {"setting": "services.webserver"}
        result = json_rpc('Settings.GetSettingValue').execute(web_query)
        xbmc_webserver_enabled = result['result']['value']
        if not xbmc_webserver_enabled:
            log.debug("Kodi web server not enabled, can not cache images")
            return

        # get the port
        web_port = {"setting": "services.webserverport"}
        result = json_rpc('Settings.GetSettingValue').execute(web_port)
        xbmc_port = result['result']['value']
        log.debug("xbmc_port: {0}", xbmc_port)

        # get the user
        web_user = {"setting": "services.webserverusername"}
        result = json_rpc('Settings.GetSettingValue').execute(web_user)
        xbmc_username = result['result']['value']
        log.debug("xbmc_username: {0}", xbmc_username)

        # get the password
        web_pass = {"setting": "services.webserverpassword"}
        result = json_rpc('Settings.GetSettingValue').execute(web_pass)
        xbmc_password = result['result']['value']

        params = {"properties": ["url"]}
        json_result = json_rpc('Textures.GetTextures').execute(params)
        textures = json_result.get("result", {}).get("textures", [])

        if self.stop_all_activity:
            return

        texture_urls = set()
        for texture in textures:
            url = texture.get("url")
            url = urllib.unquote(url)
            url = url.replace("image://", "")
            url = url[0:-1]
            texture_urls.add(url)

        del textures
        del json_result

        if self.stop_all_activity:
            return

        url = ('{server}/emby/Users/{userid}/Items?' + '&Recursive=true' +
               '&IncludeItemTypes=Movie,Series,Episode,BoxSet' +
               '&ImageTypeLimit=1' + '&format=json')

        data_manager = DataManager()
        results = data_manager.GetContent(url)
        if results is None:
            results = []

        if isinstance(results, dict):
            results = results.get("Items")

        server = downloadUtils.getServer()
        missing_texture_urls = set()

        if self.stop_all_activity:
            return

        image_types = [
            "thumb", "poster", "banner", "clearlogo", "tvshow.poster",
            "tvshow.banner", "tvshow.landscape"
        ]
        for item in results:
            art = getArt(item, server)
            for image_type in art:
                image_url = art[image_type]
                if image_url not in texture_urls and not image_url.endswith(
                        "&Tag=") and len(image_url) > 0:
                    missing_texture_urls.add(image_url)

            if self.stop_all_activity:
                return

        log.debug("texture_urls: {0}", texture_urls)
        log.debug("missing_texture_urls: {0}", missing_texture_urls)
        log.debug("Number of existing textures: {0}", len(texture_urls))
        log.debug("Number of missing textures: {0}", len(missing_texture_urls))

        kodi_http_server = "localhost:" + str(xbmc_port)
        headers = {}
        if xbmc_password:
            auth = "%s:%s" % (xbmc_username, xbmc_password)
            headers = {'Authorization': 'Basic %s' % base64.b64encode(auth)}

        total = len(missing_texture_urls)
        index = 1

        count_done = 0
        for get_url in missing_texture_urls:
            log.debug("texture_url: {0}", get_url)
            url = double_urlencode(get_url)
            kodi_texture_url = ("/image/image://%s" % url)
            log.debug("kodi_texture_url: {0}", kodi_texture_url)

            percentage = int((float(index) / float(total)) * 100)
            message = "%s of %s" % (index, total)
            progress.update(percentage, "%s" % (message))

            conn = httplib.HTTPConnection(kodi_http_server, timeout=20)
            conn.request(method="GET", url=kodi_texture_url, headers=headers)
            data = conn.getresponse()
            if data.status == 200:
                count_done += 1
            log.debug("Get Image Result: {0}", data.status)

            index += 1
            if "iscanceled" in dir(progress) and progress.iscanceled():
                break

            if self.stop_all_activity:
                break

        result_report = []
        result_report.append(
            i18n('existing_textures') + str(len(texture_urls)))
        result_report.append(
            i18n('missing_textures') + str(len(missing_texture_urls)))
        result_report.append(i18n('loaded_textures') + str(count_done))
        return result_report
Пример #6
0
def showMenu(params):
    log.debug("showMenu(): {0}", params)

    item_id = params["item_id"]

    url = "{server}/emby/Users/{userid}/Items/" + item_id + "?format=json"
    data_manager = DataManager()
    result = data_manager.GetContent(url)
    log.debug("Playfile item info: {0}", result)

    if result is None:
        return

    action_items = []
    
    if result["Type"] in ["Episode", "Movie", "Music"]:
        li = xbmcgui.ListItem(i18n('play'))
        li.setProperty('menu_id', 'play')
        action_items.append(li)

    if result["Type"] in ["Season", "MusicAlbum"]:
        li = xbmcgui.ListItem(i18n('play_all'))
        li.setProperty('menu_id', 'play_all')
        action_items.append(li)

    if result["Type"] in ["Episode", "Movie"]:
        li = xbmcgui.ListItem(i18n('emby_force_transcode'))
        li.setProperty('menu_id', 'transcode')
        action_items.append(li)

    if result["Type"] == "Movie":
        li = xbmcgui.ListItem(i18n('play_trailer'))
        li.setProperty('menu_id', 'play_trailer')
        action_items.append(li)

    if result["Type"] == "Episode" and result["ParentId"] is not None:
        li = xbmcgui.ListItem(i18n('view_season'))
        li.setProperty('menu_id', 'view_season')
        action_items.append(li)

    user_data = result["UserData"]
    if user_data.get("Played", False) is False:
        li = xbmcgui.ListItem(i18n('emby_mark_watched'))
        li.setProperty('menu_id', 'mark_watched')
        action_items.append(li)
    else:
        li = xbmcgui.ListItem(i18n('emby_mark_unwatched'))
        li.setProperty('menu_id', 'mark_unwatched')
        action_items.append(li)

    if user_data["IsFavorite"] == False:
        li = xbmcgui.ListItem(i18n('emby_set_favorite'))
        li.setProperty('menu_id', 'emby_set_favorite')
        action_items.append(li)
    else:
        li = xbmcgui.ListItem(i18n('emby_unset_favorite'))
        li.setProperty('menu_id', 'emby_unset_favorite')
        action_items.append(li)

    li = xbmcgui.ListItem(i18n('emby_delete'))
    li.setProperty('menu_id', 'delete')
    action_items.append(li)

    #xbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc=False)

    action_menu = ActionMenu("ActionMenu.xml", PLUGINPATH, "default", "720p")
    action_menu.setActionItems(action_items)
    action_menu.doModal()
    selected_action_item = action_menu.getActionItem()
    selected_action = ""
    if selected_action_item is not None:
        selected_action = selected_action_item.getProperty('menu_id')
    log.debug("Menu Action Selected: {0}", selected_action_item)
    del action_menu

    if selected_action == "play":
        log.debug("Play Item")
        #list_item = populate_listitem(params["item_id"])
        #result = xbmcgui.Dialog().info(list_item)
        #log.debug("xbmcgui.Dialog().info: {0}", result)
        PLAY(params)

    elif selected_action == "play_all":
        PLAY(params)

    elif selected_action == "play_trailer":
        playTrailer(item_id)

    elif selected_action == "transcode":
        params['force_transcode'] = 'true'
        PLAY(params)

    elif selected_action == "emby_set_favorite":
        markFavorite(item_id)

    elif selected_action == "emby_unset_favorite":
        unmarkFavorite(item_id)

    elif selected_action == "mark_watched":
        markWatched(item_id)

    elif selected_action == "mark_unwatched":
        markUnwatched(item_id)

    elif selected_action == "delete":
        delete(result)

    elif selected_action == "view_season":
        parent_id = result["ParentId"]
        xbmc.executebuiltin(
            'ActivateWindow(Videos, plugin://plugin.video.embycon/?mode=PARENT_CONTENT&ParentId={0}&media_type=episodes, return)'.format(parent_id))
Пример #7
0
def populateWidgetItems(itemsUrl, override_select_action=None):

    server = downloadUtils.getServer()
    if server is None:
        return []

    settings = xbmcaddon.Addon()
    select_action = settings.getSetting("widget_select_action")

    if override_select_action is not None:
        select_action = str(override_select_action)

    log.debug("WIDGET_DATE_URL: {0}", itemsUrl)

    home_window = HomeWindow()

    # get the items
    data_manager = DataManager()
    result = data_manager.GetContent(itemsUrl)

    if result is not None and isinstance(
            result, dict) and result.get("Items") is not None:
        simmilarTo = result.get("BaselineItemName", None)
        result = result.get("Items")
    elif result is not None and isinstance(result, list) and len(result) > 0:
        simmilarTo = result[0].get("BaselineItemName", None)
        result = result[0].get("Items")
    else:
        result = []

    itemCount = 1
    listItems = []
    for item in result:
        item_id = item["Id"]
        name = item["Name"]
        episodeDetails = ""
        log.debug("WIDGET_DATE_NAME: {0}", name)

        title = name
        tvshowtitle = ""
        item_type = item["Type"]
        series_name = item["SeriesName"]

        if item_type == "Episode" and series_name is not None:

            episode_number = item["IndexNumber"]
            if episode_number is None:
                episode_number = 0

            season_number = item["ParentIndexNumber"]
            if season_number is None:
                season_number = 0

            name = series_name + " " + episodeDetails
            name = "%s S%02dE%02d" % (series_name, season_number,
                                      episode_number)
            tvshowtitle = "S%02dE%02d" % (season_number, episode_number)
            title = series_name

        art = getArt(item, server, widget=True)

        if kodi_version > 17:
            list_item = xbmcgui.ListItem(label=name,
                                         iconImage=art['thumb'],
                                         offscreen=True)
        else:
            list_item = xbmcgui.ListItem(label=name, iconImage=art['thumb'])

        # list_item.setLabel2(episodeDetails)

        production_year = item["ProductionYear"]
        prem_year = item["PremiereDate"]
        if production_year is None and prem_year is not None:
            production_year = int(prem_year[:4])

        # add progress percent
        userData = item["UserData"]
        if userData["Played"] == True:
            playCount = "1"
            overlay = "5"
        else:
            playCount = "0"
            overlay = "6"

        runtime = item["RunTimeTicks"]
        playBackTicks = userData["PlaybackPositionTicks"]

        if playBackTicks is not None and runtime is not None and runtime > 0:
            runtime = float(runtime)
            playBackTicks = float(playBackTicks)
            playBackPos = int(((playBackTicks / 1000) / 10000) / 60)
            list_item.setProperty('ResumeTime', str(playBackPos))
            percentage = int((playBackTicks / runtime) * 100.0)
            list_item.setProperty("complete_percentage", str(percentage))

        video_info_label = {
            "title": title,
            "tvshowtitle": tvshowtitle,
            "year": production_year,
            "Overlay": overlay,
            "playcount": playCount
        }

        list_item.setInfo(type="Video", infoLabels=video_info_label)
        list_item.setProperty('fanart_image', art['fanart'])  # back compat
        list_item.setProperty('discart', art['discart'])  # not avail to setArt
        list_item.setArt(art)
        # add count
        #list_item.setProperty("item_index", str(itemCount))
        #itemCount = itemCount + 1

        list_item.setProperty('IsPlayable', 'false')

        if runtime is not None:
            totalTime = str(int(float(runtime) / (10000000 * 60)))
            list_item.setProperty('TotalTime', str(totalTime))

        list_item.setContentLookup(False)
        list_item.setProperty('id', item_id)

        if simmilarTo is not None:
            list_item.setProperty('suggested_from_watching', simmilarTo)

        session_id = "&session_id=" + home_window.getProperty("session_id")

        if select_action == "1":
            playurl = "plugin://plugin.video.embycon/?item_id=" + item_id + '&mode=PLAY' + session_id
        elif select_action == "0":
            playurl = "plugin://plugin.video.embycon/?item_id=" + item_id + '&mode=SHOW_MENU' + session_id

        itemTupple = (playurl, list_item, False)
        listItems.append(itemTupple)

    return listItems
Пример #8
0
def getWidgetContentCast(handle, params):
    log.debug("getWigetContentCast Called: {0}", params)
    server = downloadUtils.getServer()

    id = params["id"]
    data_manager = DataManager()
    result = data_manager.GetContent("{server}/emby/Users/{userid}/Items/" +
                                     id + "?format=json")
    log.debug("ItemInfo: {0}", result)

    listItems = []
    if result is not None:
        people = result.get("People")
    else:
        people = None

    if people is not None:
        for person in people:
            #if (person.get("Type") == "Director"):
            #    director = director + person.get("Name") + ' '
            #if (person.get("Type") == "Writing"):
            #    writer = person.get("Name")
            #if (person.get("Type") == "Writer"):
            #    writer = person.get("Name")
            if (person.get("Type") == "Actor"):
                person_name = person.get("Name")
                person_role = person.get("Role")
                person_id = person.get("Id")
                person_tag = person.get("PrimaryImageTag")
                person_thumbnail = None
                if person_tag:
                    person_thumbnail = downloadUtils.imageUrl(person_id,
                                                              "Primary",
                                                              0,
                                                              400,
                                                              400,
                                                              person_tag,
                                                              server=server)

                if kodi_version > 17:
                    list_item = xbmcgui.ListItem(label=person_name,
                                                 iconImage=person_thumbnail,
                                                 offscreen=True)
                else:
                    list_item = xbmcgui.ListItem(label=person_name,
                                                 iconImage=person_thumbnail)

                if person_thumbnail:
                    artLinks = {}
                    artLinks["thumb"] = person_thumbnail
                    artLinks["poster"] = person_thumbnail
                    list_item.setArt(artLinks)

                labels = {}
                labels["mediatype"] = "artist"
                list_item.setInfo(type="music", infoLabels=labels)

                if person_role:
                    list_item.setLabel2(person_role)

                itemTupple = ("", list_item, False)
                listItems.append(itemTupple)

    xbmcplugin.setContent(handle, 'artists')
    xbmcplugin.addDirectoryItems(handle, listItems)
    xbmcplugin.endOfDirectory(handle, cacheToDisc=False)
Пример #9
0
def playFile(play_info, monitor):

    id = play_info.get("item_id")

    # if this is a list of items them add them all to the play list
    if isinstance(id, list):
        return playListOfItems(id, monitor)

    auto_resume = play_info.get("auto_resume", "-1")
    force_transcode = play_info.get("force_transcode", False)
    media_source_id = play_info.get("media_source_id", "")
    use_default = play_info.get("use_default", False)

    log.debug("playFile id({0}) resume({1}) force_transcode({2})", id, auto_resume, force_transcode)

    settings = xbmcaddon.Addon()
    addon_path = settings.getAddonInfo('path')
    force_auto_resume = settings.getSetting('forceAutoResume') == 'true'
    jump_back_amount = int(settings.getSetting("jump_back_amount"))

    server = download_utils.getServer()

    url = "{server}/emby/Users/{userid}/Items/" + id + "?format=json"
    data_manager = DataManager()
    result = data_manager.GetContent(url)
    log.debug("Playfile item: {0}", result)

    if result is None:
        log.debug("Playfile item was None, so can not play!")
        return

    # if this is a season, tv show or album then play all items in that parent
    if result.get("Type") == "Season" or result.get("Type") == "MusicAlbum":
        log.debug("PlayAllFiles for parent item id: {0}", id)
        url = ('{server}/emby/Users/{userid}/items' +
               '?ParentId=' + id +
               '&Fields=MediaSources' +
               '&format=json')
        result = data_manager.GetContent(url)
        log.debug("PlayAllFiles items: {0}", result)

        # process each item
        items = result["Items"]
        if items is None:
            items = []
        return playAllFiles(items, monitor)

    # select the media source to use
    media_sources = result.get('MediaSources')
    selected_media_source = None

    if media_sources is None or len(media_sources) == 0:
        log.debug("Play Failed! There is no MediaSources data!")
        return

    elif len(media_sources) == 1:
        selected_media_source = media_sources[0]

    elif media_source_id != "":
        for source in media_sources:
            if source.get("Id", "na") == media_source_id:
                selected_media_source = source
                break

    elif len(media_sources) > 1:
        sourceNames = []
        for source in media_sources:
            sourceNames.append(source.get("Name", "na"))

        dialog = xbmcgui.Dialog()
        resp = dialog.select(i18n('select_source'), sourceNames)
        if resp > -1:
            selected_media_source = media_sources[resp]
        else:
            log.debug("Play Aborted, user did not select a MediaSource")
            return

    if selected_media_source is None:
        log.debug("Play Aborted, MediaSource was None")
        return

    seekTime = 0
    auto_resume = int(auto_resume)

    # process user data for resume points
    if auto_resume != -1:
        seekTime = (auto_resume / 1000) / 10000

    elif force_auto_resume:
        userData = result.get("UserData")
        reasonableTicks = int(userData.get("PlaybackPositionTicks")) / 1000
        seekTime = reasonableTicks / 10000

    else:
        userData = result.get("UserData")
        if userData.get("PlaybackPositionTicks") != 0:

            reasonableTicks = int(userData.get("PlaybackPositionTicks")) / 1000
            seekTime = reasonableTicks / 10000
            displayTime = str(timedelta(seconds=seekTime))

            resumeDialog = ResumeDialog("ResumeDialog.xml", addon_path, "default", "720p")
            resumeDialog.setResumeTime("Resume from " + displayTime)
            resumeDialog.doModal()
            resume_result = resumeDialog.getResumeAction()
            del resumeDialog
            log.debug("Resume Dialog Result: {0}", resume_result)

            # check system settings for play action
            # if prompt is set ask to set it to auto resume
            params = {"setting": "myvideos.selectaction"}
            setting_result = json_rpc('Settings.getSettingValue').execute(params)
            log.debug("Current Setting (myvideos.selectaction): {0}", setting_result)
            current_value = setting_result.get("result", None)
            if current_value is not None:
                current_value = current_value.get("value", -1)
            if current_value not in (2,3):
                return_value = xbmcgui.Dialog().yesno(i18n('extra_prompt'), i18n('turn_on_auto_resume?'))
                if return_value:
                    params = {"setting": "myvideos.selectaction", "value": 2}
                    json_rpc_result = json_rpc('Settings.setSettingValue').execute(params)
                    log.debug("Save Setting (myvideos.selectaction): {0}", json_rpc_result)

            if resume_result == 1:
                seekTime = 0
            elif resume_result == -1:
                return

    listitem_props = []
    playback_type = "0"
    playurl = None
    play_session_id = id_generator()
    log.debug("play_session_id: {0}", play_session_id)

    # check if strm file, path will contain contain strm contents
    if selected_media_source.get('Container') == 'strm':
        playurl, listitem_props = PlayUtils().getStrmDetails(selected_media_source)
        if playurl is None:
            return

    if not playurl:
        playurl, playback_type = PlayUtils().getPlayUrl(id, selected_media_source, force_transcode, play_session_id)

    log.debug("Play URL: {0} ListItem Properties: {1}", playurl, listitem_props)

    playback_type_string = "DirectPlay"
    if playback_type == "2":
        playback_type_string = "Transcode"
    elif playback_type == "1":
        playback_type_string = "DirectStream"

    # add the playback type into the overview
    if result.get("Overview", None) is not None:
        result["Overview"] = playback_type_string + "\n" + result.get("Overview")
    else:
        result["Overview"] = playback_type_string

    # add title decoration is needed
    item_title = result.get("Name", i18n('missing_title'))
    list_item = xbmcgui.ListItem(label=item_title)

    if playback_type == "2": # if transcoding then prompt for audio and subtitle
        playurl = audioSubsPref(playurl, list_item, selected_media_source, id, use_default)
        log.debug("New playurl for transcoding: {0}", playurl)

    elif playback_type == "1": # for direct stream add any streamable subtitles
        externalSubs(selected_media_source, list_item, id)

    # add playurl and data to the monitor
    data = {}
    data["item_id"] = id
    data["playback_type"] = playback_type_string
    data["play_session_id"] = play_session_id
    data["play_action_type"] = "play"
    monitor.played_information[playurl] = data
    log.debug("Add to played_information: {0}", monitor.played_information)

    list_item.setPath(playurl)
    list_item = setListItemProps(id, list_item, result, server, listitem_props, item_title)

    playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    playlist.clear()
    playlist.add(playurl, list_item)
    xbmc.Player().play(playlist)

    send_next_episode_details(result)

    if seekTime == 0:
        return

    count = 0
    while not xbmc.Player().isPlaying():
        log.debug("Not playing yet...sleep for 1 sec")
        count = count + 1
        if count >= 10:
            return
        else:
            xbmc.Monitor().waitForAbort(1)

    seekTime = seekTime - jump_back_amount

    target_seek = (seekTime - 5)
    current_position = 0
    while current_position < target_seek:
        # xbmc.Player().pause()
        xbmc.sleep(100)
        xbmc.Player().seekTime(seekTime)
        xbmc.sleep(100)
        # xbmc.Player().play()
        current_position = xbmc.Player().getTime()
        log.debug("Playback_Start_Seek target:{0} current:{1}", target_seek, current_position)
def showServerSessions():
    log.debug("showServerSessions Called")

    handle = int(sys.argv[1])
    downloadUtils = DownloadUtils()
    data_manager = DataManager()

    url = "{server}/emby/Users/{userid}"
    results = data_manager.GetContent(url)

    is_admin = results.get("Policy", {}).get("IsAdministrator", False)
    if not is_admin:
        xbmcplugin.endOfDirectory(handle, cacheToDisc=False)
        return

    url = "{server}/emby/Sessions"
    results = data_manager.GetContent(url)
    log.debug("session_info: {0}", results)

    if results is None:
        return

    list_items = []
    for session in results:
        device_name = session.get("DeviceName", "na")
        user_name = session.get("UserName", "na")
        client_name = session.get("Client", "na")
        client_version = session.get("ApplicationVersion", "na")

        play_state = session.get("PlayState", None)
        now_playing = session.get("NowPlayingItem", None)
        transcoding_info = session.get("TranscodingInfo", None)

        session_info = user_name + " - " + client_name
        user_session_details = ""

        percenatge_played = 0
        position_ticks = 0
        runtime = 0
        play_method = "na"

        if play_state is not None:
            position_ticks = play_state.get("PositionTicks", 0)
            play_method = play_state.get("PlayMethod", "na")

        art = {}
        if now_playing:
            server = downloadUtils.getServer()
            art = getArt(now_playing, server)

            runtime = now_playing.get("RunTimeTicks", 0)
            if position_ticks > 0 and runtime > 0:
                percenatge_played = (position_ticks / float(runtime)) * 100.0
                percenatge_played = int(percenatge_played)

            session_info += " (" + now_playing.get(
                "Name", "na") + " " + str(percenatge_played) + "%)"
            user_session_details += now_playing.get(
                "Name", "na") + " " + str(percenatge_played) + "%" + "\n"

        else:
            session_info += " (idle)"
            user_session_details += "Idle" + "\n"

        transcoding_details = ""
        if transcoding_info:
            if not transcoding_info.get("IsVideoDirect", None):
                transcoding_details += "Video:" + transcoding_info.get(
                    "VideoCodec", "") + ":" + str(
                        transcoding_info.get("Width", 0)) + "x" + str(
                            transcoding_info.get("Height", 0)) + "\n"
            else:
                transcoding_details += "Video:direct\n"

            if not transcoding_info.get("IsAudioDirect", None):
                transcoding_details += "Audio:" + transcoding_info.get(
                    "AudioCodec", "") + ":" + str(
                        transcoding_info.get("AudioChannels", 0)) + "\n"
            else:
                transcoding_details += "Audio:direct\n"

            transcoding_details += "Bitrate:" + str(
                transcoding_info.get("Bitrate", 0)) + "\n"

        list_item = xbmcgui.ListItem(label=session_info)
        list_item.setArt(art)

        user_session_details += device_name + "(" + client_version + ")\n"
        user_session_details += client_name + "\n"
        user_session_details += play_method + "\n"
        user_session_details += transcoding_details + "\n"

        info_labels = {}
        info_labels["duration"] = str(runtime / 10000000)
        info_labels["mediatype"] = "movie"
        info_labels["plot"] = user_session_details
        list_item.setInfo('video', info_labels)

        list_item.setProperty('TotalTime', str(runtime / 10000000))
        list_item.setProperty('ResumeTime', str(position_ticks / 10000000))
        list_item.setProperty("complete_percentage", str(percenatge_played))

        item_tuple = ("", list_item, False)
        list_items.append(item_tuple)

    xbmcplugin.setContent(handle, "movies")
    xbmcplugin.addDirectoryItems(handle, list_items)
    xbmcplugin.endOfDirectory(handle, cacheToDisc=False)
Пример #11
0
def getCollections():
    log.debug("== ENTER: getCollections ==")

    server = downloadUtils.getServer()
    if server is None:
        return []

    userid = downloadUtils.getUserId()

    if userid == None or len(userid) == 0:
        log.debug("No userid so returning []")
        return []

    data_manager = DataManager()
    result = data_manager.GetContent(
        "{server}/emby/Users/{userid}/Items/Root?format=json")
    if result is None:
        return []

    parentid = result.get("Id")
    log.debug("parentid: {0}", parentid)

    htmlpath = "{server}/emby/Users/{userid}/items?ParentId=" + parentid + "&Sortby=SortName&format=json"
    result = data_manager.GetContent(htmlpath)

    if result is not None:
        result = result.get("Items")
    else:
        result = []

    collections = []

    for item in result:
        item_name = item.get("Name")

        collection_type = item.get('CollectionType', None)
        log.debug("CollectionType: {0}", collection_type)
        log.debug("Title: {0}", item_name)

        if collection_type == "music":
            item_data = {}
            item_data['title'] = item_name + i18n('_all_albums')
            item_data['thumbnail'] = downloadUtils.getArtwork(item,
                                                              "Primary",
                                                              server=server)
            item_data['media_type'] = 'MusicAlbums'
            item_data['path'] = (
                '{server}/emby/Users/{userid}/Items' + '?Recursive=true' +
                '&ParentId=' + item.get("Id") +
                '&IncludeItemTypes=MusicAlbum' + '&ImageTypeLimit=1' +
                '&EnableImageTypes=Primary,Backdrop,Banner,Thumb' +
                '&format=json')
            collections.append(item_data)

            item_data = {}
            item_data['title'] = item_name + i18n('_all_artists')
            item_data['thumbnail'] = downloadUtils.getArtwork(item,
                                                              "Primary",
                                                              server=server)
            item_data['media_type'] = 'MusicArtists'
            item_data['path'] = (
                '{server}/emby/Artists/AlbumArtists' + '?Recursive=true' +
                '&ParentId=' + item.get("Id") + '&ImageTypeLimit=1' +
                '&EnableImageTypes=Primary,Backdrop,Banner,Thumb' +
                '&format=json')
            collections.append(item_data)

        if collection_type in ["movies", "boxsets"]:
            collections.append({
                'title':
                item_name,
                'thumbnail':
                downloadUtils.getArtwork(item, "Primary", server=server),
                'path': ('{server}/emby/Users/{userid}/Items' + '?ParentId=' +
                         item.get("Id") + '&IsVirtualUnaired=false' +
                         '&CollapseBoxSetItems=true' + '&Recursive=true' +
                         '&IsMissing=False' + '&Fields={field_filters}' +
                         '&ImageTypeLimit=1' + '&format=json'),
                'media_type':
                collection_type
            })

        if collection_type == "tvshows":
            collections.append({
                'title':
                item_name,
                'thumbnail':
                downloadUtils.getArtwork(item, "Primary", server=server),
                'path': ('{server}/emby/Users/{userid}/Items' + '?ParentId=' +
                         item.get("Id") + '&IsVirtualUnaired=false' +
                         '&IsMissing=False' + '&Fields={field_filters}' +
                         '&ImageTypeLimit=1' + '&format=json'),
                'media_type':
                collection_type
            })
            collections.append({
                'title':
                item_name + i18n('_unwatched'),
                'thumbnail':
                downloadUtils.getArtwork(item, "Primary", server=server),
                'path': ('{server}/emby/Users/{userid}/Items' + '?ParentId=' +
                         item.get("Id") + '&IsVirtualUnaired=false' +
                         '&IsMissing=False' + '&Fields={field_filters}' +
                         '&Filters=IsUnplayed' + '&Recursive=true' +
                         '&IncludeItemTypes=Series' + '&ImageTypeLimit=1' +
                         '&format=json'),
                'media_type':
                'tvshows'
            })
            collections.append({
                'title':
                item_name + i18n('_in_progress'),
                'thumbnail':
                downloadUtils.getArtwork(item, "Primary", server=server),
                'path': ('{server}/emby/Users/{userid}/Items' + '?ParentId=' +
                         item.get("Id") + '&Limit={ItemLimit}' +
                         '&IsVirtualUnaired=false' + '&IsMissing=False' +
                         '&Fields={field_filters}' + '&Filters=IsResumable' +
                         '&Recursive=true' + '&IncludeItemTypes=Episode' +
                         '&ImageTypeLimit=1' + '&format=json'),
                'media_type':
                'Episodes',
                'name_format':
                'Episode|episode_name_format'
            })
            collections.append({
                'title':
                item_name + i18n('_latest'),
                'thumbnail':
                downloadUtils.getArtwork(item, "Primary", server=server),
                'path': ('{server}/emby/Users/{userid}/Items/Latest' +
                         '?ParentId=' + item.get("Id") + '&Limit={ItemLimit}' +
                         '&IsVirtualUnaired=false' + '&IsMissing=False' +
                         '&Fields={field_filters}' + '&SortBy=DateCreated' +
                         '&SortOrder=Descending' + '&Filters=IsUnplayed' +
                         '&Recursive=true' + '&IncludeItemTypes=Episode' +
                         '&ImageTypeLimit=1' + '&format=json'),
                'media_type':
                'Episodes',
                'name_format':
                'Episode|episode_name_format'
            })
            collections.append({
                'title':
                item_name + i18n('_recently_added'),
                'thumbnail':
                downloadUtils.getArtwork(item, "Primary", server=server),
                'path': ('{server}/emby/Users/{userid}/Items' + '?ParentId=' +
                         item.get("Id") + '&Limit={ItemLimit}' +
                         '&IsVirtualUnaired=false' + '&IsMissing=False' +
                         '&Fields={field_filters}' + '&SortBy=DateCreated' +
                         '&SortOrder=Descending' +
                         '&Filters={IsUnplayed,}IsNotFolder' +
                         '&Recursive=true' + '&IncludeItemTypes=Episode' +
                         '&ImageTypeLimit=1' + '&format=json'),
                'media_type':
                'Episodes',
                'name_format':
                'Episode|episode_name_format'
            })
            collections.append({
                'title':
                item_name + i18n('_next_up'),
                'thumbnail':
                downloadUtils.getArtwork(item, "Primary", server=server),
                'path': ('{server}/emby/Shows/NextUp/?Userid={userid}' +
                         '&ParentId=' + item.get("Id") + '&Limit={ItemLimit}' +
                         '&Recursive=true' + '&Fields={field_filters}' +
                         '&Filters=IsUnplayed,IsNotFolder' +
                         '&IsVirtualUnaired=false' + '&IsMissing=False' +
                         '&IncludeItemTypes=Episode' + '&ImageTypeLimit=1' +
                         '&format=json'),
                'media_type':
                'Episodes',
                'name_format':
                'Episode|episode_name_format'
            })
            collections.append({
                'title':
                item_name + i18n('_genres'),
                'item_type':
                'plugin_link',
                'thumbnail':
                downloadUtils.getArtwork(item, "Primary", server=server),
                'path':
                'plugin://plugin.video.embycon/?mode=GENRES&item_type=tvshow&parent_id='
                + item.get("Id"),
                'media_type':
                'tvshows'
            })

        if collection_type == "movies":
            collections.append({
                'title':
                item_name + i18n('_unwatched'),
                'thumbnail':
                downloadUtils.getArtwork(item, "Primary", server=server),
                'path':
                ('{server}/emby/Users/{userid}/Items' + '?ParentId=' +
                 item.get("Id") + '&IsVirtualUnaired=false' +
                 '&IsMissing=False' + '&Fields={field_filters}' +
                 '&Filters=IsUnplayed' + '&ImageTypeLimit=1' + '&format=json'),
                'media_type':
                collection_type
            })
            collections.append({
                'title':
                item_name + i18n('_in_progress'),
                'thumbnail':
                downloadUtils.getArtwork(item, "Primary", server=server),
                'path': ('{server}/emby/Users/{userid}/Items' + '?ParentId=' +
                         item.get("Id") + '&Limit={ItemLimit}' +
                         '&IsVirtualUnaired=false' + '&IsMissing=False' +
                         '&Fields={field_filters}' + '&Filters=IsResumable' +
                         '&ImageTypeLimit=1' + '&format=json'),
                'media_type':
                collection_type
            })
            collections.append({
                'title':
                item_name + i18n('_recently_added'),
                'thumbnail':
                downloadUtils.getArtwork(item, "Primary", server=server),
                'path': ('{server}/emby/Users/{userid}/Items' + '?ParentId=' +
                         item.get("Id") + '&Limit={ItemLimit}' +
                         '&IsVirtualUnaired=false' + '&IsMissing=False' +
                         '&Fields={field_filters}' + '&SortBy=DateCreated' +
                         '&SortOrder=Descending' +
                         '&Filters={IsUnplayed,}IsNotFolder' +
                         '&ImageTypeLimit=1' + '&format=json'),
                'media_type':
                collection_type
            })
            collections.append({
                'title':
                item_name + i18n('_genres'),
                'item_type':
                'plugin_link',
                'thumbnail':
                downloadUtils.getArtwork(item, "Primary", server=server),
                'path':
                'plugin://plugin.video.embycon/?mode=GENRES&item_type=movie&parent_id='
                + item.get("Id"),
                'media_type':
                collection_type
            })

    # Add standard nodes
    item_data = {}
    item_data['title'] = i18n('movies_all')
    item_data['media_type'] = 'Movies'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Fields={field_filters}' + '&Recursive=true' +
                         '&IncludeItemTypes=Movie' + '&ImageTypeLimit=1' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('movies_unwatched')
    item_data['media_type'] = 'Movies'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Recursive=true' + '&Fields={field_filters}' +
                         '&Filters=IsUnplayed' + '&IncludeItemTypes=Movie' +
                         '&ImageTypeLimit=1' + '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('movies_in_progress')
    item_data['media_type'] = 'Movies'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Limit={ItemLimit}' + '&Recursive=true' +
                         '&Fields={field_filters}' + '&Filters=IsResumable' +
                         '&IncludeItemTypes=Movie' + '&ImageTypeLimit=1' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('movies_recently_added')
    item_data['media_type'] = 'Movies'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Limit={ItemLimit}' + '&Recursive=true' +
                         '&SortBy=DateCreated' + '&Fields={field_filters}' +
                         '&SortOrder=Descending' +
                         '&Filters={IsUnplayed,}IsNotFolder' +
                         '&IncludeItemTypes=Movie' + '&ImageTypeLimit=1' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('movies_favorites')
    item_data['media_type'] = 'Movies'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Fields={field_filters}' + '&Recursive=true' +
                         '&Filters=IsFavorite' + '&IncludeItemTypes=Movie' +
                         '&ImageTypeLimit=1' + '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('movies_boxsets')
    item_data['media_type'] = 'BoxSets'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Recursive=true' + '&Fields={field_filters}' +
                         '&IncludeItemTypes=BoxSet' + '&ImageTypeLimit=1' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('tvshows_all')
    item_data['media_type'] = 'tvshows'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Fields={field_filters}' + '&Recursive=true' +
                         '&IncludeItemTypes=Series' + '&ImageTypeLimit=1' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('tvshows_unwatched')
    item_data['media_type'] = 'tvshows'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Fields={field_filters}' + '&Recursive=true' +
                         '&Filters=IsUnplayed' + '&IncludeItemTypes=Series' +
                         '&ImageTypeLimit=1' + '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('tvshows_favorites')
    item_data['media_type'] = 'tvshows'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Fields={field_filters}' + '&Recursive=true' +
                         '&Filters=IsFavorite' + '&IncludeItemTypes=Series' +
                         '&ImageTypeLimit=1' + '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('tvshows_latest')
    item_data['media_type'] = 'Episodes'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items/Latest' +
                         '?Limit={ItemLimit}' + '&Recursive=true' +
                         '&GroupItems=true' + '&SortBy=DateCreated' +
                         '&Fields={field_filters}' + '&SortOrder=Descending' +
                         '&Filters={IsUnplayed}' + '&IsVirtualUnaired=false' +
                         '&IsMissing=False' + '&IncludeItemTypes=Episode' +
                         '&ImageTypeLimit=1' + '&format=json')
    item_data['name_format'] = 'Episode|episode_name_format'
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('episodes_in_progress')
    item_data['media_type'] = 'Episodes'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Limit={ItemLimit}' + '&Recursive=true' +
                         '&Fields={field_filters}' + '&Filters=IsResumable' +
                         '&IncludeItemTypes=Episode' + '&ImageTypeLimit=1' +
                         '&format=json')
    item_data['name_format'] = 'Episode|episode_name_format'
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('episodes_recently_added')
    item_data['media_type'] = 'Episodes'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Limit={ItemLimit}' + '&Recursive=true' +
                         '&SortBy=DateCreated' + '&Fields={field_filters}' +
                         '&SortOrder=Descending' +
                         '&Filters={IsUnplayed,}IsNotFolder' +
                         '&IsVirtualUnaired=false' + '&IsMissing=False' +
                         '&IncludeItemTypes=Episode' + '&ImageTypeLimit=1' +
                         '&format=json')
    item_data['name_format'] = 'Episode|episode_name_format'
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('episodes_up_next')
    item_data['media_type'] = 'Episodes'
    item_data['path'] = ('{server}/emby/Shows/NextUp/?Userid={userid}' +
                         '&Limit={ItemLimit}' + '&Recursive=true' +
                         '&Fields={field_filters}' +
                         '&Filters=IsUnplayed,IsNotFolder' +
                         '&IsVirtualUnaired=false' + '&IsMissing=False' +
                         '&IncludeItemTypes=Episode' + '&ImageTypeLimit=1' +
                         '&format=json')
    item_data['name_format'] = 'Episode|episode_name_format'
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('upcoming_tv')
    item_data['media_type'] = 'Episodes'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Recursive=true' + '&SortBy=PremiereDate' +
                         '&Fields={field_filters}' + '&SortOrder=Ascending' +
                         '&IsVirtualUnaired=true' + '&IsNotFolder' +
                         '&IncludeItemTypes=Episode' + '&ImageTypeLimit=1' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('music_all_albums')
    item_data['media_type'] = 'MusicAlbums'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Recursive=true' + '&IncludeItemTypes=MusicAlbum' +
                         '&ImageTypeLimit=1' +
                         '&EnableImageTypes=Primary,Backdrop,Banner,Thumb' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = i18n('music_all_artists')
    item_data['media_type'] = 'MusicArtists'
    item_data['path'] = ('{server}/emby/Artists/AlbumArtists' +
                         '?Recursive=true' + '&ImageTypeLimit=1' +
                         '&EnableImageTypes=Primary,Backdrop,Banner,Thumb' +
                         '&format=json')
    collections.append(item_data)

    return collections
Пример #12
0
def showGenreList(params):
    log.debug("showGenreList: {0}", params)

    server = downloadUtils.getServer()
    if server is None:
        return

    parent_id = params.get("parent_id")
    item_type = params.get("item_type")

    kodi_type = "Movies"
    emby_type = "Movie"
    if item_type is not None and item_type == "tvshow":
        emby_type = "Series"
        kodi_type = "tvshows"

    url = ("{server}/emby/Genres?" + "SortBy=SortName" +
           "&SortOrder=Ascending" + "&IncludeItemTypes=" + emby_type +
           "&Recursive=true" + "&UserId={userid}")

    if parent_id is not None:
        url += "&parentid=" + parent_id

    data_manager = DataManager()
    result = data_manager.GetContent(url)

    if result is not None:
        result = result.get("Items")
    else:
        result = []

    collections = []
    xbmcplugin.setContent(int(sys.argv[1]), 'genres')

    for genre in result:
        item_data = {}
        item_data['title'] = genre.get("Name")
        item_data['media_type'] = kodi_type
        item_data['thumbnail'] = downloadUtils.getArtwork(genre,
                                                          "Primary",
                                                          server=server)

        url = ("{server}/emby/Users/{userid}/Items" +
               "?Fields={field_filters}" + "&Recursive=true" + "&GenreIds=" +
               genre.get("Id") + "&IncludeItemTypes=" + emby_type +
               "&ImageTypeLimit=1")

        if parent_id is not None:
            url += "&parentid=" + parent_id

        item_data['path'] = url
        collections.append(item_data)

    for collection in collections:
        url = sys.argv[0] + ("?url=" + urllib.quote(collection['path']) +
                             "&mode=GET_CONTENT" + "&media_type=" +
                             collection["media_type"])
        log.debug("addMenuDirectoryItem: {0} - {1} - {2}",
                  collection.get('title'), url, collection.get("thumbnail"))
        addMenuDirectoryItem(collection.get('title', i18n('unknown')),
                             url,
                             thumbnail=collection.get("thumbnail"))

    xbmcplugin.endOfDirectory(int(sys.argv[1]))
Пример #13
0
def cache_artwork():
    log.debug("cache_artwork")

    xbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc=False)

    # is the web server enabled
    web_query = {"setting": "services.webserver"}
    result = json_rpc('Settings.GetSettingValue').execute(web_query)
    xbmc_webserver_enabled = result['result']['value']
    if not xbmc_webserver_enabled:
        xbmcgui.Dialog().ok(i18n('notice'), i18n('http_control'))
        return

    # get the port
    web_port = {"setting": "services.webserverport"}
    result = json_rpc('Settings.GetSettingValue').execute(web_port)
    xbmc_port = result['result']['value']
    log.debug("xbmc_port: {0}", xbmc_port)

    # get the user
    web_user = {"setting": "services.webserverusername"}
    result = json_rpc('Settings.GetSettingValue').execute(web_user)
    xbmc_username = result['result']['value']
    log.debug("xbmc_username: {0}", xbmc_username)

    # get the password
    web_pass = {"setting": "services.webserverpassword"}
    result = json_rpc('Settings.GetSettingValue').execute(web_pass)
    xbmc_password = result['result']['value']

    # ask to delete all textures
    question_result = xbmcgui.Dialog().yesno(i18n('delete'), i18n('delete_existing'))
    if question_result:
        pdialog = xbmcgui.DialogProgress()
        pdialog.create(i18n('deleting_textures'), "")
        index = 0

        json_result = json_rpc('Textures.GetTextures').execute()
        textures = json_result.get("result", {}).get("textures", [])
        log.debug("texture ids: {0}", textures)
        total = len(textures)
        for texture in textures:
            texture_id = texture["textureid"]
            params = {"textureid": int(texture_id)}
            json_result = json_rpc('Textures.RemoveTexture').execute(params)
            percentage = int((float(index) / float(total)) * 100)
            message = "%s of %s" % (index, total)
            pdialog.update(percentage, "%s" % (message))

            index += 1
            if pdialog.iscanceled():
                break

        del textures
        del pdialog

    question_result = xbmcgui.Dialog().yesno(i18n('cache_all_textures_title'), i18n('cache_all_textures'))
    if not question_result:
        return

    params = {"properties": ["url"]}
    json_result = json_rpc('Textures.GetTextures').execute(params)
    textures = json_result.get("result", {}).get("textures", [])

    texture_urls = set()
    for texture in textures:
        url = texture.get("url")
        url = urllib.unquote(url)
        url = url.replace("image://", "")
        url = url[0:-1]
        texture_urls.add(url)

    del textures
    del json_result

    url = ('{server}/emby/Users/{userid}/Items?' +
        '&Recursive=true' +
        '&IncludeItemTypes=Movie,Series,Episode,BoxSet' +
        '&ImageTypeLimit=1' +
        '&format=json')

    data_manager = DataManager()
    results = data_manager.GetContent(url)
    if results is None:
        results = []

    if isinstance(results, dict):
        results = results.get("Items")

    server = downloadUtils.getServer()
    missing_texture_urls = set()

    image_types = ["thumb", "poster", "banner", "clearlogo", "tvshow.poster", "tvshow.banner", "tvshow.landscape"]
    for item in results:
        art = getArt(item, server)
        for image_type in image_types:
            image_url = art[image_type]
            if image_url not in texture_urls and not image_url.endswith("&Tag=") and len(image_url) > 0:
                missing_texture_urls.add(image_url)

    log.debug("texture_urls: {0}", texture_urls)
    log.debug("missing_texture_urls: {0}", missing_texture_urls)
    log.debug("Number of existing textures: {0}", len(texture_urls))
    log.debug("Number of missing textures: {0}", len(missing_texture_urls))

    kodi_http_server = "localhost:" + str(xbmc_port)
    headers = {}
    if xbmc_password:
        auth = "%s:%s" % (xbmc_username, xbmc_password)
        headers = {'Authorization': 'Basic %s' % base64.b64encode(auth)}

    pdialog = xbmcgui.DialogProgress()
    pdialog.create(i18n('caching_textures'), "")
    total = len(missing_texture_urls)
    index = 1

    count_done = 0
    for get_url in missing_texture_urls:
        log.debug("texture_url: {0}", get_url)
        url = double_urlencode(get_url)
        kodi_texture_url = ("/image/image://%s" % url)
        log.debug("kodi_texture_url: {0}", kodi_texture_url)

        percentage = int((float(index) / float(total)) * 100)
        message = "%s of %s" % (index, total)
        pdialog.update(percentage, "%s" % (message))

        conn = httplib.HTTPConnection(kodi_http_server, timeout=20)
        conn.request(method="GET", url=kodi_texture_url, headers=headers)
        data = conn.getresponse()
        if data.status == 200:
            count_done += 1
        log.debug("Get Image Result: {0}", data.status)

        index += 1
        if pdialog.iscanceled():
            break

    pdialog.close()
    del pdialog

    report_text = i18n('existing_textures') + str(len(texture_urls)) + "\n"
    report_text += i18n('missing_textures') + str(len(missing_texture_urls)) + "\n"
    report_text += i18n('loaded_textures') + str(count_done)
    xbmcgui.Dialog().ok(i18n('done'), report_text)
def getCollections():
    log.debug("== ENTER: getCollections ==")

    server = downloadUtils.getServer()
    if server is None:
        return []

    userid = downloadUtils.getUserId()

    if userid is None or len(userid) == 0:
        log.debug("No userid so returning []")
        return []

    data_manager = DataManager()
    result = data_manager.GetContent("{server}/emby/Users/{userid}/Items/Root?format=json")
    if result is None:
        return []

    parentid = result.get("Id")
    log.debug("parentid: {0}", parentid)

    htmlpath = "{server}/emby/Users/{userid}/Views?format=json"
    # htmlpath = "{server}/emby/Users/{userid}/items?ParentId=" + parentid + "&Sortby=SortName&format=json"
    result = data_manager.GetContent(htmlpath)

    if result is not None:
        result = result.get("Items")
    else:
        result = []

    collections = []

    settings = xbmcaddon.Addon()
    group_movies = settings.getSetting('group_movies') == "true"
    show_x_filtered_items = settings.getSetting("show_x_filtered_items")

    for item in result:
        item_name = item.get("Name")

        collection_type = item.get('CollectionType', None)
        type = item.get('Type', None)
        log.debug("CollectionType: {0}", collection_type)
        log.debug("Title: {0}", item_name)
        art = getArt(item=item, server=server)
        art['landscape'] = downloadUtils.getArtwork(item, "Primary", server=server)

        if collection_type == "music":
            item_data = {}
            item_data['title'] = item_name + string_load(30320)
            item_data['art'] = art
            item_data['media_type'] = 'MusicAlbums'
            item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                                 '?Recursive=true' +
                                 '&ParentId=' + item.get("Id") +
                                 '&IncludeItemTypes=MusicAlbum' +
                                 '&ImageTypeLimit=1' +
                                 '&EnableImageTypes=Primary,Backdrop,Banner,Thumb' +
                                 '&SortBy=Name' +
                                 '&SortOrder=Ascending' +
                                 '&format=json')
            collections.append(item_data)

            item_data = {}
            item_data['title'] = item_name + string_load(30268) + " (" + show_x_filtered_items + ")"
            item_data['art'] = art
            item_data['media_type'] = 'MusicAlbums'
            item_data['path'] = ('{server}/emby/Users/{userid}/Items/Latest' +
                                 '?IncludeItemTypes=Audio' +
                                 '&ParentId=' + item.get("Id") +
                                 '&ImageTypeLimit=1' +
                                 '&Limit={ItemLimit}' +
                                 '&EnableImageTypes=Primary,Backdrop,Banner,Thumb' +
                                 '&SortBy=Name' +
                                 '&SortOrder=Ascending' +
                                 '&format=json')
            collections.append(item_data)

            item_data = {}
            item_data['title'] = item_name + string_load(30349) + " (" + show_x_filtered_items + ")"
            item_data['art'] = art
            item_data['media_type'] = 'MusicAlbum'
            item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                                 '?SortBy=DatePlayed' +
                                 '&SortOrder=Descending' +
                                 '&IncludeItemTypes=Audio' +
                                 '&Limit={ItemLimit}' +
                                 '&Recursive=true' +
                                 '&ParentId=' + item.get("Id") +
                                 '&ImageTypeLimit=1' +
                                 '&EnableImageTypes=Primary,Backdrop,Banner,Thumb' +
                                 '&Filters=IsPlayed' +
                                 '&format=json')
            collections.append(item_data)

            item_data = {}
            item_data['title'] = item_name + string_load(30353) + " (" + show_x_filtered_items + ")"
            item_data['art'] = art
            item_data['media_type'] = 'MusicAlbum'
            item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                                 '?SortBy=PlayCount' +
                                 '&SortOrder=Descending' +
                                 '&IncludeItemTypes=Audio' +
                                 '&Limit={ItemLimit}' +
                                 '&Recursive=true' +
                                 '&ParentId=' + item.get("Id") +
                                 '&ImageTypeLimit=1' +
                                 '&EnableImageTypes=Primary,Backdrop,Banner,Thumb' +
                                 '&Filters=IsPlayed' +
                                 '&format=json')
            collections.append(item_data)

            item_data = {}
            item_data['title'] = item_name + string_load(30321)
            item_data['art'] = art
            item_data['media_type'] = 'MusicArtists'
            item_data['path'] = ('{server}/emby/Artists/AlbumArtists' +
                                 '?Recursive=true' +
                                 '&ParentId=' + item.get("Id") +
                                 '&ImageTypeLimit=1' +
                                 '&EnableImageTypes=Primary,Backdrop,Banner,Thumb' +
                                 '&SortBy=Name' +
                                 '&SortOrder=Ascending' +
                                 '&format=json')
            collections.append(item_data)

        if collection_type in ["livetv"]:
            collections.append({
                'title': item_name + string_load(30360),
                'art': art,
                'path': ('{server}/emby/LiveTv/Channels' +
                         '?UserId={userid}' +
                         '&Recursive=false' +
                         '&Fields={field_filters}' +
                         '&ImageTypeLimit=1' +
                         '&EnableTotalRecordCount=false' +
                         '&format=json'),
                'media_type': collection_type})

            collections.append({
                'title': item_name + string_load(30361),
                'art': art,
                'path': ('{server}/emby/LiveTv/Programs/Recommended' +
                         '?UserId={userid}' +
                         '&IsAiring=true' +
                         '&Fields=ChannelInfo,{field_filters}' +
                         '&ImageTypeLimit=1' +
                         '&EnableTotalRecordCount=false' +
                         '&format=json'),
                'media_type': collection_type})

            collections.append({
                'title': item_name + string_load(30362),
                'art': art,
                'path': ('{server}/emby/LiveTv/Recordings' +
                         '?UserId={userid}' +
                         '&Recursive=false' +
                         '&Fields={field_filters}' +
                         '&ImageTypeLimit=1' +
                         '&EnableTotalRecordCount=false' +
                         '&format=json'),
                'media_type': collection_type})

        if collection_type in ["homevideos"]:
            collections.append({
                'title': item_name,
                'art': art,
                'path': ('{server}/emby/Users/{userid}/Items' +
                         '?ParentId=' + item.get("Id") +
                         '&IsVirtualUnaired=false' +
                         '&Recursive=false' +
                         '&IsMissing=False' +
                         '&Fields={field_filters}' +
                         '&ImageTypeLimit=1' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json'),
                'media_type': collection_type})

            collections.append({
                'title': item_name + string_load(30267) + " (" + show_x_filtered_items + ")",
                'art': art,
                'use_cache': False,
                'path': ('{server}/emby/Users/{userid}/Items' +
                         '?ParentId=' + item.get("Id") +
                         '&Limit={ItemLimit}' +
                         '&SortBy=DatePlayed' +
                         '&SortOrder=Descending' +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&Fields={field_filters}' +
                         '&Filters=IsResumable' +
                         '&Recursive=true' +
                         '&ImageTypeLimit=1' +
                         '&format=json'),
                'media_type': collection_type})

            collections.append({
                'title': item_name + string_load(30268) + " (" + show_x_filtered_items + ")",
                'art': art,
                'use_cache': False,
                'path': ('{server}/emby/Users/{userid}/Items' +
                         '?ParentId=' + item.get("Id") +
                         '&CollapseBoxSetItems=false' +
                         '&GroupItemsIntoCollections=false' +
                         '&Recursive=true' +
                         '&Limit={ItemLimit}' +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&Fields={field_filters}' +
                         '&SortBy=DateCreated' +
                         '&SortOrder=Descending' +
                         '&Filters=IsUnplayed,IsNotFolder' +
                         '&IsPlayed=false' +
                         '&ImageTypeLimit=1' +
                         '&format=json'),
                'media_type': collection_type})

        if collection_type in ["boxsets"]:
            collections.append({
                'title': item_name,
                'art': art,
                'path': ('{server}/emby/Users/{userid}/Items' +
                         '?ParentId=' + item.get("Id") +
                         '&IsVirtualUnaired=false' +
                         '&IncludeItemTypes=Boxset' +
                         '&CollapseBoxSetItems=' + str(group_movies) +
                         '&GroupItemsIntoCollections=' + str(group_movies) +
                         '&Recursive=true' +
                         '&IsMissing=False' +
                         '&Fields={field_filters}' +
                         '&ImageTypeLimit=1' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json'),
                'media_type': collection_type})

        if collection_type in ["movies"]:
            collections.append({
                'title': item_name,
                'art': art,
                'path': ('{server}/emby/Users/{userid}/Items' +
                         '?ParentId=' + item.get("Id") +
                         '&IsVirtualUnaired=false' +
                         '&IncludeItemTypes=Movie' +
                         '&CollapseBoxSetItems=' + str(group_movies) +
                         '&GroupItemsIntoCollections=' + str(group_movies) +
                         '&Recursive=true' +
                         '&IsMissing=False' +
                         '&Fields={field_filters}' +
                         '&ImageTypeLimit=1' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json'),
                'media_type': collection_type})

        if collection_type == "tvshows":
            collections.append({
                'title': item_name,
                'art': art,
                'path': ('{server}/emby/Users/{userid}/Items' +
                         '?ParentId=' + item.get("Id") +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&Fields={field_filters}' +
                         '&ImageTypeLimit=1' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json'),
                'media_type': collection_type})

            collections.append({
                'title': item_name + string_load(30285),
                'art': art,
                'path': ('{server}/emby/Users/{userid}/Items' +
                         '?ParentId=' + item.get("Id") +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&Fields={field_filters}' +
                         '&Filters=IsUnplayed' +
                         '&IsPlayed=false' +
                         '&Recursive=true' +
                         '&IncludeItemTypes=Series' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&ImageTypeLimit=1' +
                         '&format=json'),
                'media_type': 'tvshows'})

            collections.append({
                'title': item_name + string_load(30267) + " (" + show_x_filtered_items + ")",
                'art': art,
                'use_cache': False,
                'path': ('{server}/emby/Users/{userid}/Items' +
                         '?ParentId=' + item.get("Id") +
                         '&Limit={ItemLimit}' +
                         '&SortBy=DatePlayed' +
                         '&SortOrder=Descending' +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&Fields={field_filters}' +
                         '&Filters=IsResumable' +
                         '&Recursive=true' +
                         '&IncludeItemTypes=Episode' +
                         '&ImageTypeLimit=1' +
                         '&format=json'),
                'media_type': 'Episodes',
                'name_format': 'Episode|episode_name_format'})

            collections.append({
                'title': item_name + string_load(30288) + " (" + show_x_filtered_items + ")",
                'art': art,
                'use_cache': False,
                'path': ('{server}/emby/Users/{userid}/Items/Latest' +
                         '?ParentId=' + item.get("Id") +
                         '&Limit={ItemLimit}' +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&Fields={field_filters}' +
                         '&SortBy=DateCreated' +
                         '&SortOrder=Descending' +
                         '&Filters=IsUnplayed' +
                         '&IsPlayed=false' +
                         '&Recursive=true' +
                         '&IncludeItemTypes=Episode' +
                         '&ImageTypeLimit=1' +
                         '&format=json'),
                'media_type': 'Episodes',
                'name_format': 'Episode|episode_name_format'})

            collections.append({
                'title': item_name + string_load(30268) + " (" + show_x_filtered_items + ")",
                'art': art,
                'use_cache': False,
                'path': ('{server}/emby/Users/{userid}/Items' +
                         '?ParentId=' + item.get("Id") +
                         '&Limit={ItemLimit}' +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&Fields={field_filters}' +
                         '&SortBy=DateCreated' +
                         '&SortOrder=Descending' +
                         '&Filters=IsUnplayed,IsNotFolder' +
                         '&IsPlayed=false' +
                         '&Recursive=true' +
                         '&IncludeItemTypes=Episode' +
                         '&ImageTypeLimit=1' +
                         '&format=json'),
                'media_type': 'Episodes',
                'name_format': 'Episode|episode_name_format'})

            collections.append({
                'title': item_name + string_load(30278) + " (" + show_x_filtered_items + ")",
                'art': art,
                'use_cache': False,
                'path': ('{server}/emby/Shows/NextUp/?Userid={userid}' +
                         '&ParentId=' + item.get("Id") +
                         '&Limit={ItemLimit}' +
                         '&Recursive=true' +
                         '&Fields={field_filters}' +
                         '&Filters=IsUnplayed,IsNotFolder' +
                         '&IsPlayed=false' +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&IncludeItemTypes=Episode' +
                         '&ImageTypeLimit=1' +
                         '&format=json'),
                'media_type': 'Episodes',
                'name_format': 'Episode|episode_name_format'})

            collections.append({
                'title': item_name + string_load(30325),
                'item_type': 'plugin_link',
                'art': art,
                'path': 'plugin://plugin.video.embycon/?mode=GENRES&item_type=tvshow&parent_id=' + item.get("Id"),
                'media_type': 'tvshows'})

        if type == "Channel":
            collections.append({
                'title': item_name,
                'art': art,
                'path': ('{server}/emby/Users/{userid}/Items' +
                         '?ParentId=' + item.get("Id") +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&Fields={field_filters}' +
                         '&ImageTypeLimit=1' +
                         '&format=json'),
                'media_type': 'files',
                'name_format': 'Episode|episode_name_format'})

        if collection_type == "movies":
            collections.append({
                'title': item_name + string_load(30285),
                'art': art,
                'path': ('{server}/emby/Users/{userid}/Items' +
                         '?ParentId=' + item.get("Id") +
                         '&IncludeItemTypes=Movie' +
                         '&CollapseBoxSetItems=false' +
                         '&GroupItemsIntoCollections=false' +
                         '&Recursive=true' +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&Fields={field_filters}' +
                         '&Filters=IsUnplayed' +
                         '&IsPlayed=false' +
                         '&ImageTypeLimit=1' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json'),
                'media_type': collection_type})

            collections.append({
                'title': item_name + string_load(30267) + " (" + show_x_filtered_items + ")",
                'art': art,
                'use_cache': False,
                'path': ('{server}/emby/Users/{userid}/Items' +
                         '?ParentId=' + item.get("Id") +
                         '&IncludeItemTypes=Movie' +
                         '&CollapseBoxSetItems=false' +
                         '&GroupItemsIntoCollections=false' +
                         '&Recursive=true' +
                         '&Limit={ItemLimit}' +
                         '&SortBy=DatePlayed' +
                         '&SortOrder=Descending' +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&Fields={field_filters}' +
                         '&Filters=IsResumable' +
                         '&ImageTypeLimit=1' +
                         '&format=json'),
                'media_type': collection_type})

            collections.append({
                'title': item_name + string_load(30268) + " (" + show_x_filtered_items + ")",
                'art': art,
                'use_cache': False,
                'path': ('{server}/emby/Users/{userid}/Items' +
                         '?ParentId=' + item.get("Id") +
                         '&IncludeItemTypes=Movie' +
                         '&CollapseBoxSetItems=false' +
                         '&GroupItemsIntoCollections=false' +
                         '&Recursive=true' +
                         '&Limit={ItemLimit}' +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&Fields={field_filters}' +
                         '&SortBy=DateCreated' +
                         '&SortOrder=Descending' +
                         '&Filters=IsUnplayed,IsNotFolder' +
                         '&IsPlayed=false' +
                         '&ImageTypeLimit=1' +
                         '&format=json'),
                'media_type': collection_type})

            collections.append({
                'title': item_name + string_load(30325),
                'item_type': 'plugin_link',
                'art': art,
                'path': 'plugin://plugin.video.embycon/?mode=GENRES&item_type=movie&parent_id=' + item.get("Id"),
                'media_type': collection_type})

            collections.append({
                'title': item_name + ' - Pages',
                'item_type': 'plugin_link',
                'art': art,
                'path': 'plugin://plugin.video.embycon/?mode=MOVIE_PAGES&parent_id=' + item.get("Id"),
                'media_type': collection_type})


    # Add standard nodes
    item_data = {}
    item_data['title'] = string_load(30256)
    item_data['media_type'] = 'Movies'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Fields={field_filters}' +
                         '&CollapseBoxSetItems=' + str(group_movies) +
                         '&GroupItemsIntoCollections=' + str(group_movies) +
                         '&Recursive=true' +
                         '&IncludeItemTypes=Movie' +
                         '&ImageTypeLimit=1' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30286)
    item_data['media_type'] = 'Movies'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Recursive=true' +
                         '&CollapseBoxSetItems=false' +
                         '&GroupItemsIntoCollections=false' +
                         '&Fields={field_filters}' +
                         '&Filters=IsUnplayed' +
                         '&IsPlayed=false' +
                         '&IncludeItemTypes=Movie' +
                         '&ImageTypeLimit=1' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30258) + " (" + show_x_filtered_items + ")"
    item_data['media_type'] = 'Movies'
    item_data['use_cache'] = False
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?CollapseBoxSetItems=false' +
                         '&Limit={ItemLimit}' +
                         '&GroupItemsIntoCollections=false' +
                         '&Recursive=true' +
                         '&Fields={field_filters}' +
                         '&SortBy=DatePlayed' +
                         '&SortOrder=Descending' +
                         '&Filters=IsResumable' +
                         '&IncludeItemTypes=Movie' +
                         '&ImageTypeLimit=1' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30257) + " (" + show_x_filtered_items + ")"
    item_data['media_type'] = 'Movies'
    item_data['use_cache'] = False
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?CollapseBoxSetItems=false' +
                         '&Limit={ItemLimit}' +
                         '&GroupItemsIntoCollections=false' +
                         '&Recursive=true' +
                         '&SortBy=DateCreated' +
                         '&Fields={field_filters}' +
                         '&SortOrder=Descending' +
                         '&Filters=IsUnplayed,IsNotFolder' +
                         '&IsPlayed=false' +
                         '&IncludeItemTypes=Movie' +
                         '&ImageTypeLimit=1' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30259)
    item_data['media_type'] = 'Movies'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Fields={field_filters}' +
                         '&CollapseBoxSetItems=false' +
                         '&GroupItemsIntoCollections=false' +
                         '&Recursive=true' +
                         '&Filters=IsFavorite' +
                         '&IncludeItemTypes=Movie' +
                         '&ImageTypeLimit=1' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30260)
    item_data['media_type'] = 'BoxSets'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Recursive=true' +
                         '&Fields={field_filters}' +
                         '&IncludeItemTypes=BoxSet' +
                         '&ImageTypeLimit=1' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30261)
    item_data['media_type'] = 'tvshows'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Fields={field_filters}' +
                         '&Recursive=true' +
                         '&IncludeItemTypes=Series' +
                         '&ImageTypeLimit=1' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30279)
    item_data['media_type'] = 'tvshows'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Fields={field_filters}' +
                         '&Recursive=true' +
                         '&Filters=IsUnplayed' +
                         '&IsPlayed=false' +
                         '&IncludeItemTypes=Series' +
                         '&ImageTypeLimit=1' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30262)
    item_data['media_type'] = 'tvshows'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Fields={field_filters}' +
                         '&Recursive=true' +
                         '&Filters=IsFavorite' +
                         '&IncludeItemTypes=Series' +
                         '&ImageTypeLimit=1' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30287) + " (" + show_x_filtered_items + ")"
    item_data['media_type'] = 'Episodes'
    item_data['use_cache'] = False
    item_data['path'] = ('{server}/emby/Users/{userid}/Items/Latest' +
                         '?GroupItems=true' +
                         '&Limit={ItemLimit}' +
                         '&Recursive=true' +
                         '&SortBy=DateCreated' +
                         '&Fields={field_filters}' +
                         '&SortOrder=Descending' +
                         '&Filters=IsUnplayed' +
                         '&IsPlayed=false' +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&IncludeItemTypes=Episode' +
                         '&ImageTypeLimit=1' +
                         '&format=json')
    item_data['name_format'] = 'Episode|episode_name_format'
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30264) + " (" + show_x_filtered_items + ")"
    item_data['media_type'] = 'Episodes'
    item_data['use_cache'] = False
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?SortBy=DatePlayed' +
                         '&Limit={ItemLimit}' +
                         '&SortOrder=Descending' +
                         '&Recursive=true' +
                         '&Fields={field_filters}' +
                         '&Filters=IsResumable' +
                         '&IncludeItemTypes=Episode' +
                         '&ImageTypeLimit=1' +
                         '&format=json')
    item_data['name_format'] = 'Episode|episode_name_format'
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30263) + " (" + show_x_filtered_items + ")"
    item_data['media_type'] = 'Episodes'
    item_data['use_cache'] = False
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?SortBy=DateCreated' +
                         '&Limit={ItemLimit}' +
                         '&Recursive=true' +
                         '&Fields={field_filters}' +
                         '&SortOrder=Descending' +
                         '&Filters=IsUnplayed,IsNotFolder' +
                         '&IsPlayed=false' +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&IncludeItemTypes=Episode' +
                         '&ImageTypeLimit=1' +
                         '&format=json')
    item_data['name_format'] = 'Episode|episode_name_format'
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30265) + " (" + show_x_filtered_items + ")"
    item_data['media_type'] = 'Episodes'
    item_data['use_cache'] = False
    item_data['path'] = ('{server}/emby/Shows/NextUp/?Userid={userid}' +
                         '&Limit={ItemLimit}' +
                         '&Recursive=true' +
                         '&Fields={field_filters}' +
                         '&Filters=IsUnplayed,IsNotFolder' +
                         '&IsPlayed=false' +
                         '&IsVirtualUnaired=false' +
                         '&IsMissing=False' +
                         '&IncludeItemTypes=Episode' +
                         '&ImageTypeLimit=1' +
                         '&format=json')
    item_data['name_format'] = 'Episode|episode_name_format'
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30318)
    item_data['media_type'] = 'MusicAlbums'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?Recursive=true' +
                         '&IncludeItemTypes=MusicAlbum' +
                         '&ImageTypeLimit=1' +
                         '&EnableImageTypes=Primary,Backdrop,Banner,Thumb' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30350) + " (" + show_x_filtered_items + ")"
    item_data['art'] = art
    item_data['media_type'] = 'MusicAlbums'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items/Latest' +
                         '?IncludeItemTypes=Audio' +
                         '&ImageTypeLimit=1' +
                         '&Limit={ItemLimit}' +
                         '&EnableImageTypes=Primary,Backdrop,Banner,Thumb' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30351) + " (" + show_x_filtered_items + ")"
    item_data['art'] = art
    item_data['media_type'] = 'MusicAlbum'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?SortBy=DatePlayed' +
                         '&SortOrder=Descending' +
                         '&IncludeItemTypes=Audio' +
                         '&Limit={ItemLimit}' +
                         '&Recursive=true' +
                         '&ImageTypeLimit=1' +
                         '&EnableImageTypes=Primary,Backdrop,Banner,Thumb' +
                         '&Filters=IsPlayed' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30352) + " (" + show_x_filtered_items + ")"
    item_data['art'] = art
    item_data['media_type'] = 'MusicAlbum'
    item_data['path'] = ('{server}/emby/Users/{userid}/Items' +
                         '?SortBy=PlayCount' +
                         '&SortOrder=Descending' +
                         '&IncludeItemTypes=Audio' +
                         '&Limit={ItemLimit}' +
                         '&Recursive=true' +
                         '&ImageTypeLimit=1' +
                         '&EnableImageTypes=Primary,Backdrop,Banner,Thumb' +
                         '&Filters=IsPlayed' +
                         '&format=json')
    collections.append(item_data)

    item_data = {}
    item_data['title'] = string_load(30319)
    item_data['media_type'] = 'MusicArtists'
    item_data['path'] = ('{server}/emby/Artists/AlbumArtists' +
                         '?Recursive=true' +
                         '&ImageTypeLimit=1' +
                         '&EnableImageTypes=Primary,Backdrop,Banner,Thumb' +
                         '&SortBy=Name' +
                         '&SortOrder=Ascending' +
                         '&format=json')
    collections.append(item_data)

    return collections
def showMoviePages(params):
    log.debug("showMoviePages: {0}", params)

    parent_id = params.get("parent_id")
    settings = xbmcaddon.Addon()

    group_movies = settings.getSetting('group_movies') == "true"

    url = ('{server}/emby/Users/{userid}/Items' +
           '?IsVirtualUnaired=false' +
           '&CollapseBoxSetItems=' + str(group_movies) +
           '&GroupItemsIntoCollections=' + str(group_movies) +
           '&Recursive=true' +
           "&IncludeItemTypes=Movie"
           '&IsMissing=False' +
           '&ImageTypeLimit=0' +
           '&format=json')

    if parent_id:
        url += "&ParentId=" + parent_id

    data_manager = DataManager()
    result = data_manager.GetContent(url)

    if result is None:
        return

    total_results = result.get("TotalRecordCount", 0)
    log.debug("showMoviePages TotalRecordCount {0}", total_results)

    if result == 0:
        return

    page_limit = int(settings.getSetting('moviePageSize'))
    if page_limit == 0:
        page_limit = 20

    start_index = 0
    collections = []

    while start_index < total_results:

        item_url = ("{server}/emby/Users/{userid}/Items" +
                    "?IsVirtualUnaired=false" +
                    '&CollapseBoxSetItems=' + str(group_movies) +
                    '&GroupItemsIntoCollections=' + str(group_movies) +
                    "&Recursive=true" +
                    "&IsMissing=False" +
                    "&IncludeItemTypes=Movie"
                    "&Fields={field_filters}" +
                    "&ImageTypeLimit=1" +
                    "&SortBy=Name" +
                    "&SortOrder=Ascending" +
                    "&format=json")

        if parent_id:
            item_url += "&ParentId=" + parent_id

        item_url += "&StartIndex=" + str(start_index) + "&Limit=" + str(page_limit)

        page_upper = start_index + page_limit
        if page_upper > total_results:
            page_upper = total_results

        item_data = {}
        item_data['title'] = "Page (" + str(start_index + 1) + " - " + str(page_upper) + ")"
        item_data['path'] = item_url
        item_data['media_type'] = 'movies'

        collections.append(item_data)
        start_index = start_index + page_limit

    for collection in collections:
        content_url = urllib.quote(collection['path'])
        url = sys.argv[0] + ("?url=" + content_url +
                             "&mode=GET_CONTENT" +
                             "&media_type=" + collection["media_type"])
        log.debug("addMenuDirectoryItem: {0} - {1} - {2}", collection.get('title'), url, collection.get("art"))
        addMenuDirectoryItem(collection.get('title', string_load(30250)), url, art=collection.get("art"))

    xbmcplugin.endOfDirectory(int(sys.argv[1]))
def showGenreList(params):
    log.debug("showGenreList: {0}", params)

    server = downloadUtils.getServer()
    if server is None:
        return

    parent_id = params.get("parent_id")
    item_type = params.get("item_type")

    kodi_type = "Movies"
    emby_type = "Movie"
    if item_type is not None and item_type == "tvshow":
        emby_type = "Series"
        kodi_type = "tvshows"

    url = ("{server}/emby/Genres?" +
           "SortBy=Name" +
           "&SortOrder=Ascending" +
           "&IncludeItemTypes=" + emby_type +
           "&Recursive=true" +
           "&UserId={userid}")

    if parent_id is not None:
        url += "&parentid=" + parent_id

    data_manager = DataManager()
    result = data_manager.GetContent(url)

    if result is not None:
        result = result.get("Items")
    else:
        result = []

    settings = xbmcaddon.Addon()
    group_movies = settings.getSetting('group_movies') == "true"

    collections = []
    xbmcplugin.setContent(int(sys.argv[1]), 'genres')

    for genre in result:
        art = getArt(item=genre, server=server)
        item_data = {}
        item_data['title'] = genre.get("Name")
        item_data['media_type'] = kodi_type
        item_data['art'] = art

        url = ("{server}/emby/Users/{userid}/Items" +
               "?Fields={field_filters}" +
               "&Recursive=true" +
               '&CollapseBoxSetItems=' + str(group_movies) +
               '&GroupItemsIntoCollections=' + str(group_movies) +
               "&GenreIds=" + genre.get("Id") +
               "&IncludeItemTypes=" + emby_type +
               "&ImageTypeLimit=1")

        if parent_id is not None:
            url += "&parentid=" + parent_id

        item_data['path'] = url
        collections.append(item_data)

    for collection in collections:
        url = sys.argv[0] + ("?url=" + urllib.quote(collection['path']) +
                             "&mode=GET_CONTENT" +
                             "&media_type=" + collection["media_type"])
        log.debug("addMenuDirectoryItem: {0} - {1} - {2}", collection.get('title'), url, collection.get("art"))
        addMenuDirectoryItem(collection.get('title', string_load(30250)), url, art=collection.get("art"))

    xbmcplugin.endOfDirectory(int(sys.argv[1]))