Example #1
0
def library_thread():
    trakt_sync = int(ADDON.getSetting("trakt_sync"))
    if trakt_sync > 0:
        limit = trakt_sync * 3600
        count = limit - int(ADDON.getSetting("library_update_delay"))
        while not xbmc.abortRequested:
            # trakt_sync hours passed - Update Library
            if count >= limit:
                count = 0
                try:
                    urllib2.urlopen(
                        QUASARD_HOST +
                        "/library/movie/watchlist/add?updating=true")
                    urllib2.urlopen(
                        QUASARD_HOST +
                        "/library/movie/collection/add?updating=true")
                    urllib2.urlopen(
                        QUASARD_HOST +
                        "/library/show/watchlist/add?updating=true")
                    urllib2.urlopen(
                        QUASARD_HOST +
                        "/library/show/collection/add?updating=true")
                    with closing(
                            urllib2.urlopen(QUASARD_HOST +
                                            "/library/userlists")) as response:
                        data = json.loads(response.read())
                        for userlist in data:
                            urllib2.urlopen(
                                QUASARD_HOST +
                                "/library/movie/list/add/%d?updating=true" %
                                userlist['IDs']['trakt'])
                            urllib2.urlopen(
                                QUASARD_HOST +
                                "/library/show/list/add/%d?updating=true" %
                                userlist['IDs']['trakt'])
                    urllib2.urlopen(QUASARD_HOST + "/library/update")
                except:
                    pass
            time.sleep(5)
            count += 5
    else:
        limit = int(ADDON.getSetting("library_update_frequency")) * 3600
        count = limit - int(ADDON.getSetting("library_update_delay"))
        while not xbmc.abortRequested:
            # library_update_frequency hours passed - Update Library
            if count >= limit:
                count = 0
                try:
                    urllib2.urlopen(QUASARD_HOST + "/library/update")
                except:
                    pass
            time.sleep(5)
            count += 5
Example #2
0
 def __init__(self, w=OVERLAY_WIDTH, h=OVERLAY_HEIGHT, *args, **kwargs):
     self.window = xbmcgui.Window(WINDOW_FULLSCREEN_VIDEO)
     viewport_w, viewport_h = self._get_skin_resolution()
     # Adjust size based on viewport, we are using 1080p coordinates
     w = int(w * viewport_w / VIEWPORT_WIDTH)
     h = int(h * viewport_h / VIEWPORT_HEIGHT)
     x = (viewport_w - w) / 2
     y = (viewport_h - h) / 2 + int(
         ADDON.getSetting(id="overlay_status_offset"))
     self._shown = False
     self._text = ""
     self._label = xbmcgui.ControlLabel(x,
                                        y,
                                        w,
                                        h,
                                        self._text,
                                        alignment=XBFONT_CENTER_X
                                        | XBFONT_CENTER_Y,
                                        *args,
                                        **kwargs)
     self._shadow = xbmcgui.ControlLabel(x + 1,
                                         y + 1,
                                         w,
                                         h,
                                         self._text,
                                         textColor='0xD0000000',
                                         alignment=XBFONT_CENTER_X
                                         | XBFONT_CENTER_Y,
                                         *args,
                                         **kwargs)
     self._background = xbmcgui.ControlImage(
         x, y, w, h,
         os.path.join(ADDON_PATH, "resources", "img",
                      "black.png").encode('utf-8'))
     self._background.setColorDiffuse("0xD0000000")
Example #3
0
    def AddonFailure(self, addonId):
        if ADDON.getSetting("provider_disable_failing") == u"false":
            return 0

        if addonId in self._failures:
            self._failures[addonId] += 1
        else:
            self._failures[addonId] = 1

        log.warning("Recorded failure %d for %s" % (self._failures[addonId], addonId))

        if self._failures[addonId] > int(ADDON.getSetting("provider_allowed_failures")):
            try:
                time.sleep(10)
                notify(getLocalizedString(30111))
                urllib2.urlopen("%s/provider/%s/disable" % (QUASARD_HOST, addonId))
            except:
                notify(getLocalizedString(30112))
                return 0
        return self._failures[addonId]
Example #4
0
    def AddonFailure(self, addonId):
        if ADDON.getSetting("provider_disable_failing") == u"false":
            return 0

        if addonId in self._failures:
            self._failures[addonId] += 1
        else:
            self._failures[addonId] = 1

        log.warning("Recorded failure %d for %s" % (self._failures[addonId], addonId))

        if self._failures[addonId] > int(ADDON.getSetting("provider_allowed_failures")):
            try:
                time.sleep(10)
                notify(ADDON.getLocalizedString(30111).encode('utf-8'))
                urllib2.urlopen("%s/provider/%s/disable" % (QUASARD_HOST, addonId))
            except:
                notify(ADDON.getLocalizedString(30112).encode('utf-8'))
                return 0
        return self._failures[addonId]
Example #5
0
 def GetAllSettings(self):
     settings = []
     settingsFile = os.path.join(ADDON.getAddonInfo("path"), "resources", "settings.xml")
     with open(settingsFile, 'r') as settingsStr:
         fileContent = settingsStr.read()
         keyType = re.findall(r".*id=\"(\w+)\".*type=\"(\w+)\"", fileContent)
     for key, _type in keyType:
         settings.append({
             "key": key,
             "type": _type,
             "value": ADDON.getSetting(key)
         })
     return settings
Example #6
0
def library_thread():
    limit = 8 * 60 * 60
    count = limit - int(ADDON.getSetting("library_update_delay"))
    while not xbmc.abortRequested:
        # 8 hours passed - Update Library
        if count >= limit:
            count = 0
            try:
                urllib2.urlopen(QUASARD_HOST + "/library/update")
            except:
                pass
        time.sleep(3)
        count += 3
Example #7
0
 def __init__(self, w=OVERLAY_WIDTH, h=OVERLAY_HEIGHT, *args, **kwargs):
     self.window = xbmcgui.Window(WINDOW_FULLSCREEN_VIDEO)
     viewport_w, viewport_h = self._get_skin_resolution()
     # Adjust size based on viewport, we are using 1080p coordinates
     w = int(w * viewport_w / VIEWPORT_WIDTH)
     h = int(h * viewport_h / VIEWPORT_HEIGHT)
     x = (viewport_w - w) / 2
     y = (viewport_h - h) / 2 + int(ADDON.getSetting(id="overlay_status_offset"))
     self._shown = False
     self._text = ""
     self._label = xbmcgui.ControlLabel(x, y, w, h, self._text, alignment=XBFONT_CENTER_X | XBFONT_CENTER_Y, *args, **kwargs)
     self._background = xbmcgui.ControlImage(x, y, w, h, os.path.join(RESOURCES_PATH, "img", "black.png"))
     self._background.setColorDiffuse("0xD0000000")
Example #8
0
def library_thread():
    limit = 8 * 60 * 60
    count = limit - int(ADDON.getSetting("library_update_delay"))
    while not xbmc.abortRequested:
        # 8 hours passed - Update Library
        if count >= limit:
            count = 0
            try:
                urllib2.urlopen(QUASARD_HOST + "/library/update")
            except:
                pass
        time.sleep(3)
        count += 3
Example #9
0
 def GetAllSettings(self):
     settings = []
     settingsFile = os.path.join(ADDON_PATH, "resources", "settings.xml")
     with open(settingsFile, 'r') as settingsStr:
         fileContent = settingsStr.read()
         keyType = re.findall(r".*id=\"(\w+)\".*type=\"(\w+)\"(.*option=\"(\w+)\")?", fileContent)
     for key, _type, optgroup, option in keyType:
         settings.append({
             "key": key,
             "type": _type,
             "option": option,
             "value": ADDON.getSetting(key)
         })
     return settings
Example #10
0
 def GetAllSettings(self):
     settings = []
     settingsFile = os.path.join(ADDON_PATH, "resources", "settings.xml")
     with open(settingsFile, 'r') as settingsStr:
         fileContent = settingsStr.read()
         keyType = re.findall(r".*id=\"(\w+)\".*type=\"(\w+)\"(.*option=\"(\w+)\")?", fileContent)
     for key, _type, optgroup, option in keyType:
         settings.append({
             "key": key,
             "type": _type,
             "option": option,
             "value": ADDON.getSetting(key)
         })
     return settings
Example #11
0
def library_thread():
    trakt_sync = int(ADDON.getSetting("trakt_sync"))
    if trakt_sync > 0:
        limit = trakt_sync * 3600
        count = limit - int(ADDON.getSetting("library_update_delay"))
        while not xbmc.abortRequested:
            # trakt_sync hours passed - Update Library
            if count >= limit:
                count = 0
                try:
                    urllib2.urlopen(QUASARD_HOST + "/library/movie/watchlist/add?updating=true")
                    urllib2.urlopen(QUASARD_HOST + "/library/movie/collection/add?updating=true")
                    urllib2.urlopen(QUASARD_HOST + "/library/show/watchlist/add?updating=true")
                    urllib2.urlopen(QUASARD_HOST + "/library/show/collection/add?updating=true")
                    with closing(urllib2.urlopen(QUASARD_HOST + "/library/userlists")) as response:
                        data = json.loads(response.read())
                        for userlist in data:
                            urllib2.urlopen(QUASARD_HOST + "/library/movie/list/add/%d?updating=true" % userlist['IDs']['trakt'])
                            urllib2.urlopen(QUASARD_HOST + "/library/show/list/add/%d?updating=true" % userlist['IDs']['trakt'])
                    urllib2.urlopen(QUASARD_HOST + "/library/update")
                except:
                    pass
            time.sleep(5)
            count += 5
    else:
        limit = int(ADDON.getSetting("library_update_frequency")) * 3600
        count = limit - int(ADDON.getSetting("library_update_delay"))
        while not xbmc.abortRequested:
            # library_update_frequency hours passed - Update Library
            if count >= limit:
                count = 0
                try:
                    urllib2.urlopen(QUASARD_HOST + "/library/update")
                except:
                    pass
            time.sleep(5)
            count += 5
Example #12
0
 def GetAllSettings(self):
     settings = []
     settingsFile = os.path.join(ADDON.getAddonInfo("path"), "resources",
                                 "settings.xml")
     with open(settingsFile, 'r') as settingsStr:
         fileContent = settingsStr.read()
         keyType = re.findall(r".*id=\"(\w+)\".*type=\"(\w+)\"",
                              fileContent)
     for key, _type in keyType:
         settings.append({
             "key": key,
             "type": _type,
             "value": ADDON.getSetting(key)
         })
     return settings
Example #13
0
def get_setting(key, converter=str, choices=None):
    value = ADDON.getSetting(id=key)
    if converter is str:
        return value
    elif converter is unicode:
        return value.decode('utf-8')
    elif converter is bool:
        return value == 'true'
    elif converter is int:
        return int(value)
    elif isinstance(choices, (list, tuple)):
        return choices[int(value)]
    else:
        raise TypeError('Acceptable converters are str, unicode, bool and '
                        'int. Acceptable choices are instances of list '
                        ' or tuple.')
def get_setting(key, converter=str, choices=None):
    value = ADDON.getSetting(id=key)
    if converter is str:
        return value
    elif converter is unicode:
        return value.decode('utf-8')
    elif converter is bool:
        return value == 'true'
    elif converter is int:
        return int(value)
    elif isinstance(choices, (list, tuple)):
        return choices[int(value)]
    else:
        raise TypeError('Acceptable converters are str, unicode, bool and '
                        'int. Acceptable choices are instances of list '
                        ' or tuple.')
Example #15
0
 def GetSetting(self, *args, **kwargs):
     return ADDON.getSetting(*args, **kwargs)
def run(url_suffix=""):
    if not os.path.exists(os.path.join(ADDON_PATH, ".firstrun")):
        notify(getLocalizedString(30101))
        system_information()
        return

    donatePath = os.path.join(ADDON_PATH, ".donate")
    if not os.path.exists(donatePath):
        with open(donatePath, "w"):
            os.utime(donatePath, None)
        dialog = xbmcgui.Dialog()
        dialog.ok("Quasar", getLocalizedString(30141))

    socket.setdefaulttimeout(int(ADDON.getSetting("buffer_timeout")))
    urllib2.install_opener(urllib2.build_opener(NoRedirectHandler()))

    url = sys.argv[0].replace("plugin://%s" % ADDON_ID, QUASARD_HOST + url_suffix) + sys.argv[2]
    log.debug("Requesting %s from %s" % (url, repr(sys.argv)))

    try:
        data = _json(url)
    except urllib2.URLError as e:
        if '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 = unicode(e)
        except:
            try:
                msg = str(e)
            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)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_DATE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_GENRE)
        xbmcplugin.setContent(HANDLE, content_type)

    listitems = range(len(data["items"]))
    for i, item in enumerate(data["items"]):
        # Translate labels
        if item["label"][0:8] == "LOCALIZE":
            item["label"] = unicode(getLocalizedLabel(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"] != unicode(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])
            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=True)
Example #17
0
File: rpc.py Project: Jaloga/xiaomi
 def GetSetting(self, *args, **kwargs):
     return ADDON.getSetting(*args, **kwargs)
Example #18
0
def notify(message, header=ADDON_NAME, time=5000, image=ADDON_ICON):
    sound = ADDON.getSetting('do_not_disturb') == 'false'
    dialog = xbmcgui.Dialog()
    return dialog.notification(toUtf8(header), toUtf8(message), toUtf8(image), time, sound)
Example #19
0
def run(url_suffix=""):
    if not os.path.exists(os.path.join(xbmc.translatePath(ADDON.getAddonInfo("path")), ".firstrun")):
        notify(getLocalizedString(30101))
        system_information()
        return

    socket.setdefaulttimeout(300)
    urllib2.install_opener(urllib2.build_opener(NoRedirectHandler()))

    url = sys.argv[0].replace("plugin://%s" % ADDON_ID, QUASARD_HOST + url_suffix) + sys.argv[2]
    log.info("Requesting %s from %s" % (url, repr(sys.argv)))

    try:
        data = _json(url)
    except Exception as e:
        map(log.error, traceback.format_exc().split("\n"))
        notify("%s: %s" % (getLocalizedString(30225), repr(e).encode('utf-8')))
        return

    if not data:
        return

    if data["content_type"]:
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_UNSORTED)
        if data["content_type"] != "tvshows":
            xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_DATE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_GENRE)
        xbmcplugin.setContent(HANDLE, data["content_type"])

    listitems = 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 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"])
        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"])
        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)
Example #20
0
def run(url_suffix=""):
    if not os.path.exists(os.path.join(ADDON_PATH, ".firstrun")):
        notify(getLocalizedString(30101))
        system_information()
        return

    donatePath = os.path.join(ADDON_PATH, ".donate")
    if not os.path.exists(donatePath):
        with open(donatePath, "w"):
            os.utime(donatePath, None)
        dialog = xbmcgui.Dialog()
        dialog.ok("Quasar", getLocalizedString(30141))

    socket.setdefaulttimeout(int(ADDON.getSetting("buffer_timeout")))
    urllib2.install_opener(urllib2.build_opener(NoRedirectHandler()))

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

    url = sys.argv[0].replace("plugin://%s" % ADDON_ID, QUASARD_HOST + url_suffix) + sys.argv[2]
    log.debug("Requesting %s from %s" % (url, repr(sys.argv)))

    try:
        data = _json(url)
    except urllib2.URLError as e:
        if 'Connection refused' in e.reason:
            notify(getLocalizedString(30116), time=7000)
        else:
            import traceback
            list(map(log.error, traceback.format_exc().split("\n")))
            notify(e.reason, time=7000)
        return
    except Exception as e:
        import traceback
        list(map(log.error, traceback.format_exc().split("\n")))
        try:
            msg = unicode(e)
        except:
            try:
                msg = str(e)
            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":
            if not PY3:
                item["label"] = unicode(getLocalizedLabel(item["label"]), 'utf-8')
            else:
                item["label"] = getLocalizedLabel(item["label"])
                if isinstance(item["label"], bytes):
                    item["label"] = item["label"].decode("utf8")
        if item["label2"][0:8] == "LOCALIZE":
            item["label2"] = getLocalizedLabel(item["label2"])

        listItem = xbmcgui.ListItem(label=item["label"], label2=item["label2"])
        listItem.setArt({'icon': item["icon"]})
        listItem.setArt({'thumb': item["thumbnail"]})
        if item.get("info"):
            listItem.setInfo("video", item["info"])
        if item.get("stream_info"):
            for type_, values in list(item["stream_info"].items()):
                listItem.addStreamInfo(type_, values)
        if item.get("art"):
            listItem.setArt(item["art"])
        elif ADDON.getSetting('default_fanart') == 'true' and ((not PY3 and item["label"] != unicode(getLocalizedString(30218), 'utf-8')) or (PY3 and item["label"] != str(getLocalizedString(30218)))):
            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])
            listItem.addContextMenuItems(item["context_menu"])
        listItem.setProperty("isPlayable", item["is_playable"] and "true" or "false")
        if item.get("properties"):
            for k, v in list(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)
def run(url_suffix=""):
    if not os.path.exists(
            os.path.join(xbmc.translatePath(ADDON.getAddonInfo("path")),
                         ".firstrun")):
        notify(getLocalizedString(30101))
        system_information()
        return

    socket.setdefaulttimeout(300)
    urllib2.install_opener(urllib2.build_opener(NoRedirectHandler()))

    url = sys.argv[0].replace("plugin://%s" % ADDON_ID,
                              QUASARD_HOST + url_suffix) + sys.argv[2]
    log.info("Requesting %s from %s" % (url, repr(sys.argv)))

    try:
        data = _json(url)
    except Exception as e:
        map(log.error, traceback.format_exc().split("\n"))
        notify("%s: %s" % (getLocalizedString(30225), repr(e).encode('utf-8')))
        return

    if not data:
        return

    if data["content_type"]:
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_UNSORTED)
        xbmcplugin.addSortMethod(HANDLE,
                                 xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_DATE)
        xbmcplugin.addSortMethod(HANDLE, xbmcplugin.SORT_METHOD_GENRE)
        xbmcplugin.setContent(HANDLE, data["content_type"])

    listitems = 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 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"])
        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"])
        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)
Example #22
0
def notify(message, header=ADDON_NAME, time=5000, image=ADDON_ICON):
    sound = ADDON.getSetting('do_not_disturb') == 'false'
    dialog = xbmcgui.Dialog()
    return dialog.notification(toUtf8(header), toUtf8(message), toUtf8(image), time, sound)