Esempio n. 1
0
 def end_of_directory(self, forceStatus=None):
     if self.seen_nodes:
         self.seen_nodes = {}
     success = True
     if forceStatus is not None:
         success = forceStatus
     if not self.put_item_ok or self.total_put == 0:
         success = False
     if not self.asList:
         xbmcplugin.setContent(
             handle=self.handle, content=self.content_type)
         xbmcplugin.endOfDirectory(
             handle=self.handle,
             succeeded=success,
             updateListing=False,
             cacheToDisc=success)
     return self.total_put
Esempio n. 2
0
def set_content(content):
    xbmcplugin.setContent(int(sys.argv[1]), content)
Esempio n. 3
0
import importlib
import six

from kodi_six import xbmc, xbmcplugin, xbmcaddon, xbmcvfs

from resources.lib import basics
from resources.lib.url_dispatcher import URL_Dispatcher
from resources.lib import utils
from resources.lib import favorites
from resources.lib import pin
from resources.lib.adultsite import AdultSite
from resources.lib.sites import *  # noqa

socket.setdefaulttimeout(60)

xbmcplugin.setContent(basics.addon_handle, 'movies')
addon = xbmcaddon.Addon()
TRANSLATEPATH = xbmcvfs.translatePath if six.PY3 else xbmc.translatePath
progress = utils.progress
dialog = utils.dialog

url_dispatcher = URL_Dispatcher('main')

if addon.getSetting('custom_sites') == 'true':
    sys.path.append(basics.customSitesDir)
    for module_name in favorites.enabled_custom_sites():
        try:
            importlib.import_module(module_name)
        except Exception as e:
            utils.kodilog('{0} {1}: {2}'.format(utils.i18n('err_custom'), module_name, e))
            favorites.disable_custom_site_by_module(module_name)
def run(url_suffix=""):
    to = int(ADDON.getSetting("buffer_timeout"))
    if to < 60:
        to = 60
    to = to * 2

    socket.setdefaulttimeout(to)
    urllib_request.install_opener(
        urllib_request.build_opener(NoRedirectHandler()))

    # Pause currently playing Elementum file to avoid doubling requests
    try:
        if xbmc.Player().isPlaying() and ADDON_ID in xbmc.Player(
        ).getPlayingFile():
            xbmc.Player().pause()
    except:
        pass

    url = sys.argv[0].replace("plugin://%s" % ADDON_ID,
                              ELEMENTUMD_HOST + url_suffix) + sys.argv[2]
    query_add = ""

    if len(sys.argv) > 3:
        app = sys.argv[3].replace(":", "=")

        # Replacing resume=false with resume=true if item is launched from main window
        title = xbmc.getInfoLabel('ListItem.Title')
        label = xbmc.getInfoLabel('ListItem.Label')
        # if "resume" in app and not title and not label:
        #     app = app.replace("resume=false", "resume=true")
        # if "resume" not in app and not title and not label:
        if not title and not label:
            if app:
                app = app.replace("resume=false", "")
                app += "&"
            if app and "resume" not in app:
                app += "resume=true"
        query_add = app
    elif "play" in url or "links" in url:
        query_add = "resume=true"

    if query_add and "resume" not in url:
        query_add = query_add.replace("resume=", "doresume=")
        if "?" in url:
            url += "&" + query_add
        else:
            url += "?" + query_add

    log.debug("Requesting %s from %s" % (url, repr(sys.argv)))

    try:
        data = _json(url)
    except urllib_error.URLError as e:
        if isinstance(e.reason, IOError) or isinstance(
                e.reason, OSError) or 'Connection refused' in e.reason:
            notify(getLocalizedString(30116), time=7000)
        else:
            import traceback
            map(log.error, traceback.format_exc().split("\n"))
            notify(e.reason, time=7000)
        return
    except Exception as e:
        import traceback
        map(log.error, traceback.format_exc().split("\n"))
        try:
            msg = six.ensure_text(e.__str__(), errors='ignore')
        except:
            try:
                msg = six.ensure_binary(e.__str__(), errors='ignore')
            except:
                msg = repr(e)
        notify(getLocalizedLabel(msg), time=7000)
        return

    if not data:
        return

    if data["content_type"]:
        content_type = data["content_type"]
        if data["content_type"].startswith("menus"):
            content_type = data["content_type"].split("_")[1]

        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_UNSORTED)
        if content_type != "tvshows":
            xbmcplugin.addSortMethod(HANDLE,
                                     xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
        else:
            xbmcplugin.addSortMethod(HANDLE,
                                     xbmcplugin.SORT_METHOD_TITLE_IGNORE_THE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_DATE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_GENRE)
        xbmcplugin.setContent(HANDLE, content_type)

    listitems = list(range(len(data["items"])))
    for i, item in enumerate(data["items"]):
        # Translate labels
        if item["label"][0:8] == "LOCALIZE":
            item["label"] = getLocalizedLabel(item["label"])
            if isinstance(item["label"], str):
                item["label"] = six.ensure_text(item["label"], 'utf-8')
        if item["label2"][0:8] == "LOCALIZE":
            item["label2"] = getLocalizedLabel(item["label2"])

        listItem = xbmcgui.ListItem(label=item["label"],
                                    label2=item["label2"],
                                    iconImage=item["icon"],
                                    thumbnailImage=item["thumbnail"])
        if item.get("info"):
            listItem.setInfo("video", item["info"])
        if item.get("stream_info"):
            for type_, values in item["stream_info"].items():
                listItem.addStreamInfo(type_, values)
        if item.get("art"):
            listItem.setArt(item["art"])
        elif ADDON.getSetting('default_fanart'
                              ) == 'true' and item["label"] != six.ensure_text(
                                  getLocalizedString(30218), 'utf-8'):
            fanart = os.path.join(ADDON_PATH, "fanart.png")
            listItem.setArt({'fanart': fanart})
        if item.get("context_menu"):
            # Translate context menus
            for m, menu in enumerate(item["context_menu"]):
                if menu[0][0:8] == "LOCALIZE":
                    menu[0] = getLocalizedLabel(menu[0])
            listItem.addContextMenuItems(item["context_menu"])
        listItem.setProperty("isPlayable", item["is_playable"] and "true"
                             or "false")
        if item.get("properties"):
            for k, v in item["properties"].items():
                listItem.setProperty(k, v)
        listitems[i] = (item["path"], listItem, not item["is_playable"])

    xbmcplugin.addDirectoryItems(HANDLE, listitems, totalItems=len(listitems))

    # Set ViewMode
    if data["content_type"]:
        viewMode = ADDON.getSetting("viewmode_%s" % data["content_type"])
        if viewMode:
            try:
                xbmc.executebuiltin('Container.SetViewMode(%s)' % viewMode)
            except Exception as e:
                log.warning("Unable to SetViewMode(%s): %s" %
                            (viewMode, repr(e)))

    xbmcplugin.endOfDirectory(HANDLE,
                              succeeded=True,
                              updateListing=False,
                              cacheToDisc=False)
Esempio n. 5
0
def run(url_suffix="", retry=0):
    if '/restart/' in sys.argv[0]:
        restart_signal()
        return

    try:
        buffer_timeout = int(ADDON.getSetting("buffer_timeout"))
        if buffer_timeout < 60:
            buffer_timeout = 60
    except:
        buffer_timeout = 60
    buffer_timeout = buffer_timeout * 2

    try:
        preload_timeout = int(ADDON.getSetting("preload_timeout"))
        if preload_timeout < 1:
            preload_timeout = 1
    except:
        preload_timeout = 1

    socket.setdefaulttimeout(buffer_timeout)
    opener = urllib_request.build_opener(NoRedirectHandler())
    opener.addheaders = [('User-Agent', ADDON_ID)]
    urllib_request.install_opener(opener)

    # Pause currently playing Elementum file to avoid doubling requests
    try:
        if xbmc.Player().isPlaying() and ADDON_ID in xbmc.Player(
        ).getPlayingFile():
            xbmc.Player().pause()
    except:
        pass

    url = sys.argv[0].replace("plugin://%s" % ADDON_ID,
                              ELEMENTUMD_HOST + url_suffix) + sys.argv[2]
    query_add = ""

    if len(sys.argv) > 3:
        query_add = sys.argv[3].replace(":", "=")

    if query_add and "resume=" not in url:
        query_add = query_add.replace("resume=", "doresume=")
        if "?" in url:
            url += "&" + query_add
        else:
            url += "?" + query_add

    log.debug("Requesting %s from %s" % (url, repr(sys.argv)))

    try:
        data = _json(url)
    except PlayerException as e:
        redirect_url = e.__str__()
        log.debug("Launching player with %s" % (redirect_url))
        xbmcplugin.endOfDirectory(HANDLE, succeeded=True)
        xbmc.sleep(500)
        xbmc.executeJSONRPC(
            '{"jsonrpc":"2.0","method":"Player.Open","params":{"item":{"file":"%s"}},"id":"1"}'
            % (redirect_url))
        return
    except RedirectException as e:
        redirect_url = e.__str__()
        log.debug("Redirecting Kodi with %s" % (redirect_url))
        xbmcplugin.endOfDirectory(HANDLE, succeeded=True)
        xbmc.sleep(500)
        if "keyboard=1" in sys.argv[0]:
            xbmc.executebuiltin('Container.Update(%s,replace)' %
                                (redirect_url))
        else:
            xbmc.executebuiltin('Container.Update(%s)' % (redirect_url))
        return
    except urllib_error.URLError as e:
        # We can retry the request if connection is refused.
        # For example when plugin has not yet started but is requested by someone.
        if retry <= 2:
            time.sleep(preload_timeout)
            return run(retry=retry + 1)

        if isinstance(e.reason, IOError) or isinstance(
                e.reason, OSError) or 'Connection refused' in e.reason:
            notify(getLocalizedString(30116), time=7000)
        else:
            import traceback
            map(log.error, traceback.format_exc().split("\n"))
            notify(e.reason, time=7000)
        return
    except Exception as e:
        import traceback
        log.debug(traceback.print_exc())
        map(log.error, traceback.format_exc().split("\n"))
        try:
            msg = six.ensure_text(e.__str__(), errors='ignore')
        except:
            try:
                msg = six.ensure_binary(e.__str__(), errors='ignore')
            except:
                msg = repr(e)
        notify(getLocalizedLabel(msg), time=7000)
        return

    if not data:
        return

    if data["content_type"]:
        content_type = data["content_type"]
        if data["content_type"].startswith("menus"):
            content_type = data["content_type"].split("_")[1]

        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_UNSORTED)
        if content_type != "tvshows":
            xbmcplugin.addSortMethod(HANDLE,
                                     xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
        else:
            xbmcplugin.addSortMethod(HANDLE,
                                     xbmcplugin.SORT_METHOD_TITLE_IGNORE_THE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_DATE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_GENRE)
        xbmcplugin.setContent(HANDLE, content_type)

    listitems = list(range(len(data["items"])))
    for i, item in enumerate(data["items"]):
        # Translate labels
        if "LOCALIZE" in item["label"]:
            if item["label"][0:8] == "LOCALIZE":
                item["label"] = getLocalizedLabel(item["label"])
            else:
                item["label"] = getLocalizedText(item["label"])
            if isinstance(item["label"], str):
                item["label"] = six.ensure_text(item["label"], 'utf-8')
        if "LOCALIZE" in item["label2"]:
            if item["label2"][0:8] == "LOCALIZE":
                item["label2"] = getLocalizedText(item["label2"])
            else:
                item["label2"] = getLocalizedText(item["label2"])
            if isinstance(item["label2"], str):
                item["label2"] = six.ensure_text(item["label2"], 'utf-8')

        if PLATFORM['kodi'] >= 19:
            listItem = xbmcgui.ListItem(label=item["label"],
                                        label2=item["label2"])
            listItem.setArt({'icon': item["icon"]})
            listItem.setArt({'thumb': item["thumbnail"]})
        else:
            listItem = xbmcgui.ListItem(label=item["label"],
                                        label2=item["label2"],
                                        iconImage=item["icon"],
                                        thumbnailImage=item["thumbnail"])

        try:
            if item.get("castmembers") and PLATFORM['kodi'] >= 17:
                listItem.setCast(item.get("castmembers"))
            if item.get("info"):
                item["info"] = normalizeLabels(item["info"])
                listItem.setInfo("video", item["info"])
            if item.get("stream_info"):
                for type_, values in item["stream_info"].items():
                    listItem.addStreamInfo(type_, values)
            if item.get("art"):
                if "fanarts" in item.get("art") and item.get("art")["fanarts"]:
                    try:
                        start = 0
                        fanart_list = []
                        for fa in item.get("art")["fanarts"]:
                            start += 1
                            item.get("art")["fanart{}".format(start)] = fa
                            fanart_list.append({'image': fa})

                        if PLATFORM['kodi'] >= 18:
                            listItem.setAvailableFanart(fanart_list)
                    except Exception as e:
                        log.warning(
                            "Could not initialize ListItem.Art (%s): %s" %
                            (repr(item.get("art")), repr(e)))
                        pass
                    del item.get("art")["fanarts"]

                listItem.setArt(item["art"])
            elif ADDON.getSetting('default_fanart') == 'true' and item[
                    "label"] != six.ensure_text(getLocalizedString(30218),
                                                'utf-8'):
                fanart = os.path.join(ADDON_PATH, "fanart.jpg")
                listItem.setArt({'fanart': fanart})
            if item.get("context_menu"):
                # Translate context menus
                for m, menu in enumerate(item["context_menu"]):
                    if menu[0][0:8] == "LOCALIZE":
                        menu[0] = getLocalizedLabel(menu[0])
                    if PLATFORM['kodi'] >= 19 and menu[1][0:5] == "XBMC.":
                        menu[1] = menu[1][5:]
                listItem.addContextMenuItems(item["context_menu"])
            listItem.setProperty("isPlayable", item["is_playable"] and "true"
                                 or "false")
            if item.get("properties"):
                for k, v in item["properties"].items():
                    listItem.setProperty(k, v)
        except Exception as e:
            log.warning("Could not initialize ListItem (%s): %s" %
                        (repr(item.get("info")), repr(e)))
        listitems[i] = (item["path"], listItem, not item["is_playable"])

    xbmcplugin.addDirectoryItems(HANDLE, listitems, totalItems=len(listitems))

    # Set ViewMode
    if data["content_type"]:
        viewMode = ADDON.getSetting("viewmode_%s" % data["content_type"])
        if viewMode:
            try:
                xbmc.executebuiltin('Container.SetViewMode(%s)' % viewMode)
            except Exception as e:
                log.warning("Unable to SetViewMode(%s): %s" %
                            (viewMode, repr(e)))

    xbmcplugin.endOfDirectory(HANDLE,
                              succeeded=True,
                              updateListing=False,
                              cacheToDisc=True)
def mainSearch(url):
    if '|SPLIT|' in url: url, site = url.split('|SPLIT|')
    term = url
    if term == "null":  term = kodi.get_keyboard('Search %s' % kodi.get_name())

    if term:
        search_on_off = kodi.get_setting("search_setting")
        if search_on_off == "true":
            delTerm(term)
            addTerm(term)

        display_term = term
        term = quote_plus(term)
        term = term.lower()

        if site == 'all':
            sources = __all__
            search_sources = []
            for i in sources:
                try:
                    if eval(i + ".search_tag") == 1: search_sources.append(i)
                except:
                    pass

            if search_sources:
                i = 0
                source_num = 0
                failed_list = ''
                line1 = kodi.giveColor('Searching: ', 'white') + kodi.giveColor('%s', 'dodgerblue')
                line2 = kodi.giveColor('Found: %s videos', 'white')
                line3 = kodi.giveColor('Source: %s of ' + str(len(search_sources)), 'white')

                kodi.dp.create(kodi.get_name(), '', line2, '')
                xbmc.executebuiltin('Dialog.Close(busydialog)')
                for u in sorted(search_sources):
                    if kodi.dp.iscanceled(): break
                    try:
                        i += 1
                        progress = 100 * int(i) / len(search_sources)
                        kodi.dp.update(progress, line1 % u.title(), line2 % str(source_num), line3 % str(i))
                        search_url = eval(u + ".search_base") % term
                        try:
                            source_n = eval(u + ".content('%s',True)" % search_url)
                        except:
                            source_n = 0
                        try:
                            source_n = int(source_n)
                        except:
                            source_n = 0
                        if not source_n:
                            if failed_list == '':
                                failed_list += str(u).title()
                            else:
                                failed_list += ', %s' % str(u).title()
                        else:
                            source_num += int(source_n)
                    except:
                        pass
                kodi.dp.close()
                if failed_list != '':
                    kodi.notify(msg='%s failed to return results.' % failed_list, duration=4000, sound=True)
                    log_utils.log('Scrapers failing to return search results are :: : %s' % failed_list,
                                  xbmc.LOGERROR)
                else:
                    kodi.notify(msg='%s results found.' % str(source_num), duration=4000, sound=True)
                xbmcplugin.setContent(kodi.syshandle, 'movies')
                xbmcplugin.endOfDirectory(kodi.syshandle, cacheToDisc=True)
                local_utils.setView('search')
        else:
            search_url = eval(site + ".search_base") % term
            eval(site + ".content('%s')" % search_url)
    else:
        kodi.notify(msg='Blank searches are not allowed.')
        quit()
Esempio n. 7
0
def browse(media, view_id=None, folder=None, server_id=None, api_client=None):
    ''' Browse content dynamically.
    '''
    LOG.info("--[ v:%s/%s ] %s", view_id, media, folder)

    if not window('jellyfin_online.bool') and server_id is None:

        monitor = xbmc.Monitor()

        for _i in range(300):
            if window('jellyfin_online.bool'):
                break
            elif monitor.waitForAbort(0.1):
                return
        else:
            LOG.error("Default server is not online.")

            return

    folder = folder.lower() if folder else None

    if folder is None and media in ('homevideos', 'movies', 'books',
                                    'audiobooks'):
        return browse_subfolders(media, view_id, server_id)

    if folder and folder == 'firstletter':
        return browse_letters(media, view_id, server_id)

    if view_id:

        view = api_client.get_item(view_id)
        xbmcplugin.setPluginCategory(PROCESS_HANDLE, view['Name'])

    content_type = "files"

    if media in ('tvshows', 'seasons', 'episodes', 'movies', 'musicvideos',
                 'songs', 'albums'):
        content_type = media
    elif media in ('homevideos', 'photos'):
        content_type = "images"
    elif media in ('books', 'audiobooks'):
        content_type = "videos"
    elif media == 'music':
        content_type = "artists"

    if folder == 'recentlyadded':
        listing = api_client.get_recently_added(None, view_id, None)
    elif folder == 'genres':
        listing = api_client.get_genres(view_id)
    elif media == 'livetv':
        listing = api_client.get_channels()
    elif folder == 'unwatched':
        listing = get_filtered_section(view_id, None, None, None, None, None,
                                       ['IsUnplayed'], None, server_id,
                                       api_client)
    elif folder == 'favorite':
        listing = get_filtered_section(view_id, None, None, None, None, None,
                                       ['IsFavorite'], None, server_id,
                                       api_client)
    elif folder == 'inprogress':
        listing = get_filtered_section(view_id, None, None, None, None, None,
                                       ['IsResumable'], None, server_id,
                                       api_client)
    elif folder == 'boxsets':
        listing = get_filtered_section(view_id, get_media_type('boxsets'),
                                       None, True, None, None, None, None,
                                       server_id, api_client)
    elif folder == 'random':
        listing = get_filtered_section(view_id, get_media_type(content_type),
                                       25, True, "Random", None, None, None,
                                       server_id, api_client)
    elif (folder or "").startswith('firstletter-'):
        listing = get_filtered_section(
            view_id, get_media_type(content_type), None, None, None, None,
            None, {'NameStartsWith': folder.split('-')[1]}, server_id,
            api_client)
    elif (folder or "").startswith('genres-'):
        listing = get_filtered_section(view_id, get_media_type(content_type),
                                       None, None, None, None, None,
                                       {'GenreIds': folder.split('-')[1]},
                                       server_id, api_client)
    elif folder == 'favepisodes':
        listing = get_filtered_section(None, get_media_type(content_type), 25,
                                       None, None, None, ['IsFavorite'], None,
                                       server_id, api_client)
    elif folder and media == 'playlists':
        listing = get_filtered_section(folder, get_media_type(content_type),
                                       None, False, 'None', None, None, None,
                                       server_id, api_client)
    elif media == 'homevideos':
        listing = get_filtered_section(folder or view_id,
                                       get_media_type(content_type), None,
                                       False, None, None, None, None,
                                       server_id, api_client)
    elif media in ['movies', 'episodes']:
        listing = get_filtered_section(folder or view_id,
                                       get_media_type(content_type), None,
                                       True, None, None, None, None, server_id,
                                       api_client)
    elif media in ('boxset', 'library'):
        listing = get_filtered_section(folder or view_id, None, None, True,
                                       None, None, None, None, server_id,
                                       api_client)
    elif media == 'boxsets':
        listing = get_filtered_section(folder or view_id, None, None, False,
                                       None, None, ['Boxsets'], None,
                                       server_id, api_client)
    elif media == 'tvshows':
        listing = get_filtered_section(folder or view_id,
                                       get_media_type(content_type), None,
                                       True, None, None, None, None, server_id,
                                       api_client)
    elif media == 'seasons':
        listing = api_client.get_seasons(folder)
    elif media != 'files':
        listing = get_filtered_section(folder or view_id,
                                       get_media_type(content_type), None,
                                       False, None, None, None, None,
                                       server_id, api_client)
    else:
        listing = get_filtered_section(folder or view_id, None, None, False,
                                       None, None, None, None, server_id,
                                       api_client)

    if listing:

        actions = Actions(server_id, api_client)
        list_li = []
        listing = listing if type(listing) == list else listing.get(
            'Items', [])

        for item in listing:

            li = xbmcgui.ListItem()
            li.setProperty('jellyfinid', item['Id'])
            li.setProperty('jellyfinserver', server_id)
            actions.set_listitem(item, li)

            if item.get('IsFolder'):

                params = {
                    'id': view_id or item['Id'],
                    'mode': "browse",
                    'type': get_folder_type(item, media) or media,
                    'folder': item['Id'],
                    'server': server_id
                }
                path = "%s?%s" % ("plugin://plugin.video.jellyfin/",
                                  urlencode(params))
                context = []

                if item['Type'] in ('Series', 'Season', 'Playlist'):
                    context.append((
                        "Play",
                        "RunPlugin(plugin://plugin.video.jellyfin/?mode=playlist&id=%s&server=%s)"
                        % (item['Id'], server_id)))

                if item['UserData']['Played']:
                    context.append((translate(
                        16104
                    ), "RunPlugin(plugin://plugin.video.jellyfin/?mode=unwatched&id=%s&server=%s)"
                                    % (item['Id'], server_id)))
                else:
                    context.append((translate(
                        16103
                    ), "RunPlugin(plugin://plugin.video.jellyfin/?mode=watched&id=%s&server=%s)"
                                    % (item['Id'], server_id)))

                li.addContextMenuItems(context)
                list_li.append((path, li, True))

            elif item['Type'] == 'Genre':

                params = {
                    'id': view_id or item['Id'],
                    'mode': "browse",
                    'type': get_folder_type(item, media) or media,
                    'folder': 'genres-%s' % item['Id'],
                    'server': server_id
                }
                path = "%s?%s" % ("plugin://plugin.video.jellyfin/",
                                  urlencode(params))
                list_li.append((path, li, True))

            else:
                if item['Type'] not in ('Photo', 'PhotoAlbum'):
                    params = {
                        'id': item['Id'],
                        'mode': "play",
                        'server': server_id
                    }
                    path = "%s?%s" % ("plugin://plugin.video.jellyfin/",
                                      urlencode(params))
                    li.setProperty('path', path)
                    context = [(translate(
                        13412
                    ), "RunPlugin(plugin://plugin.video.jellyfin/?mode=playlist&id=%s&server=%s)"
                                % (item['Id'], server_id))]

                    if item['UserData']['Played']:
                        context.append((translate(
                            16104
                        ), "RunPlugin(plugin://plugin.video.jellyfin/?mode=unwatched&id=%s&server=%s)"
                                        % (item['Id'], server_id)))
                    else:
                        context.append((translate(
                            16103
                        ), "RunPlugin(plugin://plugin.video.jellyfin/?mode=watched&id=%s&server=%s)"
                                        % (item['Id'], server_id)))

                    li.addContextMenuItems(context)

                list_li.append((li.getProperty('path'), li, False))

        xbmcplugin.addDirectoryItems(PROCESS_HANDLE, list_li, len(list_li))

    if content_type == 'images':
        xbmcplugin.addSortMethod(PROCESS_HANDLE,
                                 xbmcplugin.SORT_METHOD_VIDEO_TITLE)
        xbmcplugin.addSortMethod(PROCESS_HANDLE, xbmcplugin.SORT_METHOD_DATE)
        xbmcplugin.addSortMethod(PROCESS_HANDLE,
                                 xbmcplugin.SORT_METHOD_VIDEO_RATING)
        xbmcplugin.addSortMethod(PROCESS_HANDLE,
                                 xbmcplugin.SORT_METHOD_VIDEO_RUNTIME)

    xbmcplugin.setContent(PROCESS_HANDLE, content_type)
    xbmcplugin.endOfDirectory(PROCESS_HANDLE)
def run():
    """
    Run the plugin.
    """
    params = get_params()
    try:
        url = unquote_plus(params["url"])
    except Exception:
        url = None
    try:
        name = unquote_plus(params["name"])
    except Exception:
        name = None
    try:
        mode = int(params["mode"])
    except Exception:
        mode = None
    try:
        page_hash = unquote_plus(params['page_hash'])
    except Exception:
        page_hash = None
    try:
        page = unquote_plus(params['page'])
    except Exception:
        page = None

    log('Mode: ' + str(mode))
    log('URL : ' + str(url))
    log('Name: ' + str(name))
    log('Page Hash: ' + str(page_hash))
    log('Page: ' + str(page))

    if mode is None:
        identifiers = [
            'All_Shows',
            'Favourite_Shows',
            'Newest_Favourite_Shows',
            'Recommendations',
            'Newest_Shows',
            'Most_Clicked_Shows',
            'Soon_Offline',
            'Shows_By_Date',
            # 'Live_TV',
            'Search',
            'SRF_Live',
            'SRF_YouTube'
        ]
        SRFPlayTV().build_main_menu(identifiers)
    elif mode == 10:
        SRFPlayTV().build_all_shows_menu()
    elif mode == 11:
        SRFPlayTV().build_favourite_shows_menu()
    elif mode == 12:
        SRFPlayTV().build_newest_favourite_menu(page=page)
    elif mode == 13:
        SRFPlayTV().build_topics_overview_menu('Newest')
    elif mode == 14:
        SRFPlayTV().build_topics_overview_menu('Most clicked')
    elif mode == 15:
        SRFPlayTV().build_topics_menu('Soon offline', page=page)
    elif mode == 16:
        SRFPlayTV().build_topics_menu('Trending', page=page)
    elif mode == 17:
        SRFPlayTV().build_dates_overview_menu()
    elif mode == 18:
        SRFPlayTV().build_live_menu(extract_srf3=True)
    elif mode == 19:
        SRFPlayTV().manage_favourite_shows()
    elif mode == 20:
        SRFPlayTV().build_show_menu(name, page_hash=page_hash)
    elif mode == 21:
        SRFPlayTV().build_episode_menu(name)
    elif mode == 22:
        SRFPlayTV().build_topics_menu('Newest', name, page=page)
    elif mode == 23:
        SRFPlayTV().build_topics_menu('Most clicked', name, page=page)
    elif mode == 24:
        SRFPlayTV().build_date_menu(name)
    elif mode == 25:
        SRFPlayTV().pick_date()
    # elif mode == 26:
    #     SRFPlayTV().build_tv_menu()
    elif mode == 27:
        SRFPlayTV().build_search_menu()
    elif mode == 28:
        SRFPlayTV().build_search_media_menu(mode=mode,
                                            name=name,
                                            page=page,
                                            page_hash=page_hash)
    elif mode == 29:
        SRFPlayTV().build_search_show_menu(name=name)
    elif mode == 70:
        SRFPlayTV().build_recent_search_menu('media')
    elif mode == 71:
        SRFPlayTV().build_recent_search_menu('show')
    elif mode == 30:
        SRFPlayTV().build_youtube_channel_overview_menu(33)
    elif mode == 33:
        SRFPlayTV().build_youtube_channel_menu(name,
                                               mode,
                                               page=page,
                                               page_token=page_hash)
    elif mode == 50:
        SRFPlayTV().play_video(name)
    elif mode == 51:
        SRFPlayTV().play_livestream(name)

    xbmcplugin.setContent(int(sys.argv[1]), CONTENT_TYPE)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_NONE)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_TITLE)
    xbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc=True)
def process_movies(context, url, tree=None):
    # get the server name from the URL, which was passed via the on screen listing..
    server = context.plex_network.get_server_from_url(url)

    tree = get_xml(context, url, tree)
    if tree is None:
        return

    content_counter = {
        'photo': 0,
        'track': 0,
        'video': 0,
    }
    # Find all the video tags, as they contain the data we need to link to a file.
    start_time = time.time()
    items = []
    append_item = items.append
    if PY3:
        branches = tree.iter()
    else:
        branches = tree.getiterator()

    for branch in branches:
        item = Item(server, url, tree, branch)
        if branch.tag.lower() == 'video':
            append_item(create_movie_item(context, item))
        elif branch.tag.lower() == 'track':  # mixed content video playlist
            append_item(create_track_item(context, item))
        elif branch.tag.lower() == 'photo':  # mixed content video playlist
            append_item(create_photo_item(context, item))

    if items:
        content_type = 'movies'
        if context.settings.mixed_content_type() == 'majority':
            majority = max(content_counter, key=content_counter.get)
            if majority == 'photo':
                content_type = 'images'
            elif majority == 'track':
                content_type = 'songs'

        if content_type == 'movies' and '/collection/' in url:
            xbmcplugin.addSortMethod(get_handle(),
                                     xbmcplugin.SORT_METHOD_VIDEO_YEAR)
        xbmcplugin.addSortMethod(get_handle(), xbmcplugin.SORT_METHOD_UNSORTED)
        xbmcplugin.addSortMethod(
            get_handle(), xbmcplugin.SORT_METHOD_VIDEO_SORT_TITLE_IGNORE_THE)
        xbmcplugin.addSortMethod(get_handle(),
                                 xbmcplugin.SORT_METHOD_DATEADDED)
        xbmcplugin.addSortMethod(get_handle(), xbmcplugin.SORT_METHOD_DATE)
        xbmcplugin.addSortMethod(get_handle(),
                                 xbmcplugin.SORT_METHOD_VIDEO_RATING)
        if content_type != 'movies' and '/collection/' not in url:
            xbmcplugin.addSortMethod(get_handle(),
                                     xbmcplugin.SORT_METHOD_VIDEO_YEAR)
        xbmcplugin.addSortMethod(get_handle(),
                                 xbmcplugin.SORT_METHOD_VIDEO_RUNTIME)
        xbmcplugin.addSortMethod(get_handle(),
                                 xbmcplugin.SORT_METHOD_MPAA_RATING)
        xbmcplugin.setContent(get_handle(), content_type)
        xbmcplugin.addDirectoryItems(get_handle(), items, len(items))

    LOG.debug('PROCESS: It took %s seconds to process %s items' %
              (time.time() - start_time, len(items)))

    xbmcplugin.endOfDirectory(get_handle(),
                              cacheToDisc=context.settings.cache_directory())
def run():
    """
    Run the plugin.
    """
    params = get_params()
    try:
        url = unquote_plus(params["url"])
    except Exception:
        url = None
    try:
        name = unquote_plus(params["name"])
    except Exception:
        name = None
    try:
        mode = int(params["mode"])
    except Exception:
        mode = None
    try:
        page_hash = unquote_plus(params['page_hash'])
    except Exception:
        page_hash = None
    try:
        page = unquote_plus(params['page'])
    except Exception:
        page = None

    log('run, mode = %s, url = %s, name = %s, page_hash = %s, '
        'page = %s' % (mode, url, name, page_hash, page))

    if mode is None:
        identifiers = [
            'All_Shows',
            'Shows_Topics',
            'Favourite_Shows',
            'Newest_Favourite_Shows',
            'Radio_Channels',
            # 'Newest_Audios',
            'Most_Listened',
            'Search',
            'Live_Radio',
        ]
        SRFPlayRadio().build_main_menu(identifiers)
    elif mode == 10:
        SRFPlayRadio().build_shows_menu('radio')
    elif mode == 11:
        SRFPlayRadio().build_favourite_radio_shows_menu()
    elif mode == 12:
        SRFPlayRadio().build_newest_favourite_menu(page=page, audio=True)
    elif mode == 19:
        SRFPlayRadio().manage_favourite_shows(audio=True)
    elif mode == 20:
        SRFPlayRadio().build_show_menu(name, page_hash=page_hash, audio=True)
    elif mode == 21:
        SRFPlayRadio().build_episode_menu(name, audio=True)
    elif mode == 40:
        SRFPlayRadio().build_radio_channels_menu()
    elif mode == 41:
        SRFPlayRadio().build_radio_channel_overview(name)
    elif mode == 42:
        SRFPlayRadio().build_shows_menu('radio', channel_id=name)
    elif mode == 43:
        SRFPlayRadio().build_audio_menu('Newest', 43, name, page=page)
    elif mode == 44:
        SRFPlayRadio().build_audio_menu('Most clicked', 44, name, page=page)
    # elif mode == 45:
    #     SRFPlayRadio().build_audio_menu('Newest', 45, page=page)
    elif mode == 46:
        SRFPlayRadio().build_audio_menu('Most clicked', 46, page=page)
    elif mode == 27:
        SRFPlayRadio().build_search_menu(audio=True)
    elif mode == 28:
        SRFPlayRadio().build_search_media_menu(mode=mode,
                                               name=name,
                                               page=page,
                                               page_hash=page_hash,
                                               audio=True)
    elif mode == 29:
        SRFPlayRadio().build_search_show_menu(name=name, audio=True)
    elif mode == 47:
        SRFPlayRadio().build_live_radio_menu()
    elif mode == 48:
        SRFPlayRadio().build_radio_topics_menu()
    elif mode == 49:
        SRFPlayRadio().build_radio_shows_by_topic(name)
    elif mode == 50:
        SRFPlayRadio().play_video(name, audio=True)
    elif mode == 51:
        SRFPlayRadio().play_livestream(name)

    xbmcplugin.setContent(int(sys.argv[1]), CONTENT_TYPE)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_NONE)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)
    xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_TITLE)
    xbmcplugin.endOfDirectory(int(sys.argv[1]), cacheToDisc=True)
Esempio n. 11
0
    def add_video_item(self, video):
        # Create a list item with a text label and a thumbnail image.

        episode_no = video.get('sequence')
        episode_date = video.get('releaseDate')

        if episode_date:
            try:
                episode_date = datetime(*(time.strptime(
                    episode_date.split('T')[0], "%Y-%m-%d")[0:6]))
            except Exception as e:
                logger.warn(
                    'Failed to parse the episode date - {} -- {}'.format(
                        episode_date, str(e)))
                episode_date = None
                pass

        if episode_no == 0:
            if episode_date:
                title = u'{} | {}'.format(video['title'],
                                          episode_date.strftime('%d.%m.%Y'))
            else:
                title = u'{}'.format(video['title'])
            #title = u'{} | {}'.format(video['title'],episode_date.strftime('%d.%m.%Y') if episode_date else None)
        else:
            title = u'{} - {} | {}'.format(
                episode_no, video['title'],
                episode_date.strftime('%d.%m.%Y') if episode_date else None)

        type = video['type']
        if video['container'] is not None:
            VideoType = video['container'].get('type')
        else:
            VideoType = video.get('type')

        #web_pdb.set_trace()
        videoid = video['id']
        if video['stream']:
            if video['stream'].get('provider') == 'youtube':
                stream_url = 'https://www.youtube.com/embed/{}?autoplay=1&rel=0&modestbranding=1&playsinline=1&iv_load_policy=3&start=0&enablejsapi=1&origin=https://www.mxplayer.in&widgetid=1'.format(
                    video['stream']['youtube'].get('id'))
                weburl = resolveurl.HostedMediaFile(url=stream_url).resolve()
            elif video['stream']['sony'] is not None:
                weburl = video['stream']['sony'].get('hlsUrl')
            elif video['stream']['thirdParty'] is not None:
                weburl = video['stream']['thirdParty'].get('hlsUrl')
            elif video['stream']['altBalaji'] is not None:
                videoid = video['stream']['altBalaji'].get('dashId')
                weburl = video['stream']['altBalaji'].get('hlsUrl')
            elif video['stream']['hls'] is not None:
                if video['stream']['hls'].get('base') is not None:
                    base_url = video['stream']['hls'].get('base')
                else:
                    base_url = video['stream']['hls'].get('high')
                if base_url[:4] == 'http':
                    weburl = base_url
                else:
                    weburl = 'https://j2apps.s.llnwi.net/' + base_url
            elif video['stream']['mxplay']['hls'] is not None:
                weburl = video['stream']['mxplay']['hls'].get('main')

        list_item = xbmcgui.ListItem(label=title)

        # Set additional info for the list item.
        #web_pdb.set_trace()
        description = self.get_description(video)

        list_item.setInfo(
            'video', {
                'title': title,
                'genre': MxPlayerPlugin.get_genre(video),
                'episode': episode_no,
                'webUrl': weburl,
                'plot': description,
                'duration': video.get('duration'),
                'year': episode_date.year if episode_date else None,
                'date':
                episode_date.strftime('%d.%m.%Y') if episode_date else None,
                'mediatype': 'video',
            })

        # Set graphics (thumbnail, fanart, banner, poster, landscape etc.) for the list item.
        # Here we use the same image for all items for simplicity's sake.
        if VideoType != 'liveChannel':
            list_image, cover_image = MxPlayerPlugin.get_images(video)
            list_item.setArt({
                'poster': cover_image or list_image,
                'thumb': list_image or cover_image,
                'icon': list_image or cover_image,
                'fanart': list_image or cover_image,
            })

        # Set 'IsPlayable' property to 'true'.
        # This is mandatory for playable items!
        list_item.setProperty('IsPlayable', 'true')

        # Create a URL for a plugin recursive call.
        # Example: plugin://plugin.video.example/?action=play&video=http:
        # //www.vidsplay.com/wp-content/uploads/2017/04/crab.mp4
        url = self.get_url(action='play',
                           content_id=videoid,
                           video_url=weburl,
                           type=VideoType)

        # Add the list item to a virtual Kodi folder.
        # is_folder = False means that this item won't open any sub-list.
        is_folder = False

        # Add our item to the Kodi virtual folder listing.
        xbmcplugin.addDirectoryItem(self.handle, url, list_item, is_folder)
        xbmcplugin.setContent(self.handle, 'movies')
Esempio n. 12
0
from kodi_six import xbmc, xbmcplugin, xbmcaddon, xbmcvfs

from resources.lib import basics
from resources.lib.url_dispatcher import URL_Dispatcher
from resources.lib import utils
from resources.lib import favorites
from resources.lib import pin
from resources.lib.adultsite import AdultSite
from resources.lib.sites import *  # noqa

socket.setdefaulttimeout(60)

addon = basics.addon
content = 'movies' if addon.getSetting('content') == '0' else 'videos'
xbmcplugin.setContent(basics.addon_handle, content)
addon = xbmcaddon.Addon()
TRANSLATEPATH = xbmcvfs.translatePath if six.PY3 else xbmc.translatePath
progress = utils.progress
dialog = utils.dialog

url_dispatcher = URL_Dispatcher('main')

if addon.getSetting('custom_sites') == 'true':
    sys.path.append(basics.customSitesDir)
    for module_name in favorites.enabled_custom_sites():
        try:
            importlib.import_module(module_name)
        except Exception as e:
            utils.kodilog('{0} {1}: {2}'.format(utils.i18n('err_custom'),
                                                module_name, e))
Esempio n. 13
0
def show_search_box(name, url, language, mode):
    xbmcplugin.setContent(_plugin_handle, 'movies')
    keyb = xbmc.Keyboard('', 'Search for Movies')
    keyb.doModal()
    if (keyb.isConfirmed()):
        search_term = quote_plus(keyb.getText())
        if len(search_term) == 0:
            return
        postData = einthusanRedirectUrl+'/movie/results/?'+url+'&query=' + search_term
        headers={'Origin':einthusanRedirectUrl,'Referer':einthusanRedirectUrl+'/movie/browse/?'+url,'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
        htmlcontent = requests.get(postData, headers=headers).text
        matches = re.compile('<div class="block1">.*?href=".*?watch\/(.*?)\/\?lang=(.*?)".*?<img src="(.+?)".+?<h3>(.+?)<\/h3>.+?<p>(.+?)<span>(.+?)<\/span>.+?i class=(.+?)<p class=".*?synopsis">\s*(.+?)\s*<\/p><div class="professionals">(.+?)<\/div><\/div><div class="block3">.+?<span>Wiki<\/span>.+?<a(.+?)Trailer<\/span>').findall(htmlcontent)
        for id, lang, img, name, year, genre, ishd, synopsis, prof_content, trailer_content in matches:
            name = name.replace(",","").encode('ascii', 'ignore').decode('ascii')
            movie = str(name)+','+str(id)+','+lang+','
            if 'ultrahd' in ishd:
                movie = movie+'itshd,'+postData
            else:
                movie = movie+'itsnothd,'+postData
            image = 'https:' + img
            try:
                description = synopsis.encode('ascii', 'ignore').decode('ascii')
            except:
                description=""

            info = {
                'plot': html.unescape(html2text.html2text(description).replace('\n', ' ').replace('\r', '')),
                'genre': genre,
                'year': year,
                'title': html2text.html2text(name),
                'originaltitle': html2text.html2text(name),
                'mediatype': 'movie',
                'country': 'India',
                'cast': [],
                'director': [],
                'artist': []
            }

            prof_matches = re.compile('<input.+?<img src="(.+?)">.+?<p>(.+?)<\/p><label>(.+?)<\/label>').findall(prof_content)
            for prof_img, prof_name, prof_label in prof_matches:
                if (prof_label == 'Director'):
                    info['director'].append(prof_name)
                else:
                    info['cast'].append((prof_name, prof_label))

            try:
                trailer_link = re.search('href="(.+?)"', trailer_content)
                if trailer_link:
                    trailer_id = re.findall('^[^v]+v=(.{3,11}).*', trailer_link.group(0))[0]
                    info['trailer'] = 'plugin://plugin.video.youtube/play/?video_id=%s' % trailer_id
            except:
                pass

            addStream(name, movie, 2, image, lang, info)

        nextpage=re.findall('data-disabled="([^"]*)" href="(.+?)"', htmlcontent)[-1]
        if nextpage[0]!='true':
            nextPage_Url = einthusanRedirectUrl+nextpage[1]
            get_movies_and_music_videos_helper(name, nextPage_Url, language, 2)

        xbmcplugin.endOfDirectory(_plugin_handle, cacheToDisc=True)
Esempio n. 14
0
    def get_next_page(self,
                      mode,
                      url,
                      pattern,
                      site='',
                      parse=None,
                      pictures=False):

        try:
            dirlst = []
            icon = xbmc.translatePath(
                os.path.join('special://home/addons/script.adultflix.artwork',
                             'resources/art/main/next.png'))
            fanart = xbmc.translatePath(
                os.path.join('special://home/addons/script.adultflix.artwork',
                             'resources/art/%s/fanart.jpg' % site))
            if '|GOT_URL' in url:
                url = url.split('|GOT_URL')[0]
                dirlst.append({
                    'name': kodi.giveColor('Next Page -->', 'white'),
                    'url': url,
                    'mode': mode,
                    'icon': icon,
                    'fanart': fanart,
                    'description': 'Load More......',
                    'folder': True
                })
            else:
                r = client.request(url)
                url = re.findall(r'%s' % pattern, r)[0]
                if parse:
                    url = urljoin(parse, url)
                if '&amp;' in url: url = url.replace('&amp;', '&')
                dirlst.append({
                    'name': kodi.giveColor('Next Page -->', 'white'),
                    'url': url,
                    'mode': mode,
                    'icon': icon,
                    'fanart': fanart,
                    'description': 'Load More......',
                    'folder': True
                })
            if 'chaturbate' in url:
                if dirlst:
                    buildDirectory(dirlst, isVideo=True, chaturbate=True)
            elif pictures:
                if dirlst: buildDirectory(dirlst, pictures=True)
            else:
                if dirlst: buildDirectory(dirlst, isVideo=True)
        except Exception as e:
            log_utils.log(
                'Error getting next page for %s :: Error: %s' %
                (site.title(), str(e)), xbmc.LOGERROR)
            xbmcplugin.setContent(kodi.syshandle, 'movies')
            if 'chaturbate' in url:
                local_utils.setView('chaturbate')
            elif pictures:
                local_utils.setView('pictures')
            else:
                local_utils.setView('thumbs')
            xbmcplugin.endOfDirectory(kodi.syshandle, cacheToDisc=True)
Esempio n. 15
0
    def display(self):
        handle = _handle()
        items = [i for i in self.items if i]

        ep_sort = True
        last_show_name = ''

        item_types = {}

        if not items and self.no_items_label:
            label = _(self.no_items_label, _label=True)

            if self.no_items_method == 'dialog':
                gui.ok(label, heading=self.title)
                return resolve()
            else:
                items.append(Item(
                    label=label,
                    is_folder=False,
                ))

        count = 0.0
        for item in items:
            if self.thumb and not item.art.get('thumb'):
                item.art['thumb'] = self.thumb

            if self.fanart and not item.art.get('fanart'):
                item.art['fanart'] = self.fanart

            if not item.specialsort:
                media_type = item.info.get('mediatype')
                show_name = item.info.get('tvshowtitle')
                if media_type != 'episode' or not show_name or (
                        last_show_name and show_name != last_show_name):
                    ep_sort = False

                if not last_show_name:
                    last_show_name = show_name

                if media_type not in item_types:
                    item_types[media_type] = 0

                item_types[media_type] += 1
                count += 1

            li = item.get_li()
            xbmcplugin.addDirectoryItem(handle, item.path, li, item.is_folder)

        if self.content == 'AUTO':
            self.content = 'videos'

            if not settings.common_settings.getBool('video_folder_content',
                                                    False) and item_types:
                type_map = {
                    'movie': 'movies',
                    'tvshow': 'tvshows',
                    'season': 'tvshows',
                    'episode': 'episodes',
                }

                top_type = sorted(item_types,
                                  key=lambda k: item_types[k],
                                  reverse=True)[0]
                percent = (item_types[top_type] / count) * 100
                content_type = type_map.get(top_type)
                if percent > 70 and content_type:
                    self.content = content_type

        if self.content: xbmcplugin.setContent(handle, self.content)
        if self.title: xbmcplugin.setPluginCategory(handle, self.title)

        if not self.sort_methods:
            self.sort_methods = [
                xbmcplugin.SORT_METHOD_EPISODE,
                xbmcplugin.SORT_METHOD_UNSORTED, xbmcplugin.SORT_METHOD_LABEL,
                xbmcplugin.SORT_METHOD_VIDEO_YEAR,
                xbmcplugin.SORT_METHOD_DATEADDED,
                xbmcplugin.SORT_METHOD_PLAYCOUNT
            ]
            if not ep_sort:
                self.sort_methods.pop(0)

        for sort_method in self.sort_methods:
            xbmcplugin.addSortMethod(handle, sort_method)

        xbmcplugin.endOfDirectory(handle,
                                  succeeded=True,
                                  updateListing=self.updateListing,
                                  cacheToDisc=self.cacheToDisc)

        if self.show_news:
            process_news()
def setContent(ctype):
    if ctype:
        xbmcplugin.setContent(HANDLE, ctype)
def buildDir(items,
             content='dirs',
             cm=None,
             search=False,
             stopend=False,
             isVideo=False,
             isDownloadable=False,
             cache=True,
             chaturbate=False,
             pictures=False):
    if items == None or len(items) == 0:
        xbmc.executebuiltin('Dialog.Close(busydialog)')
        sys.exit()

    if cm is None: cm = []

    sysaddon = sys.argv[0]
    syshandle = int(sys.argv[1])

    if chaturbate:
        import sqlite3
        databases = translatePath(os.path.join(kodi.datafolder, 'databases'))
        chaturbatedb = translatePath(os.path.join(databases, 'chaturbate.db'))
        conn = sqlite3.connect(chaturbatedb)
        conn.text_factory = str
        c = conn.cursor()
        c.execute("SELECT * FROM chaturbate ORDER BY name ASC")
        chat_urls = []
        for (chat_name, chat_url, chat_icon) in c.fetchall():
            chat_urls.append(chat_url)
    for i in items:

        try:
            name = i['name']

            if 'file_path' not in name:
                try:
                    name = client.replaceHTMLCodes(name)
                    name = kodi.sortX(name)
                except:
                    pass
            else:
                name = name.replace('file_path', '')

            item = xbmcgui.ListItem(label=name)

            try:
                if i['description']: description = i['description']
            except:
                description = name

            try:
                description = client.replaceHTMLCodes(description)
                description = kodi.sortX(description)
            except:
                pass

            kodi.giveColor(description, 'white', True)
            if pictures:
                item.setInfo('picture', {'title': name, 'plot': description})
            else:
                item.setInfo('video', {'title': name, 'plot': description})

            try:
                name = quote_plus(name)
            except:
                name = name.replace(' ', '+')

            try:
                if i['url']: url = i['url']
                else: url = 'none'
            except:
                url = 'none'
            if i['icon'] == None: thumb = kodi.addonicon
            else: thumb = i['icon']
            if i['fanart'] == None: fanart = kodi.addonicon
            else: fanart = i['fanart']
            if (not thumb == 'local') and (not fanart == 'local'):
                item.setArt({'icon': thumb, 'thumb': thumb, 'fanart': fanart})
            else:
                item.setArt({'icon': url, 'thumb': url, 'fanart': fanart})

            try:
                if i['folder']: _folder = True
                else: _folder = False
            except:
                _folder = True

            try:
                if i['isDownloaded']: isDownloaded = True
                else: isDownloaded = False
            except:
                isDownloaded = False

            if not isDownloadable:
                try:
                    if i['isDownloadable']: isDownloadable = True
                    else: isDownloadable = False
                except:
                    isDownloadable = False

            if 'typeid=history' in url:
                url = url.replace('typeid=history', '')
                history = '%s?url=%s&mode=%s' \
                % (sysaddon,quote_plus(url),str('24'))
                htext = "Remove from History"
                cm.append(('%s' % htext, 'RunPlugin(' + history + ')'))

            if 'search_term=' in url:
                search_term = '%s?url=%s&mode=%s' \
                % (sysaddon,quote_plus(url),str('25'))
                stext = "Remove Search Term"
                cm.append(('%s' % stext, 'RunPlugin(' + search_term + ')'))
                url = url.replace('search_term=', '')

            u= '%s?url=%s&mode=%s&name=%s&iconimage=%s&fanart=%s' \
            % (sysaddon,quote_plus(url),str(i['mode']),name,quote_plus(thumb),quote_plus(fanart))

            if chaturbate:
                if '|CHAT|' in url: check_url = url.split('|CHAT|')[0]
                else: check_url = url.split('|SPLIT|')[0]
                log_utils.log('URL IS %s' % (check_url), log_utils.LOGERROR)
                if check_url in str(chat_urls): chat = 'del'
                else: chat = 'add'

                chat_compiled = '%s?url=%s&mode=%s&name=%s&iconimage=%s&chat=%s&chatmode=%s&folder=%s' \
                % (sysaddon,quote_plus(check_url),str('101'),name,quote_plus(thumb),chat,str(i['mode']),str(_folder))

                if chat == 'add': ctext = "Add to"
                elif chat == 'del': ctext = "Remove from"
                cm.append(('%s Chaturbate Monitoring' % ctext,
                           'RunPlugin(' + chat_compiled + ')'))

            try:
                if i['fav']: fav = i['fav']
                else: fav = 'add'
            except:
                fav = 'add'

            try:
                if i['cm']:
                    for cmitems in i['cm']:
                        log_utils.log('%s' % (cmitems[1]), log_utils.LOGNOTICE)
                        cm.append(('%s' % cmitems[0],
                                   'RunPlugin(' + cmitems[1] + ')'))
            except:
                pass

            favorite = '%s?url=%s&mode=%s&name=%s&iconimage=%s&fav=%s&favmode=%s&folder=%s' \
            % (sysaddon,quote_plus(url),str('100'),name,quote_plus(thumb),fav,str(i['mode']),str(_folder))

            if fav == 'add': ftext = "Add to"
            elif fav == 'del': ftext = "Remove from"
            cm.append(('%s %s Favorites' % (ftext, kodi.get_name()),
                       'RunPlugin(' + favorite + ')'))

            if isDownloadable:
                dwnld = '%s?url=%s&mode=%s&name=%s&iconimage=%s' \
                % (sysaddon,quote_plus(url),str('26'),name,quote_plus(thumb))
                cm.append((
                    'Download Video ( [COLOR red]Not Working Kodi19[/COLOR] )',
                    'RunPlugin(' + dwnld + ')'))
            if isDownloaded:
                rmdwnld = '%s?url=%s&mode=%s&name=%s' \
                % (sysaddon,quote_plus(url),str('28'),name)
                cm.append(('Delete Video', 'RunPlugin(' + rmdwnld + ')'))

            open_set = '%s?mode=%s' \
            % (sysaddon,str('19'))
            stext = "Open XXX-O-DUS Settings"
            cm.append(('%s' % stext, 'RunPlugin(' + open_set + ')'))

            if isDownloadable: view_type = 'thumb'
            elif pictures: view_type = 'picture'
            elif chaturbate: view_type = 'chaturbate'
            else: view_type = 'list'
            view_compile = '%s?mode=%s&name=%s' \
            % (sysaddon,str('44'),view_type)
            cm.append(
                ('Set %s to this view mode by default.' % view_type.title(),
                 'RunPlugin(' + view_compile + ')'))

            if cm:
                item.addContextMenuItems(cm, replaceItems=False)
                cm = []

            if isVideo:
                codec_info = {'codec': 'h264'}
                item.addStreamInfo('video', codec_info)

            xbmcplugin.addDirectoryItem(handle=syshandle,
                                        url=u,
                                        listitem=item,
                                        isFolder=_folder)

        except Exception as e:
            pass
        #dialog.ok("ERRROR",str(e))
        #log_utils.log('Error adding item %s in BuildDir function ( %s %s ):: Error: %s' % (name,u,thumb,str(e)), log_utils.LOGERROR)

    if not stopend:
        if chaturbate:
            xbmcplugin.setContent(kodi.syshandle, 'movies')
            setView('chaturbate')
        elif pictures:
            xbmcplugin.setContent(kodi.syshandle, 'movies')
            setView('pictures')
        elif isVideo:
            xbmcplugin.setContent(kodi.syshandle, 'movies')
            setView('thumbs')
        else:
            xbmcplugin.setContent(kodi.syshandle, 'movies')
            setView('list')
    if (not search) and (not stopend):
        if cache: xbmcplugin.endOfDirectory(syshandle, cacheToDisc=True)
        else: xbmcplugin.endOfDirectory(syshandle, cacheToDisc=False)
Esempio n. 18
0
def listing():
    ''' Display all jellyfin nodes and dynamic entries when appropriate.
    '''
    total = int(window('Jellyfin.nodes.total') or 0)
    sync = get_sync()
    whitelist = [x.replace('Mixed:', "") for x in sync['Whitelist']]
    servers = get_credentials()['Servers'][1:]

    for i in range(total):

        window_prop = "Jellyfin.nodes.%s" % i
        path = window('%s.index' % window_prop)

        if not path:
            path = window('%s.content' % window_prop) or window(
                '%s.path' % window_prop)

        label = window('%s.title' % window_prop)
        node = window('%s.type' % window_prop)
        artwork = window('%s.artwork' % window_prop)
        view_id = window('%s.id' % window_prop)
        context = []

        if view_id and node in ('movies', 'tvshows', 'musicvideos', 'music',
                                'mixed') and view_id not in whitelist:
            label = "%s %s" % (label, translate(33166))
            context.append((
                translate(33123),
                "RunPlugin(plugin://plugin.video.jellyfin/?mode=synclib&id=%s)"
                % view_id))

        if view_id and node in ('movies', 'tvshows', 'musicvideos',
                                'music') and view_id in whitelist:

            context.append((translate(
                33136
            ), "RunPlugin(plugin://plugin.video.jellyfin/?mode=updatelib&id=%s)"
                            % view_id))
            context.append((translate(
                33132
            ), "RunPlugin(plugin://plugin.video.jellyfin/?mode=repairlib&id=%s)"
                            % view_id))
            context.append((translate(
                33133
            ), "RunPlugin(plugin://plugin.video.jellyfin/?mode=removelib&id=%s)"
                            % view_id))

        LOG.debug("--[ listing/%s/%s ] %s", node, label, path)

        if path:
            directory(label, path, artwork=artwork, context=context)

    for server in servers:
        context = []

        if server.get('ManualAddress'):
            context.append((translate(
                33141
            ), "RunPlugin(plugin://plugin.video.jellyfin/?mode=removeserver&server=%s)"
                            % server['Id']))

        if 'AccessToken' not in server:
            directory("%s (%s)" % (server['Name'], translate(30539)),
                      "plugin://plugin.video.jellyfin/?mode=login&server=%s" %
                      server['Id'],
                      False,
                      context=context)
        else:
            directory(server['Name'],
                      "plugin://plugin.video.jellyfin/?mode=browse&server=%s" %
                      server['Id'],
                      context=context)

    directory(translate(33194),
              "plugin://plugin.video.jellyfin/?mode=managelibs", True)
    directory(translate(33134),
              "plugin://plugin.video.jellyfin/?mode=addserver", False)
    directory(translate(33054), "plugin://plugin.video.jellyfin/?mode=adduser",
              False)
    directory(translate(5), "plugin://plugin.video.jellyfin/?mode=settings",
              False)
    directory(translate(33161),
              "plugin://plugin.video.jellyfin/?mode=updatepassword", False)
    directory(translate(33058), "plugin://plugin.video.jellyfin/?mode=reset",
              False)
    directory(translate(33180),
              "plugin://plugin.video.jellyfin/?mode=restartservice", False)

    if settings('backupPath'):
        directory(translate(33092),
                  "plugin://plugin.video.jellyfin/?mode=backup", False)

    xbmcplugin.setContent(PROCESS_HANDLE, 'files')
    xbmcplugin.endOfDirectory(PROCESS_HANDLE)
Esempio n. 19
0
    # To to get translated strings
    S = LocalizedStringID(addon.getLocalizedString)

    video_res = [1080, 720, 480, 360, 240][int(addon.getSetting(SettingID.RESOLUTION))]
    subtitle_setting = addon.getSetting(SettingID.SUBTITLES) == 'true'
    global_lang = addon.getSetting(SettingID.LANGUAGE) or 'E'

    # The awkward way Kodi passes arguments to the add-on...
    # argv[2] is a URL query string, probably passed by request_to_self()
    # example: ?mode=play&media=ThisVideo
    args = parse_qs(sys.argv[2][1:])
    # parse_qs puts the values in a list, so we grab the first value for each key
    args = {k: v[0] for k, v in args.items()}

    # Tested in Kodi 18: This will disable all viewtypes but list and icons won't be displayed within the list
    xbmcplugin.setContent(addon_handle, 'files')

    mode = args.get(Q.MODE)

    if mode is None:
        top_level_page()
    elif mode == M.LANGUAGES:
        language_dialog(args.get(Q.MEDIAKEY))
    elif mode == M.SET_LANG:
        set_language(args[Q.LANGCODE], args[Q.LANGNAME])
    elif mode == M.HIDDEN:
        hidden_media_dialog(args[Q.MEDIAKEY])
    elif mode == M.SEARCH:
        search_page()
    elif mode == M.PLAY:
        resolve_media(args[Q.MEDIAKEY], args.get(Q.LANGCODE))
Esempio n. 20
0
def get_next_episodes(item_id, limit):
    ''' Only for synced content.
    '''
    with Database('jellyfin') as jellyfindb:

        db = jellyfin_db.JellyfinDatabase(jellyfindb.cursor)
        library = db.get_view_name(item_id)

        if not library:
            return

    result = JSONRPC('VideoLibrary.GetTVShows').execute({
        'sort': {
            'order': "descending",
            'method': "lastplayed"
        },
        'filter': {
            'and': [{
                'operator': "true",
                'field': "inprogress",
                'value': ""
            }, {
                'operator': "is",
                'field': "tag",
                'value': "%s" % library
            }]
        },
        'properties': ['title', 'studio', 'mpaa', 'file', 'art']
    })

    try:
        items = result['result']['tvshows']
    except (KeyError, TypeError):
        return

    list_li = []

    for item in items:
        if settings('ignoreSpecialsNextEpisodes.bool'):
            params = {
                'tvshowid':
                item['tvshowid'],
                'sort': {
                    'method': "episode"
                },
                'filter': {
                    'and': [{
                        'operator': "lessthan",
                        'field': "playcount",
                        'value': "1"
                    }, {
                        'operator': "greaterthan",
                        'field': "season",
                        'value': "0"
                    }]
                },
                'properties': [
                    "title", "playcount", "season", "episode", "showtitle",
                    "plot", "file", "rating", "resume", "tvshowid", "art",
                    "streamdetails", "firstaired", "runtime", "writer",
                    "dateadded", "lastplayed"
                ],
                'limits': {
                    "end": 1
                }
            }
        else:
            params = {
                'tvshowid':
                item['tvshowid'],
                'sort': {
                    'method': "episode"
                },
                'filter': {
                    'operator': "lessthan",
                    'field': "playcount",
                    'value': "1"
                },
                'properties': [
                    "title", "playcount", "season", "episode", "showtitle",
                    "plot", "file", "rating", "resume", "tvshowid", "art",
                    "streamdetails", "firstaired", "runtime", "writer",
                    "dateadded", "lastplayed"
                ],
                'limits': {
                    "end": 1
                }
            }

        result = JSONRPC('VideoLibrary.GetEpisodes').execute(params)

        try:
            episodes = result['result']['episodes']
        except (KeyError, TypeError):
            pass
        else:
            for episode in episodes:

                li = create_listitem(episode)
                list_li.append((episode['file'], li))

        if len(list_li) == limit:
            break

    xbmcplugin.addDirectoryItems(PROCESS_HANDLE, list_li, len(list_li))
    xbmcplugin.setContent(PROCESS_HANDLE, 'episodes')
    xbmcplugin.endOfDirectory(PROCESS_HANDLE)
Esempio n. 21
0
def artifisial():
    addDir('[B]Machine learning[/B]', BASEURL + 'subject/machine-learning/', 5,
           ICON, FANART, '')
    xbmcplugin.setContent(int(sys.argv[1]), 'movies')