Example #1
0
def track_list(tracks):
    xbmcplugin.setContent(plugin.handle, 'songs')
    list_items = []
    for track in tracks:
        if not track.available:
            continue
        url = plugin.url_for(play, track_id=track.id)
        li = ListItem(track.name)
        li.setProperty('isplayable', 'true')
        li.setInfo(
            'music', {
                'title':
                track.name,
                'tracknumber':
                track.track_num,
                'discnumber':
                track.disc_num,
                'artist':
                track.artist.name,
                'album':
                track.album.name,
                'year':
                track.album.release_date.year
                if track.album.release_date else None,
            })
        if track.album:
            li.setThumbnailImage(track.album.image)
        radio_url = plugin.url_for(track_radio, track_id=track.id)
        li.addContextMenuItems([(
            'Track Radio',
            'XBMC.Container.Update(%s)' % radio_url,
        )])
        list_items.append((url, li, False))
    xbmcplugin.addDirectoryItems(plugin.handle, list_items)
    xbmcplugin.endOfDirectory(plugin.handle)
Example #2
0
def list_channels(cat_id=None):
    list_items = []
    r = s.get(list_url.format(cat_id),
              headers={"User-Agent": user_agent},
              timeout=10)
    res = r.json(strict=False)

    refresh_streams = "RunPlugin({0})".format(plugin.url_for(refresh))
    for ch in res["LIVETV"]:
        image = thumb_url.format(ch["channel_thumbnail"], quote(user_agent))
        li = ListItem(ch["channel_title"])
        li.setProperty("IsPlayable", "true")
        li.addContextMenuItems([("Refresh Streams", refresh_streams)])
        li.setArt({"thumb": image, "icon": image})
        li.setInfo(type="Video",
                   infoLabels={
                       "Title": ch["channel_title"],
                       "mediatype": "video",
                       "playcount": 0
                   })
        try:
            li.setContentLookup(False)
        except AttributeError:
            pass
        url = plugin.url_for(play, cat_id=cat_id, channel_id=ch.get("id"))
        list_items.append((url, li, False))

    xbmcplugin.addDirectoryItems(plugin.handle, list_items)
    xbmcplugin.endOfDirectory(plugin.handle)
Example #3
0
def _():
    edb.connect()
    idb.connect()
    items = []

    for path in edb.fetchall():
        drama = drama_detail(path)
        item = ListItem(drama['title'])
        item.addContextMenuItems([
            (localized_str(33100),
             'RunPlugin(plugin://plugin.video.dramacool/recently-viewed?delete='
             + path + ')'),
            (localized_str(33101),
             'RunPlugin(plugin://plugin.video.dramacool/recently-viewed?delete=%)'
             )
        ])
        item.setArt({'poster': drama.pop('poster')})
        item.setInfo('video', drama)
        items.append((plugin.url_for(path), item, True))

    edb.close()
    idb.close()
    xbmcplugin.setContent(plugin.handle, 'videos')
    xbmcplugin.addDirectoryItems(plugin.handle, items, len(items))
    xbmcplugin.endOfDirectory(plugin.handle)
Example #4
0
def list_channels(cat_id=None):
    list_items = []
    headers = {"Connection": "Keep-Alive", "Accept-Encoding": "gzip"}
    req = requests.Request("GET", list_url.format(cat_id), headers=headers)
    prepped = req.prepare()
    r = s.send(prepped, timeout=10)
    res = r.json(strict=False)

    refresh_streams = "RunPlugin({0})".format(plugin.url_for(refresh))
    for ch in res["LIVETV"]:
        image = "{0}|User-Agent={1}".format(ch["channel_thumbnail"],
                                            quote(user_agent))
        li = ListItem(ch["channel_title"])
        li.setProperty("IsPlayable", "true")
        li.addContextMenuItems([("Refresh Streams", refresh_streams)])
        li.setArt({"thumb": image, "icon": image})
        li.setInfo(type="Video",
                   infoLabels={
                       "Title": ch["channel_title"],
                       "mediatype": "video"
                   })
        li.setContentLookup(False)
        url = plugin.url_for(play, cat_id=cat_id, channel_id=ch.get("id"))
        list_items.append((url, li, False))

    xbmcplugin.addDirectoryItems(plugin.handle, list_items)
    xbmcplugin.endOfDirectory(plugin.handle)
Example #5
0
def recently_viewed(delete=None):
    ExternalDatabase.connect()
    InternalDatabase.connect()

    if delete is not None:
        ExternalDatabase.remove(delete)
        xbmc.executebuiltin('Container.Refresh')
    else:
        items = []

        for path in ExternalDatabase.fetchall():
            drama = drama_detail(path)
            item = ListItem(drama['title'])
            item.addContextMenuItems([(
                'Remove',
                'RunPlugin(plugin://plugin.video.dramacool/recently-viewed?delete='
                + path + ')')])
            item.setArt({'poster': drama.pop('poster')})
            item.setInfo('video', drama)
            items.append((plugin.url_for(path), item, True))

        xbmcplugin.setContent(plugin.handle, 'videos')
        xbmcplugin.addDirectoryItems(plugin.handle, items, len(items))
        xbmcplugin.endOfDirectory(plugin.handle)

    ExternalDatabase.close()
    InternalDatabase.close()
Example #6
0
def watchlist():
    page = int(plugin.args.get('page', [1])[0])
    length = plugin.args.get('page_length', [20])[0]
    wl = session.get_watchlist(page_length=length, page=page)
    for i in wl.items:
        pan = i.panel
        li = ListItem('{} {} ({})'.format(pan.title, pan.lang,
                                          capwords(pan.channel_id)))

        delete_link = i.actions.get('watchlist/delete')
        my_log(
            "Available actions for {} are {}.".format(i.panel.id, i.actions),
            xbmc.LOGDEBUG)
        if delete_link:
            my_log("Found delete_link.", xbmc.LOGDEBUG)
            wl_id = delete_link.split('/')[-1]
            remove_url = plugin.url_for(delete_from_watchlist, wlid=wl_id)
            my_log("remove_url is {}".format(remove_url), xbmc.LOGDEBUG)
            context_items = [(('Remove from watchlist',
                               "XBMC.RunPlugin({})".format(remove_url)))]
            li.addContextMenuItems(context_items)
        handle_panel(i.panel, li, set_menu=False)
    if wl.links.get('next'):
        li = ListItem('More...')
        page += 1
        xbmcplugin.addDirectoryItem(
            plugin.handle, plugin.url_for(watchlist, page=page, start=length),
            li, True)

    xbmcplugin.endOfDirectory(plugin.handle)
Example #7
0
def list_addonitems(addon):
    xbmcplugin.setContent(addon_handle, "movies")
    txtfile = profile + "list.txt"
    if xbmcvfs.exists(txtfile):
        with open(txtfile) as f:
            lines = f.readlines()
        nbr = 0
        for line in lines:
            item = line.split(chr(9))
            if len(item) > 3 and nbr < list_size and (item[3] == addon
                                                      or addon == '*'):
                desc = ''
                if show_date == "true" and len(item) > 4:
                    desc = desc + item[4].strip() + ' '
                if show_time == "true" and len(item) > 5:
                    desc = desc + item[5].strip() + ' '
                desc = desc + item[0]
                li = ListItem(label=desc)
                li.setInfo(type="Video", infoLabels={"Title": desc})
                li.setProperty('IsPlayable', 'true')
                command = []
                command.append((lang(
                    30008
                ), "XBMC.RunPlugin(plugin://plugin.video.last_played?menu=remove&id="
                                + str(nbr) + ")"))
                nbr = nbr + 1
                li.addContextMenuItems(command)
                li.setArt({"poster": item[2].strip()})
                addDirectoryItem(addon_handle, item[1].strip(), li, False)
        endOfDirectory(addon_handle)
Example #8
0
def list_channels(cat=None):
    playback_mode = addon.getSetting("playback_mode")
    names = []
    list_items = []
    for channel in TV.get_channels_by_category(cat, cache_time):
        title = channel.name
        if title in names:
            continue
        else:
            names.append(title)
        image = channel.img
        li = ListItem(title)
        li.setProperty("IsPlayable", "true")
        li.setArt({"thumb": image, "icon": image})
        li.setInfo(type="Video", infoLabels={"Title": title, "mediatype": "video"})
        li.setContentLookup(False)
        if playback_mode == "HLS":
            url = plugin.url_for(play, cat=cat, channel_id=channel._id)
        elif playback_mode == "RTMFP":
            url = plugin.url_for(play_rtmfp, cat=cat, channel_id=channel._id)
            fallback_url = plugin.url_for(play_netgroup, cat=cat, channel_id=channel._id)
            li.addContextMenuItems([("Play RTMFP Netgroup (P2P)", "PlayMedia({0})".format(fallback_url))])
        else:
            url = plugin.url_for(play_netgroup, cat=cat, channel_id=channel._id)
            fallback_url = plugin.url_for(play_rtmfp, cat=cat, channel_id=channel._id)
            li.addContextMenuItems([("Play RTMFP", "PlayMedia({0})".format(fallback_url))])
        list_items.append((url, li, False))
    xbmcplugin.addDirectoryItems(plugin.handle, list_items)
    xbmcplugin.setContent(plugin.handle, "videos")
    xbmcplugin.endOfDirectory(plugin.handle)
Example #9
0
def add_menu_item(method,
                  label,
                  args=None,
                  art=None,
                  info=None,
                  directory=True):
    # type: (Callable, Union[str, int], dict, dict, dict, bool) -> None
    """wrapper for xbmcplugin.addDirectoryItem"""
    info = {} if info is None else info
    art = {} if art is None else art
    args = {} if args is None else args
    label = ku.localize(label) if isinstance(label, int) else label
    list_item = ListItem(label)
    list_item.setArt(art)
    if method == search and "q" in args:
        # saved search menu items can be removed via context menu
        list_item.addContextMenuItems([(ku.localize(32019),
                                        "XBMC.RunPlugin({})".format(
                                            plugin.url_for(search,
                                                           delete=True,
                                                           q=label)))])
    if method in [play_film, programme]:
        list_item.setInfo("video", info)
        list_item.setProperty("IsPlayable", "true")
    xbmcplugin.addDirectoryItem(plugin.handle, plugin.url_for(method, **args),
                                list_item, directory)
Example #10
0
    def _generate_listitem(title_item):
        """ Generate a ListItem from a TitleItem """
        from xbmcgui import ListItem

        # Three options:
        #  - item is a virtual directory/folder (not playable, path)
        #  - item is a playable file (playable, path)
        #  - item is non-actionable item (not playable, no path)
        is_folder = bool(not title_item.is_playable and title_item.path)
        is_playable = bool(title_item.is_playable and title_item.path)

        list_item = ListItem(label=title_item.title, path=title_item.path)

        if title_item.prop_dict:
            list_item.setProperties(title_item.prop_dict)
        list_item.setProperty(key='IsPlayable',
                              value='true' if is_playable else 'false')

        list_item.setIsFolder(is_folder)

        if title_item.art_dict:
            list_item.setArt(title_item.art_dict)

        if title_item.info_dict:
            # type is one of: video, music, pictures, game
            list_item.setInfo(type='video', infoLabels=title_item.info_dict)

        if title_item.stream_dict:
            # type is one of: video, audio, subtitle
            list_item.addStreamInfo('video', title_item.stream_dict)

        if title_item.context_menu:
            list_item.addContextMenuItems(title_item.context_menu)

        return list_item
Example #11
0
def index():

    if Addon().getSettingBool('search_enable') == True:
        listitem = ListItem(f"SpiderXML {Addon().getLocalizedString(32054)}")
        listitem.setArt({"icon" : "http://spiderxml.com/spidericon.png"})
        addDirectoryItem(plugin.handle, plugin.url_for(open_json, url="http://spider.forkplayer.tv/search/?web=&onlyxml=1/", warning="adult", search=False), listitem=listitem, isFolder=True)
    
    if len(Addon().getSettingString('fork_cookie')) > 0:
        listitem = ListItem("Forkplayer.tv Account")
        listitem.setArt({"icon" : "http://forkplayer.tv/favicon.ico"})
        addDirectoryItem(plugin.handle, plugin.url_for(open_json, url="http://forkplayer.tv/xml/account.php?act=info/", search=False), listitem=listitem, isFolder=True)


    for i in range(1, 8):
        #print(Addon().getSettingString('menu'+str(i)))
        menu_item_json = Addon().getSettingString('menu'+str(i))
        if len(menu_item_json) > 0:
            menu_item = json.loads(menu_item_json)
            listitem = ListItem(menu_item['name']+" #"+str(i))
            listitem.setArt({"icon" : menu_item['icon']})
            listitem.addContextMenuItems([(Addon().getLocalizedString(32055), f'RunPlugin("plugin://plugin.fxml.helper/menu/remove?id={str(i)}")')])
            addDirectoryItem(plugin.handle, plugin.url_for(open_json, url=menu_item['url'], search=False), listitem=listitem, isFolder=True)
        else:
            print(menu_item_json+"is equal 0")

    listitem = ListItem(f"{Addon().getLocalizedString(32091)}")
    listitem.setArt({"icon" : ""})
    addDirectoryItem(plugin.handle, plugin.url_for(go), listitem=listitem, isFolder=True)

    # listitem = ListItem("SpiderXML")
    # listitem.setArt({"icon" : "http://spiderxml.com/spidericon.png"})
    # addDirectoryItem(plugin.handle, plugin.url_for(open_json, url="http://spiderxml.com/", search=False), listitem=listitem, isFolder=True)

    # listitem = ListItem("nserv")
    # listitem.setArt({"icon" : "http://cdn.nserv.host/logo/nserv.png"})
    # addDirectoryItem(plugin.handle, plugin.url_for(open_json, url="http://nserv.host:5300/", search=False), listitem=listitem, isFolder=True)

    # listitem = ListItem("CoolTV")
    # listitem.setArt({"icon" : "http://cltv.club/img/tvcool23.jpg"})
    # addDirectoryItem(plugin.handle, plugin.url_for(open_json, url="http://cltv.club/start/", search=False), listitem=listitem, isFolder=True)

    # listitem = ListItem("Lnka")
    # #listitem.setArt({"icon" : "https://images.vfl.ru/ii/1596805732/19e65e77/31279532.png"})
    # addDirectoryItem(plugin.handle, plugin.url_for(open_json, url="http://p.lnka.ru/", search=False), listitem=listitem, isFolder=True)

    # listitem = ListItem("KB team")
    # listitem.setArt({"icon" : "http://kb-team.club/no_save/logotip/kb_logo.png"})
    # addDirectoryItem(plugin.handle, plugin.url_for(open_json, url="http://kb-team.club/", search=False), listitem=listitem, isFolder=True)

    # listitem = ListItem("Vplay")
    # listitem.setArt({"icon" : "http://cdn.vplay.one/fork/logo.png"})
    # addDirectoryItem(plugin.handle, plugin.url_for(open_json, url="http://fork.vplay.one/", search=False), listitem=listitem, isFolder=True)

    # listitem = ListItem("test playlist")
    # #listitem.setArt({"icon" : "http://kb-team.club/no_save/logotip/kb_logo.png"})
    # addDirectoryItem(plugin.handle, plugin.url_for(open_json, url="https://iptvm3u.ru/list.m3u", search=False), listitem=listitem, isFolder=True)
    
    endOfDirectory(plugin.handle)
Example #12
0
def show_videos(page):
    page = int(page)
    result = lbry_rpc('file_list', {
        'page': page,
        'page_size': int(ADDON.getSetting('page_size'))
    })
    # { total_items, items, page, total_pages, page_size }
    setContent(ph, 'movies')
    items = []
    nsfw = ADDON.getSettingBool('nsfw')
    for r in result['items']:
        if r['mime_type'].startswith('video'):
            if 'metadata' in r:
                if (not nsfw and ('nsfw' in r['metadata'])
                        and r['metadata']['nsfw']):
                    continue
                li = make_video_listitem(r, r['metadata'])
            else:
                li = ListItem(r['file_name'])
            li.setMimeType(r['mime_type'])
            if r['download_path'] != None:
                url = r['download_path']
            else:
                url = r['streaming_url']

            context_items = [
                (  # Send tip context menu
                    translate(30125).format(r['channel_name']
                                            or translate(30133)),
                    'RunPlugin(' + plugin.url_for(
                        send_tip,
                        claim_id=r['claim_id'],
                        channel_name=(r['channel_name'] or translate(30133))) +
                    ')'),
                (  # File delete context menu
                    translate(30112), 'RunPlugin(' +
                    plugin.url_for(file_delete, file_name=r['file_name']) +
                    ')')
            ]
            li.addContextMenuItems(context_items)
            items.append((url, li))

    description = translate(30142).format(result['page'],
                                          result['total_pages'])
    if result['total_pages'] > 1 and page > 1:
        li = ListItem(translate(30140))
        li.setInfo('video', {'plot': description})
        li.setIsFolder(True)
        items.append((plugin.url_for(show_videos, page=page - 1), li))
    if page < result['total_pages']:
        li = ListItem(translate(30141))
        li.setInfo('video', {'plot': description})
        li.setIsFolder(True)
        items.append((plugin.url_for(show_videos, page=page + 1), li))

    addDirectoryItems(ph, items, len(items))
    endOfDirectory(ph)
def show_favorites():
    """
    User's favorite channels list
    :return:
    """
    api = API()
    user = User()
    is_authenticated = user.authenticate()

    if is_authenticated:
        favorites = api.get_favorites(user.username, user.token)
        if len(favorites) > 0:
            for item in favorites:
                # list item:
                li = ListItem(u'{0} {1}'.format(
                    item['title'].replace('CALM RADIO -', '').title(),
                    '(VIP)' if 'free' not in item['streams'] else '',
                    item['description']),
                              iconImage='{0}/{1}'.format(
                                  config['urls']['calm_arts_host'],
                                  item['image']),
                              thumbnailImage='{0}/{1}'.format(
                                  config['urls']['calm_arts_host'],
                                  item['image']))
                li.setArt({
                    'fanart':
                    '{0}{1}'.format(config['urls']['calm_blurred_arts_host'],
                                    item['image'])
                })
                li.addContextMenuItems([
                    (ADDON.getLocalizedString(32301),
                     'RunPlugin(plugin://{0}/favorites/remove/{1})'.format(
                         ADDON_ID, item['id']))
                ])
                # directory item:
                addDirectoryItem(
                    PLUGIN.handle,
                    PLUGIN.url_for(play_channel,
                                   category_id=item['category'],
                                   channel_id=item['id']), li)
            # set the content of the directory
            setContent(ADDON_HANDLE, 'songs')
            # end of directory:
            endOfDirectory(PLUGIN.handle)
            executebuiltin('Container.SetViewMode({0})'.format(
                config['viewmodes']['thumbnail'][getSkinDir() if getSkinDir(
                ) in config['viewmodes']['thumbnail'] else 'skin.confluence']))
        # favorites list is empty:
        else:
            executebuiltin('Notification("{0}", "{1}")'.format(
                ADDON.getLocalizedString(30000),
                ADDON.getLocalizedString(32306)))
    # user is not authenticated:
    else:
        executebuiltin('Notification("{0}", "{1}")'.format(
            ADDON.getLocalizedString(30000), ADDON.getLocalizedString(32110)))
Example #14
0
 def createFolder(self,
                  name,
                  params,
                  contextMenu=[],
                  arturl='',
                  name2='*',
                  fanarturl=utils.addon.getAddonInfo('fanart')):
     li = ListItem(label=name, label2=name2)
     li.setArt({'thumb': arturl, 'fanart': fanarturl})
     li.addContextMenuItems(contextMenu)
     return "?".join([utils.addon_url, urlencode(params)]), li, "true"
def _subreddit_item(title, subreddit_name=None):
    """Return ListItem for given subreddit name with context menu."""
    listitem = ListItem(title)

    if subreddit_name is None:
        subreddit_name = title
    listitem.addContextMenuItems([
        (_('Remove'), 'RunPlugin(%sremove_subreddit/%s/)' % (
            addon.base_url, subreddit_name
        ))
    ])
    return listitem
Example #16
0
 def add(self, label, prefix, type, id=None, img='', icon='', isdir=True, commands=None):
 
     # Make full path for where to look for specified image
     if img != '':
         img = os.path.join(self.rpath, img)
         
     url = Key.build_url(prefix, type=type, id=id)
     li  = ListItem(label, iconImage=icon, thumbnailImage=img)
     if commands:
         li.addContextMenuItems( commands, True )
     ok  = addDirectoryItem(self.hndl, url=url, listitem=li, isFolder=isdir)
     
     return ok
Example #17
0
def build_video_item(name,thumb,videoid,info,video_info,audio_info):
    liz=ListItem(name)
    cm = []
    cm.append(("Info", 'XBMC.Action(Info)'))
    thumb = thumb if thumb else xbmcaddon.Addon().getAddonInfo("icon")
    liz.setProperty("type", "youtube_video")
    liz.setProperty("videoid",videoid)
    liz.setArt({'thumb': thumb, 'fanart': xbmcaddon.Addon().getAddonInfo("fanart"), "poster": thumb})
    liz.setInfo(type="Video", infoLabels=info)
    liz.addStreamInfo('video', video_info)
    liz.addStreamInfo('audio', audio_info)
    liz.setProperty('IsPlayable', 'true')
    liz.addContextMenuItems(cm, replaceItems=False)
    return liz
Example #18
0
def show_favorites():
    """
    User's favorite channels list
    :return:
    """
    api = API()
    user = User()
    is_authenticated = user.authenticate()

    if is_authenticated:
        favorites = api.get_favorites(user.username, user.token)
        if len(favorites) > 0:
            for item in favorites:
                # list item:
                li = ListItem(u'{0} {1}'.format(item['title'].replace('CALM RADIO -', '').title(),
                                                '(VIP)' if 'free' not in item['streams'] else '',
                                                item['description']),
                              iconImage='{0}/{1}'.format(config['urls']['calm_arts_host'], item['image']),
                              thumbnailImage='{0}/{1}'.format(config['urls']['calm_arts_host'], item['image']))
                li.setArt({
                    'fanart': '{0}{1}'.format(config['urls']['calm_blurred_arts_host'], item['image'])
                })
                li.addContextMenuItems(
                        [(ADDON.getLocalizedString(32301), 'RunPlugin(plugin://{0}/favorites/remove/{1})'
                          .format(ADDON_ID, item['id']))]
                )
                # directory item:
                addDirectoryItem(
                        PLUGIN.handle,
                        PLUGIN.url_for(play_channel,
                                       category_id=item['category'],
                                       channel_id=item['id']),
                        li
                )
            # set the content of the directory
            setContent(ADDON_HANDLE, 'songs')
            # end of directory:
            endOfDirectory(PLUGIN.handle)
            executebuiltin('Container.SetViewMode({0})'.format(
                    config['viewmodes']['thumbnail'][getSkinDir()
                    if getSkinDir() in config['viewmodes']['thumbnail'] else 'skin.confluence']
            ))
        # favorites list is empty:
        else:
            executebuiltin('Notification("{0}", "{1}")'
                           .format(ADDON.getLocalizedString(30000), ADDON.getLocalizedString(32306)))
    # user is not authenticated:
    else:
        executebuiltin('Notification("{0}", "{1}")'
                       .format(ADDON.getLocalizedString(30000), ADDON.getLocalizedString(32110)))
def build_video_item(name,thumb,videoid,info,video_info,audio_info):
    liz=ListItem(name)
    cm = []
    cm.append(("Info", 'XBMC.Action(Info)'))
    thumb = thumb if thumb else xbmcaddon.Addon().getAddonInfo("icon")
    liz.setProperty("type", "youtube_video")
    liz.setProperty("videoid",videoid)
    liz.setArt({'thumb': thumb, 'fanart': xbmcaddon.Addon().getAddonInfo("fanart"), "poster": thumb})
    liz.setInfo(type="Video", infoLabels=info)
    liz.addStreamInfo('video', video_info)
    liz.addStreamInfo('audio', audio_info)
    liz.setProperty('IsPlayable', 'true')
    liz.addContextMenuItems(cm, replaceItems=False)
    return liz
Example #20
0
def downloads():
	if kodiutils.get_setting_as_bool("folder") and kodiutils.get_setting("downloadPath") and xbmcvfs.exists(kodiutils.get_setting("downloadPath")):
		dirs, files = xbmcvfs.listdir(kodiutils.get_setting("downloadPath"))
		if files:
			items = []
			for file_ in files:
				cm = []
				liz = ListItem(file_.split(".")[0])
				liz.setPath(os.path.join(kodiutils.get_setting("downloadPath"),file_))
				liz.setProperty('IsPlayable', 'true')
				cm.append((kodiutils.get_string(32055), 'XBMC.RunPlugin(plugin://%s/delete_file/%s)' % (ADDON.getAddonInfo("id"),urllib.quote(os.path.join(kodiutils.get_setting("downloadPath"),file_), safe='')) ))
				liz.addContextMenuItems(cm, replaceItems=False)
				items.append((liz.getPath(), liz, False))
			if items:
				addDirectoryItems(plugin.handle, items, totalItems=len(items))
	endOfDirectory(plugin.handle)
def show_channels(section_id, category_id):
    """
    Channels page (playable)
    :param section_id: Selected section ID
    :param category_id: Selected category ID
    :return:
    """
    api = API()

    for item in api.get_channels(int(category_id)):
        # list item:
        li = ListItem(
            u'{0} {1}'.format(
                item['title'].replace('CALM RADIO -', '').title(),
                ADDON.getLocalizedString(322023)
                if 'free' not in item['streams'] else '', item['description']),
            iconImage='{0}/{1}'.format(config['urls']['calm_arts_host'],
                                       item['image']),
            thumbnailImage='{0}/{1}'.format(config['urls']['calm_arts_host'],
                                            item['image']))
        li.setArt({
            'fanart':
            '{0}{1}'.format(config['urls']['calm_blurred_arts_host'],
                            item['image'])
        })
        li.addContextMenuItems([
            (ADDON.getLocalizedString(32300),
             'RunPlugin(plugin://{0}/favorites/add/{1})'.format(
                 ADDON_ID, item['id']))
        ])
        li.setInfo(
            'music',
            {'Title': item['title'].replace('CALM RADIO -', '').title()})
        # directory item:
        addDirectoryItem(
            PLUGIN.handle,
            PLUGIN.url_for(play_channel,
                           category_id=category_id,
                           channel_id=item['id']), li)
    # set the content of the directory
    setContent(ADDON_HANDLE, 'songs')
    # end of directory:
    endOfDirectory(PLUGIN.handle)
    executebuiltin('Container.SetViewMode({0})'.format(
        config['viewmodes']['thumbnail'][getSkinDir() if getSkinDir(
        ) in config['viewmodes']['thumbnail'] else 'skin.confluence']))
Example #22
0
def list_items(selGroup, nbrLines):
	xbmcplugin.setContent(addon_handle, "files")
	if xbmcvfs.exists(txtfile):
		f = xbmcvfs.File(txtfile)
		nbr=0 # nbr of line on screen (selected)
		idx=0 # idx of line on the json file
		try: lines = json.load(f)
		except: lines = []
		for line in lines:
			if nbr>=nbrLines: break
			if group_by == group_by_type: group = line["type"]
			else: group = line["source"]
			if len(line)>3 and (group==selGroup or selGroup=='*'):
				nbr=nbr+1
				desc=''
				if show_date == "true": desc = desc + line["date"].strip() + ' '
				if show_time == "true": desc = desc + line["time"].strip() + ' '
				show = ''
				if 'show' in line: show=line["show"] + " "
				if 'season' in line and line["season"]!='' and str(line["season"])!="-1":
					if 'episode' in line and line["episode"]!='' and str(line["episode"])!="-1":
						show = show + str(line["season"])+"x"+str(line["episode"]) + " "
				desc=desc + show + line["title"]
				xpath=""
				infolabels={'title': desc, 'year': line['year'], "mediatype": line['type'], 'Top250': line['id']}
				li = ListItem(label=desc)
				li.setInfo('video', infolabels)
				li.setArt({ "poster" : line["thumbnail"].strip() })
				li.setArt({ "thumbnail" : line["thumbnail"].strip() })
				li.setArt({ "fanart" : line["fanart"].strip() })
				li.setProperty('IsPlayable', 'true')
				command = []
				command.append((lang(30008), "XBMC.RunPlugin(plugin://plugin.video.last_played?menu=remove&id="+str(idx)+")"))
				if line["file"][:6]=="plugin":
					command.append((lang(30031)+line["source"], "PlayMedia(" + line["file"] + ")"))
				li.addContextMenuItems(command)
				xurl=line["file"]
				if "video" in line and line["video"]!="": xurl=line["video"]
				addDirectoryItem(addon_handle, xurl, li)
			idx = idx + 1
		f.close()
		if single_list == "true" and nbr == 0:
			li = ListItem(lang(30030))
			li.setProperty('IsPlayable', 'false')
			addDirectoryItem(addon_handle, "", li, isFolder = True)
Example #23
0
def add_menu_item(method, label, **kwargs):
    # type: (callable, Union[str, int], Any) -> None
    """wrapper for xbmcplugin.addDirectoryItem"""
    args = kwargs.get("args", {})
    label = ku.localize(label) if isinstance(label, int) else label
    list_item = ListItem(label)
    list_item.setArt(kwargs.get("art"))
    list_item.setInfo("video", kwargs.get("info"))
    if method == search and "q" in args:
        list_item.addContextMenuItems([(ku.localize(32019),
                                        "XBMC.RunPlugin({})".format(
                                            plugin.url_for(search,
                                                           delete=True,
                                                           q=label)))])
    if method == play_film:
        list_item.setProperty("IsPlayable", "true")
    xbmcplugin.addDirectoryItem(plugin.handle, plugin.url_for(method, **args),
                                list_item, kwargs.get("directory", True))
Example #24
0
 def getListItem(self):
     li = ListItem(self.getLabel())
     if isinstance(self, PlayableMedia) and getattr(self, 'available',
                                                    True):
         li.setProperty('isplayable', 'true')
     artwork = {'thumb': _addon_icon, 'fanart': _addon_fanart}
     if getattr(self, 'image', None):
         artwork['thumb'] = self.image
     if getattr(self, 'fanart', None):
         artwork['fanart'] = self.fanart
     li.setArt(artwork)
     # In Favorites View everything is a Favorite
     if self._is_logged_in and hasattr(
             self, '_isFavorite') and '/favorites/' in sys.argv[0]:
         self._isFavorite = True
     cm = self.getContextMenuItems()
     if len(cm) > 0:
         li.addContextMenuItems(cm)
     return li
Example #25
0
def show_plug_list(items):
    items = filter(lambda ep: getattr(ep, 'available', True), items)
    for i, item in enumerate(items):
        title = item.title
        if item.episode:
            title += " (%s)" % item.episode
        li = ListItem(title)
        set_common_properties(item, li)
        set_steam_details(item, li)
        li.setInfo('video', {'title': title, 'count': i, 'mediatype': 'video'})

        if getattr(item, 'series_id', None):
            action = "container.update(\"%s\")" % plugin.url_for(
                series_view, item.series_id)
            li.addContextMenuItems([("GÃ¥ til serie", action)])

        url = plugin.url_for(play, item.id)
        addDirectoryItem(plugin.handle, url, li, False)
    endOfDirectory(plugin.handle)
Example #26
0
def _():
    edb.connect()
    idb.connect()
    items = []

    for path in edb.fetchall():
        (poster, info) = idb.fetchone(path)
        item = ListItem(info['title'])
        item.addContextMenuItems([(_addon.getLocalizedString(33100),
                                   f'RunPlugin({plugin.url}?delete={path})'),
                                  (_addon.getLocalizedString(33101),
                                   f'RunPlugin({plugin.url}?delete=%)')])
        item.setArt({'poster': poster})
        item.setInfo('video', info)
        items.append((url_for(path), item, True))

    edb.close()
    idb.close()
    show(items, 'tvshows')
Example #27
0
def show_channels(section_id, category_id):
    """
    Channels page (playable)
    :param section_id: Selected section ID
    :param category_id: Selected category ID
    :return:
    """
    api = API()

    for item in api.get_channels(int(category_id)):
        # list item:
        li = ListItem(u'{0} {1}'.format(item['title'].replace('CALM RADIO -', '').title(),
                                        ADDON.getLocalizedString(322023) if 'free' not in item['streams'] else '',
                                        item['description']),
                      iconImage='{0}/{1}'.format(config['urls']['calm_arts_host'], item['image']),
                      thumbnailImage='{0}/{1}'.format(config['urls']['calm_arts_host'], item['image']))
        li.setArt({
            'fanart': '{0}{1}'.format(config['urls']['calm_blurred_arts_host'], item['image'])
        })
        li.addContextMenuItems(
                [(ADDON.getLocalizedString(32300), 'RunPlugin(plugin://{0}/favorites/add/{1})'
                  .format(ADDON_ID, item['id']))]
        )
        li.setInfo('music', {
            'Title': item['title'].replace('CALM RADIO -', '').title()
        })
        # directory item:
        addDirectoryItem(
                PLUGIN.handle,
                PLUGIN.url_for(play_channel,
                               category_id=category_id,
                               channel_id=item['id']),
                li
        )
    # set the content of the directory
    setContent(ADDON_HANDLE, 'songs')
    # end of directory:
    endOfDirectory(PLUGIN.handle)
    executebuiltin('Container.SetViewMode({0})'.format(
            config['viewmodes']['thumbnail'][getSkinDir()
            if getSkinDir() in config['viewmodes']['thumbnail'] else 'skin.confluence']
    ))
Example #28
0
def show_plug_list(items):
    items = filter(lambda ep: getattr(ep, 'available', True), items)
    for i, item in enumerate(items):
        title = item.title
        if item.episode:
            title += " (%s)" % item.episode
        li = ListItem(title)
        set_common_properties(item, li)
        set_steam_details(item, li)
        li.setInfo('video', {
            'title': title,
            'count': i,
            'mediatype': 'video'})

        if getattr(item, 'series_id', None):
            action = "container.update(\"%s\")" % plugin.url_for(series_view, item.series_id)
            li.addContextMenuItems([("GÃ¥ til serie", action)])

        url = plugin.url_for(play, item.id)
        addDirectoryItem(plugin.handle, url, li, False)
    endOfDirectory(plugin.handle)
Example #29
0
def view(titles, urls, thumbs=repeat(''), bgs=repeat(''), descr=repeat(''), update_listing=False):
  total = len(titles)
  for title, url, descr, thumb, bg in zip(titles, urls, descr, thumbs, bgs):
    descr = descr() if callable(descr) else descr
    thumb = thumb() if callable(thumb) else thumb
    bg = bg() if callable(bg) else bg
    li = ListItem(title, thumbnailImage=thumb)
    playable = plugin.route_for(url) == play
    li.setProperty('isplayable', str(playable))
    li.setProperty('fanart_image', bg)
    if playable:
      li.setInfo('video', {'title':title, 'plot':descr})
      li.addStreamInfo('video', {'codec':'h264', 'width':1280, 'height':720})
      li.addStreamInfo('audio', {'codec':'aac', 'channels':2})
      commands = []
      search_url = plugin.make_url( "/searchfor/%s" % title.encode('utf-8') )
      runner = "XBMC.ActivateWindow(Video," + search_url + ",return)"
      commands.append(( str("Search NRK..."), runner))
      li.addContextMenuItems( commands )
    addDirectoryItem(plugin.handle, plugin.make_url(url), li, not playable, total)
  endOfDirectory(plugin.handle, updateListing=update_listing)
Example #30
0
def show_group(group_name):
    # on/off button
    addDirectoryItem(plugin.handle, plugin.url_for(toggle_group, group_name),
                     ListItem("Toggle %s on/off" % group_name))
    # applicable scenes
    for scene in bridge.scenes:
        if scene.group == str(bridge.get_group_id_by_name(group_name)):
            li = ListItem("Set scene %s" % scene.name)
            li.addContextMenuItems([
                ('Set on Playback start/resume',
                 'RunPlugin(plugin://plugin.program.hue.controller/setSetting/playback_start/%s/%s)'
                 % (group_name, scene.name)),
                ('Set on Playback paused',
                 'RunPlugin(plugin://plugin.program.hue.controller/setSetting/playback_paused/%s/%s)'
                 % (group_name, scene.name)),
                ('Set on Playback stopped',
                 'RunPlugin(plugin://plugin.program.hue.controller/setSetting/playback_end/%s/%s)'
                 % (group_name, scene.name))
            ])
            addDirectoryItem(
                plugin.handle,
                plugin.url_for(scene_group, group_name, scene.name), li)
    # add a special "lights off" scene
    li = ListItem("Set scene Lights Off")
    li.addContextMenuItems([
        ('Set on Playback start/resume',
         'RunPlugin(plugin://plugin.program.hue.controller/setSetting/playback_start/%s/%s)'
         % (group_name, 'HueControllerLightsOff')),
        ('Set on Playback paused',
         'RunPlugin(plugin://plugin.program.hue.controller/setSetting/playback_paused/%s/%s)'
         % (group_name, 'HueControllerLightsOff')),
        ('Set on Playback stopped',
         'RunPlugin(plugin://plugin.program.hue.controller/setSetting/playback_end/%s/%s)'
         % (group_name, 'HueControllerLightsOff'))
    ])
    addDirectoryItem(
        plugin.handle,
        plugin.url_for(scene_group, group_name, 'HueControllerLightsOff'), li)

    endOfDirectory(plugin.handle)
Example #31
0
def plugin_follows():
    channels = load_channel_subs()
    resolve_uris = []
    for (name, claim_id) in channels:
        resolve_uris.append(name + '#' + claim_id)
    channel_infos = call_rpc('resolve', {'urls': resolve_uris})

    for (name, claim_id) in channels:
        uri = name + '#' + claim_id
        channel_info = channel_infos[uri]
        li = ListItem(name)
        if not 'error' in channel_info:
            plot = ''
            if 'title' in channel_info[
                    'value'] and channel_info['value']['title'].strip() != '':
                plot = '[B]%s[/B]\n' % channel_info['value']['title']
            else:
                plot = '[B]%s[/B]\n' % channel_info['name']
            if 'description' in channel_info['value']:
                plot = plot + channel_info['value']['description']
            infoLabels = {'plot': plot}
            li.setInfo('video', infoLabels)

            if 'thumbnail' in channel_info['value'] and 'url' in channel_info[
                    'value']['thumbnail']:
                li.setArt({
                    'thumb': channel_info['value']['thumbnail']['url'],
                    'poster': channel_info['value']['thumbnail']['url'],
                    'fanart': channel_info['value']['thumbnail']['url']
                })

        menu = []
        menu.append((tr(30206) % name, 'RunPlugin(%s)' %
                     plugin.url_for(plugin_unfollow, uri=serialize_uri(uri))))
        li.addContextMenuItems(menu)
        addDirectoryItem(
            ph, plugin.url_for(lbry_channel, uri=serialize_uri(uri), page=1),
            li, True)
    endOfDirectory(ph)
Example #32
0
def add_menu_item(method, label, args=None, art=None, info=None, directory=True):
    # type (Callable, str, dict, dict, dict, bool) -> None
    """wrapper for xbmcplugin.addDirectoryItem"""
    info = {} if info is None else info
    art = {} if art is None else art
    args = {} if args is None else args
    label = ku.get_string(label) if isinstance(label, int) else label
    list_item = ListItem(label)
    list_item.setArt(art)
    list_item.setInfo("video", info)
    if method == search and "q" in args:
        # saved search menu items can be removed via context menu
        list_item.addContextMenuItems([(
            ku.get_string(32019),
            "XBMC.RunPlugin({})".format(plugin.url_for(search, delete=True, q=label))
        )])
    if not directory and method == play_film:
        list_item.setProperty("IsPlayable", "true")
    xp.addDirectoryItem(
        plugin.handle,
        plugin.url_for(method, **args),
        list_item,
        directory)
Example #33
0
def recently_viewed(delete=None):
    ExternalDatabase.connect()

    if delete is not None:
        ExternalDatabase.remove(delete)
        xbmc.executebuiltin('Container.Refresh')
    else:
        items = []

        for row in ExternalDatabase.fetchall():
            item = ListItem(row['title'])
            item.addContextMenuItems([
                ("Remove", 'RunPlugin(plugin://plugin.video.kshowonline/recently-viewed?delete=' + row['path'] + ')'),
                ("Remove all", 'RunPlugin(plugin://plugin.video.kshowonline/recently-viewed?delete=%)')
            ])
            item.setInfo('video', {})
            items.append((plugin.url_for(row['path']), item, True))

        xbmcplugin.setContent(plugin.handle, 'videos')
        xbmcplugin.addDirectoryItems(plugin.handle, items, len(items))
        xbmcplugin.endOfDirectory(plugin.handle)

    ExternalDatabase.close()
Example #34
0
def track_list(tracks):
    xbmcplugin.setContent(plugin.handle, 'songs')
    list_items = []
    for track in tracks:
        if not track.available:
            continue
        url = plugin.url_for(play, track_id=track.id)
        li = ListItem(track.name)
        li.setProperty('isplayable', 'true')
        li.setInfo('music', {
            'title': track.name,
            'tracknumber': track.track_num,
            'discnumber': track.disc_num,
            'artist': track.artist.name,
            'album': track.album.name})
        if track.album:
            li.setThumbnailImage(track.album.image)
        radio_url = plugin.url_for(track_radio, track_id=track.id)
        li.addContextMenuItems(
            [('Track Radio', 'XBMC.Container.Update(%s)' % radio_url,)])
        list_items.append((url, li, False))
    xbmcplugin.addDirectoryItems(plugin.handle, list_items)
    xbmcplugin.endOfDirectory(plugin.handle)
Example #35
0
def list_items(selGroup, nbrLines):
    xbmcplugin.setContent(addon_handle, "files")
    if xbmcvfs.exists(txtfile):
        f = xbmcvfs.File(txtfile)
        nbr = 0  # nbr of line on screen (selected)
        idx = 0  # idx of line on the json file
        try:
            lines = json.load(f)
        except:
            lines = []
        for line in lines:
            if nbr >= nbrLines: break
            if group_by == group_by_type: group = line["type"]
            else: group = line["source"]
            if len(line) > 3 and (group == selGroup or selGroup == '*'):
                nbr = nbr + 1
                desc = ''
                if show_date == "true":
                    desc = desc + line["date"].strip() + ' '
                if show_time == "true":
                    desc = desc + line["time"].strip() + ' '
                show = ''
                if 'show' in line: show = line["show"] + " "
                if 'season' in line and line["season"] != '' and str(
                        line["season"]) != "-1":
                    if 'episode' in line and line["episode"] != '' and str(
                            line["episode"]) != "-1":
                        show = show + str(line["season"]) + "x" + str(
                            line["episode"]) + " "
                desc = desc + show + line["title"]
                xpath = ""
                infolabels = {
                    'title': desc,
                    'year': line['year'],
                    "mediatype": line['type'],
                    'Top250': line['id']
                }
                li = ListItem(label=desc)
                li.setInfo('video', infolabels)
                li.setArt({"poster": line["thumbnail"].strip()})
                li.setArt({"thumbnail": line["thumbnail"].strip()})
                li.setArt({"fanart": line["fanart"].strip()})
                li.setProperty('IsPlayable', 'true')
                command = []
                command.append((lang(
                    30008
                ), "XBMC.RunPlugin(plugin://plugin.video.last_played?menu=remove&id="
                                + str(idx) + ")"))
                if line["file"][:6] == "plugin":
                    command.append((lang(30031) + line["source"],
                                    "PlayMedia(" + line["file"] + ")"))
                li.addContextMenuItems(command)
                xurl = line["file"]
                if "video" in line and line["video"] != "":
                    xurl = line["video"]
                addDirectoryItem(addon_handle, xurl, li)
            idx = idx + 1
        f.close()
        if single_list == "true" and nbr == 0:
            li = ListItem(lang(30030))
            li.setProperty('IsPlayable', 'false')
            addDirectoryItem(addon_handle, "", li, isFolder=True)
Example #36
0
def createListItem(item, append_show_title=False, append_sxxexx=False):
    title = item['title']
    li = ListItem(title)
    li.setProperty('IsPlayable', "true")

    metadata = {
        'duration': str(item['runtime']/60),
        'Plot': item['plot'],
        'Playcount': item['playcount']
    }

    if "episode" in item:
        episode = item['episode']
        metadata['Episode'] = episode

    if "season" in item:
        season = item['season']
        metadata['Season'] = season

    if season and episode:
        li.setProperty('episodeno', "s%.2de%.2d" % (season, episode))
        if append_sxxexx is True:
            title = "S%.2dE%.2d - %s" % (season, episode, title)

    if "firstaired" in item:
        metadata['Premiered'] = item['firstaired']

    if "showtitle" in item:
        metadata['TVshowTitle'] = item['showtitle']
        if append_show_title is True:
            title = item['showtitle'] + ' - ' + title

    if "rating" in item:
        metadata['Rating'] = str(round(float(item['rating']),1))

    if "director" in item:
        metadata['Director'] = " / ".join(item['director'])

    if "writer" in item:
        metadata['Writer'] = " / ".join(item['writer'])

    if "cast" in item:
        cast = []
        castandrole = []
        for person in item['cast']:
            name = person['name']
            cast.append(name)
            castandrole.append((name, person['role']))
        metadata['Cast'] = cast
        metadata['CastAndRole'] = castandrole

    metadata['Title'] = title
    li.setLabel(title)

    li.setInfo(type="Video", infoLabels=metadata)  
    li.setProperty('resumetime', str(item['resume']['position']))
    li.setProperty('totaltime', str(item['resume']['total']))
    li.setArt(item['art'])
    li.setThumbnailImage(item['art'].get('thumb',''))
    li.setArt({'icon': 'DefaultTVShows.png'})
    li.setProperty('dbid', str(item['episodeid']))
    li.setProperty('fanart_image', item['art'].get('tvshow.fanart',''))
    try:
        li.addContextMenuItems([(lang(30032), 'XBMC.Action(Info)',)])
    except TypeError:
        # Kodi f**k-up
        pass
    for key, value in item['streamdetails'].iteritems():
        for stream in value:
            li.addStreamInfo(key, stream)
    
    return li
 def createFolder(self, name, params, contextMenu=[], album_art_url='', name2='*'):
     li = ListItem(label=name, label2=name2, thumbnailImage=album_art_url)
     li.addContextMenuItems(contextMenu, replaceItems=True)
     li.setProperty('fanart_image', self.fanart)
     url = "?".join([utils.addon_url, urlencode(params)])
     return url, li, "true"
Example #38
0
def create_listitem(item, append_show_title=False, append_sxxexx=False):
    """
    Feed with a Kodi json item response to get a xbmcgui.ListItem() with
    everything set and ready.
    """
    title = item['title']
    listitem = ListItem(title)
    listitem.setProperty('IsPlayable', 'true')
    metadata = {
        'duration': str(item['runtime'] / 60),
        'Plot': item['plot'],
        'Playcount': item['playcount']
    }
    if 'episode' in item:
        episode = item['episode']
        metadata['Episode'] = episode
    if 'season' in item:
        season = item['season']
        metadata['Season'] = season
    if season and episode:
        listitem.setProperty('episodeno', 's%.2de%.2d' % (season, episode))
        if append_sxxexx is True:
            title = 'S%.2dE%.2d - %s' % (season, episode, title)
    if 'firstaired' in item:
        metadata['Premiered'] = item['firstaired']
    if 'showtitle' in item:
        metadata['TVshowTitle'] = item['showtitle']
        if append_show_title is True:
            title = item['showtitle'] + ' - ' + title
    if 'rating' in item:
        metadata['Rating'] = str(round(float(item['rating']), 1))
    if 'director' in item:
        metadata['Director'] = item['director']
    if 'writer' in item:
        metadata['Writer'] = item['writer']
    if 'cast' in item:
        cast = []
        castandrole = []
        for person in item['cast']:
            name = person['name']
            cast.append(name)
            castandrole.append((name, person['role']))
        metadata['Cast'] = cast
        metadata['CastAndRole'] = castandrole

    metadata['Title'] = title
    metadata['mediatype'] = 'episode'
    metadata['dbid'] = str(item['episodeid'])
    listitem.setLabel(title)
    listitem.setInfo(type='Video', infoLabels=metadata)

    listitem.setProperty('resumetime', str(item['resume']['position']))
    listitem.setProperty('totaltime', str(item['resume']['total']))
    listitem.setArt(item['art'])
    listitem.setThumbnailImage(item['art'].get('thumb', ''))
    listitem.setArt({'icon': 'DefaultTVShows.png'})
    listitem.setProperty('fanart_image', item['art'].get('tvshow.fanart', ''))
    try:
        listitem.addContextMenuItems([(
            utils.lang(30032),
            'XBMC.Action(Info)',
        )])
    except TypeError:
        # Kodi f**k-up
        pass
    for key, value in item['streamdetails'].iteritems():
        for stream in value:
            listitem.addStreamInfo(key, stream)
    return listitem
Example #39
0
def get_dir_entry(mode,
                  metadata,
                  is_folder=True,
                  channel_id='',
                  channel_path='',
                  tv_show_id='',
                  season_id='',
                  video_id='',
                  stream_type='VOD',
                  block_id='',
                  override_fanart='',
                  fav_type='',
                  favorite_item=None,
                  title_prefix='',
                  client_data='',
                  compilation_id='',
                  movie_id='',
                  viewtype=''):

    params = {
        'mode':
        mode,
        'tv_show_id':
        tv_show_id,
        'season_id':
        season_id,
        'video_id':
        video_id,
        'stream_type':
        stream_type,
        'channel_id':
        channel_id,
        'channel_path':
        channel_path,
        'block_id':
        block_id,
        'fav_type':
        fav_type,
        'title':
        compat._encode(title_prefix) +
        compat._encode(metadata['infoLabels'].get('title', '')),
        'client_data':
        client_data,
        'compilation_id':
        compilation_id,
        'movie_id':
        movie_id,
        'viewtype':
        viewtype,
    }

    if favorite_item is not None:
        params.update({'favorite_item': dumps(favorite_item)})

    list_item = ListItem(label=metadata['infoLabels']['title'], offscreen=True)
    list_item.setInfo(type='video', infoLabels=metadata['infoLabels'])

    if is_folder is True:
        list_item.setProperty('isPlayable', 'false')

    if 'poster' not in metadata['art'] and 'thumb' in metadata['art']:
        metadata['art'].update({'poster': metadata['art']['thumb']})
    elif 'thumb' not in metadata['art']:
        metadata['art'].update({'thumb': default_logo})
        metadata['art'].update({'poster': default_logo})

    if 'icon' not in metadata['art']:
        metadata['art'].update({'icon': default_icon})

    if override_fanart != '':
        metadata['art'].update({'fanart': override_fanart})

    if 'fanart' not in metadata['art']:
        metadata['art'].update({'fanart': default_fanart})

    for art_key, art_value in metadata['art'].items():
        metadata['art'].update(
            {art_key: lib_joyn().add_user_agent_http_header(art_value)})

    list_item.setArt(metadata['art'])

    if mode == 'play_video' and video_id != '' and client_data != '':
        list_item.setProperty('IsPlayable', 'True')

        if 'resume_pos' in metadata.keys(
        ) and 'duration' in metadata['infoLabels'].keys():
            xbmc_helper().log_debug(
                'Setting resume position - asset {} - pos {}',
                metadata['infoLabels']['title'], metadata.get('resume_pos'))
            list_item.setProperty('ResumeTime', metadata.get('resume_pos'))
            list_item.setProperty(
                'TotalTime',
                str(float(metadata['infoLabels'].get('duration'))))

    if metadata.get('is_bookmarked',
                    None) is not None and lib_joyn().get_auth_token().get(
                        'has_account', False) is True:
        asset_id = None

        if mode == 'season' and tv_show_id != '':
            asset_id = tv_show_id
        elif mode == 'play_video' and movie_id != '':
            asset_id = movie_id
        elif mode == 'compilation_items' and compilation_id != '':
            asset_id = compilation_id

        if asset_id is not None:
            if metadata.get('is_bookmarked', False) is True:
                list_item.addContextMenuItems([(
                    xbmc_helper().translation('DEL_FROM_JOYN_BOOKMARKS_LABEL'),
                    compat._format(
                        'RunPlugin({}?{})', pluginurl,
                        urlencode({
                            'mode': 'remove_joyn_bookmark',
                            'asset_id': asset_id
                        })))])
            else:
                list_item.addContextMenuItems([
                    (xbmc_helper().translation('ADD_TO_JOYN_BOOKMARKS_LABEL'),
                     compat._format(
                         'RunPlugin({}?{})', pluginurl,
                         urlencode({
                             'mode': 'add_joyn_bookmark',
                             'asset_id': asset_id
                         })))
                ])

    return (compat._format('{}?{}', pluginurl,
                           urlencode(params)), list_item, is_folder)
def show_listing(list_items,
                 category=None,
                 sort='unsorted',
                 ascending=True,
                 content=None,
                 cache=None,
                 selected=None):
    """Show a virtual directory in Kodi"""
    from xbmcgui import ListItem
    from addon import plugin

    set_property('container.url', 'plugin://' + addon_id() + plugin.path)
    xbmcplugin.setPluginFanart(handle=plugin.handle,
                               image=from_unicode(addon_fanart()))

    usemenucaching = get_setting_bool('usemenucaching', default=True)
    if cache is None:
        cache = usemenucaching
    elif usemenucaching is False:
        cache = False

    if content:
        # content is one of: files, songs, artists, albums, movies, tvshows, episodes, musicvideos
        xbmcplugin.setContent(plugin.handle, content=content)

    # Jump through hoops to get a stable breadcrumbs implementation
    category_label = ''
    if category:
        if not content:
            category_label = 'VRT NU / '
        if plugin.path.startswith(('/favorites/', '/resumepoints/')):
            category_label += localize(30428) + ' / '  # My
        if isinstance(category, int):
            category_label += localize(category)
        else:
            category_label += category
    elif not content:
        category_label = 'VRT NU'
    xbmcplugin.setPluginCategory(handle=plugin.handle, category=category_label)

    # FIXME: Since there is no way to influence descending order, we force it here
    if not ascending:
        sort = 'unsorted'

    # NOTE: When showing tvshow listings and 'showoneoff' was set, force 'unsorted'
    if get_setting_bool(
            'showoneoff',
            default=True) and sort == 'label' and content == 'tvshows':
        sort = 'unsorted'

    # Add all sort methods to GUI (start with preferred)
    xbmcplugin.addSortMethod(handle=plugin.handle,
                             sortMethod=SORT_METHODS[sort])
    for key in sorted(SORT_METHODS):
        if key != sort:
            xbmcplugin.addSortMethod(handle=plugin.handle,
                                     sortMethod=SORT_METHODS[key])

    # FIXME: This does not appear to be working, we have to order it ourselves
#    xbmcplugin.setProperty(handle=plugin.handle, key='sort.ascending', value='true' if ascending else 'false')
#    if ascending:
#        xbmcplugin.setProperty(handle=plugin.handle, key='sort.order', value=str(SORT_METHODS[sort]))
#    else:
#        # NOTE: When descending, use unsorted
#        xbmcplugin.setProperty(handle=plugin.handle, key='sort.order', value=str(SORT_METHODS['unsorted']))

    listing = []
    showfanart = get_setting_bool('showfanart', default=True)
    for title_item in list_items:
        # Three options:
        #  - item is a virtual directory/folder (not playable, path)
        #  - item is a playable file (playable, path)
        #  - item is non-actionable item (not playable, no path)
        is_folder = bool(not title_item.is_playable and title_item.path)
        is_playable = bool(title_item.is_playable and title_item.path)

        list_item = ListItem(label=title_item.label)

        prop_dict = dict(
            IsInternetStream='true' if is_playable else 'false',
            IsPlayable='true' if is_playable else 'false',
            IsFolder='false' if is_folder else 'true',
        )
        if title_item.prop_dict:
            title_item.prop_dict.update(prop_dict)
        else:
            title_item.prop_dict = prop_dict
        # NOTE: The setProperties method is new in Kodi18
        try:
            list_item.setProperties(title_item.prop_dict)
        except AttributeError:
            for key, value in list(title_item.prop_dict.items()):
                list_item.setProperty(key=key, value=str(value))

        # FIXME: The setIsFolder method is new in Kodi18, so we cannot use it just yet
        # list_item.setIsFolder(is_folder)

        if showfanart:
            # Add add-on fanart when fanart is missing
            if not title_item.art_dict:
                title_item.art_dict = dict(fanart=addon_fanart())
            elif not title_item.art_dict.get('fanart'):
                title_item.art_dict.update(fanart=addon_fanart())
            list_item.setArt(title_item.art_dict)

        if title_item.info_dict:
            # type is one of: video, music, pictures, game
            list_item.setInfo(type='video', infoLabels=title_item.info_dict)

        if title_item.stream_dict:
            # type is one of: video, audio, subtitle
            list_item.addStreamInfo('video', title_item.stream_dict)

        if title_item.context_menu:
            list_item.addContextMenuItems(title_item.context_menu)

        url = None
        if title_item.path:
            url = title_item.path

        listing.append((url, list_item, is_folder))

    # Jump to specific item
    if selected is not None:
        pass


#        from xbmcgui import getCurrentWindowId, Window
#        wnd = Window(getCurrentWindowId())
#        wnd.getControl(wnd.getFocusId()).selectItem(selected)

    succeeded = xbmcplugin.addDirectoryItems(plugin.handle, listing,
                                             len(listing))
    xbmcplugin.endOfDirectory(plugin.handle,
                              succeeded,
                              updateListing=False,
                              cacheToDisc=cache)
    def create_directory(self):

        if self.state.type == nrk.PLAYLIST:
            self.player = utils.PluginPlayer()
        
        Log.notice('PLUGIN::SPAM -> Set plugin dir content "%s"' % self.content)
        self.dir.set_content(self.content)
        
        if self.settings['fetch_path']:
            if (self.state.type == nrk.SHOW 
            or self.state.type == nrk.SHOW_FOLDER):
                self.category = self.api.get_path(self.state.id, self.state.type)
                self.set_category()
        else:
            self.set_category()
        
        
        for i in self:
            li = ListItem(i.title, thumbnailImage=i.thumbnail)
            
            overlay = (
                    xbmcgui.ICON_OVERLAY_UNWATCHED,
                    xbmcgui.ICON_OVERLAY_WATCHED,)[
                        self.session.data_objects['watched'].has_key(i.key.id)]

                
            if i.isPlayable is True:
                li.setProperty('IsPlayable', 'true')

            li.setInfo( 'video', {
                            'plot':    i.plot, 
                            'title':   i.title, 
                            'overlay': overlay
                        }
                    )
            
            try:    
              li.setLabel2(self.type_dict[i.key.type])
            except:
              pass
              
            if self.state.type == nrk.PLAYLIST and self.state.view:
                self.player.queue(i.url, li)
            
            
            commands = []
            commands.append(( lang(30300), 
                                  'XBMC.RunPlugin(%s)' % (
                                        Key.build_url(
                                              'program',
                                              words = self.state.__dict__,
                                              refresh = True
                                        )), 
                                ))
                                
            if i.key.type == nrk.SHOW:                
                commands.append(( lang(30301), 
                                  'XBMC.RunPlugin(%s)' % (
                                        Key.build_url(
                                              'favorites',
                                              action = 'add', 
                                              name  = i.title, 
                                              thumb = i.thumbnail, 
                                              id    = i.key.id
                                        )), 
                                ))
                
            
            elif i.defntion == 'video/mp4':
                commands.append(( lang(30302), 
                                  'XBMC.RunPlugin(%s)' % (
                                        Key.build_url(
                                              'nogui',
                                              action = 'download', 
                                              name  = i.title, 
                                              thumb = i.thumbnail, 
                                              url   = i.url
                                        )), 
                                ))
                
            
            li.addContextMenuItems( commands )  
            
    
            if i.key.type != nrk.VIGNETE:
                ok = self.dir.add(i.url, li, i.isFolder, int(sys.argv[1]))
                if ok == False:
                    break
                
        if self.state.type == nrk.PLAYLIST and self.state.view:
            if self.settings.autoplay_playlist == True:
                self.player.playQueue()
Example #42
0
def get_by_category(category_id):
    dir = get_url(ids.categories_request_url.format(id=category_id), critical=True)
    dir_json = json.loads(dir)
    special = ['ganze folgen', 'clips', 'bonus']
    if "children" in dir_json["category"]:
        setContent(plugin.handle, 'tvshows')
        icon = ""
        fanart = ""
        if "images_json" in dir_json["category"]:
            images_parent = json.loads(dir_json["category"]["images_json"])
            if "image_base" in images_parent and images_parent["image_base"] != None:
                icon = images_parent["image_base"]
            if "image_show_big" in images_parent and images_parent["image_show_big"] != None:
                fanart = images_parent["image_show_big"]
        for child in dir_json["category"]["children"]:
            name = child["name"]
            icon_child = icon
            fanart_child = fanart
            if not any(x in child["name"].lower() for x in special):
                icon_child = ""
                fanart_child = ""
                if "images_json" in child:
                    images_child = json.loads(child["images_json"])
                    if "image_base" in images_child:
                        icon_child = images_child["image_base"]
                    if "image_show_big" in images_child:
                        fanart_child = images_child["image_show_big"]
            listitem = ListItem(name)
            listitem.setArt({'icon': icon_child, 'thumb': icon_child, 'poster': icon_child, 'fanart': fanart_child})
            plot = ""
            if 'description' in child and child['description'] != None:
                try:
                    startDATES = datetime(*(time.strptime(child['description'].split(', ')[1], '%d.%m.%y')[0:6])) # Do, 04.07.19
                    locale.setlocale(locale.LC_ALL, '')
                    lastTIMES = startDATES.strftime('%A - %d.%m.%Y')
                    plot = kodiutils.get_string(32006).format(str(lastTIMES))
                except: pass
            listitem.setInfo(type='Video', infoLabels={'Title': name, 'Plot': plot})
            addDirectoryItem(plugin.handle, url=plugin.url_for(get_by_category, child["id"]),
                listitem=listitem, isFolder=True)
        add_favorites_folder(plugin.url_for(get_by_category, dir_json["category"]["id"]),
            dir_json["category"]["name"], icon, fanart)
    if "vod_items" in dir_json["category"]:
        if kodiutils.get_setting("sort") == "1":
            xbmcplugin.addSortMethod(plugin.handle, xbmcplugin.SORT_METHOD_UNSORTED)
            xbmcplugin.addSortMethod(plugin.handle, xbmcplugin.SORT_METHOD_LABEL)
            xbmcplugin.addSortMethod(plugin.handle, xbmcplugin.SORT_METHOD_DURATION)
            xbmcplugin.addSortMethod(plugin.handle, xbmcplugin.SORT_METHOD_EPISODE)
        setContent(plugin.handle, 'tvshows')
        for vod in dir_json["category"]["vod_items"]:
            goDATE = None
            startTIMES = ""
            Note_1 = ""
            Note_2 = vod["summary"]
            if not Note_2:
                Note_2 = ""
            if 'order_date' in vod and not str(vod['order_date']).startswith('1970') and vod['order_date'] != None:
                try:
                    startDATES = datetime(*(time.strptime(vod['order_date'].split(' +')[0], '%Y/%m/%d %H:%M:%S')[0:6])) # 2019/06/23 14:10:00 +0000
                    LOCALstart = utc_to_local(startDATES)
                    startTIMES = LOCALstart.strftime('%d.%m.%Y - %H:%M')
                    goDATE =  LOCALstart.strftime('%d.%m.%Y')
                except: pass
            if startTIMES != "": Note_1 = kodiutils.get_string(32005).format(str(startTIMES))
            if goDATE and kodiutils.get_setting("sort") == "1": xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_DATE)
            if vod['title'].lower().find('staffel') > -1 or vod['title'].lower().find('episode') > -1 or vod['title'].lower().find('folge') > -1:
                try: vod['season'] = re.search('Staffel\s*(\d+)', vod['title']).group(1)
                except: pass
                try: vod['episode'] = re.search('Episode\s*(\d+)', vod['title']).group(1)
                except:
                    try:vod['episode'] = re.search('Folge\s*(\d+)', vod['title']).group(1)
                    except: pass
                if not kodiutils.get_setting_as_bool('keep_episode_number'):
                    try: vod['cleantitle'] = re.search(':\s*(.*)', vod['title']).group(1)
                    except: pass
                if vod.get('season', -1) != -1 or vod.get('episode', -1) != -1:
                    vod['mediatype'] = 'episode'
            log("Title: "+vod["title"])
            images = json.loads(vod["images_json"])
            listitem = ListItem(vod["title"])
            listitem.setArt({'icon': images["image_base"], 'thumb': images["image_base"], 'fanart': images["image_base"], 'poster': images["image_base"]})
            listitem.setProperty('IsPlayable', 'true')
            listitem.setInfo(type='Video', infoLabels={'Title': vod.get('cleantitle', vod["title"]), 'Plot': Note_1+Note_2, 'TvShowTitle': vod['show_name'], 'Season': vod.get('season', "-1"), 'episode': vod.get('episode', "-1"), 'Duration': vod['duration'], 'Date': goDATE, 'mediatype': vod.get('mediatype', 'video')})
            listitem.addContextMenuItems([('Queue', 'Action(Queue)')])
            addDirectoryItem(plugin.handle, url=plugin.url_for(play_video, vod["external_id"], vod["top_level_category"]["name"]),
                listitem=listitem)
    endOfDirectory(plugin.handle)
Example #43
-1
def build_episode_item(episode, show_fanart=None):
	#create episode listitem
	episode_title = episode["name"] if episode["name"] else "None"
	liz = ListItem(episode["name"])
	#infolabels
	infolabels = { "title": episode["name"] }
	if "summary" in episode.keys(): infolabels["plot"] = episode["summary"]
	if "number" in episode.keys() and episode["number"].isdigit(): infolabels["episode"] = int(episode["number"])
	if "published" in episode.keys(): 
		try: 
			infolabels["aired"] = episode['published'].rsplit('T')[0]
			infolabels["date"] = episode['published'].rsplit('T')[0].replace("-",".")
			infolabels["year"] = int(episode['published'].rsplit('T')[0].split("-")[0])
		except: xbmc.log(msg='[Revision3] could not get date information', level=xbmc.LOGERROR)
		
	if "show" in episode.keys() and "name" in episode["show"].keys(): infolabels["tvshowtitle"] = episode["show"]["name"]
	if "duration" in episode.keys() and episode["duration"].isdigit(): infolabels["duration"] = int(episode["duration"])
			
	#Art
	art = {}
	if "images" in episode.keys():
		if "medium" in episode["images"].keys():
			art["thumb"] = episode["images"]["medium"]
			art["icon"] = episode["images"]["medium"]
			art["poster"] = episode["images"]["medium"]
	if show_fanart: art["fanart"] = urllib.unquote(show_fanart)
	liz.setInfo( type="Video", infoLabels=infolabels)
	liz.setArt(art)

	#Videos
	url = ""
	if "media" in episode.keys():
		media_urls = []
		video_info = {}
		if "hd720p30" in episode["media"].keys(): media_urls.append(episode["media"]["hd720p30"]["url"])
		if "large" in episode["media"].keys(): media_urls.append(episode["media"]["large"]["url"])
		if "small" in episode["media"].keys(): media_urls.append(episode["media"]["small"]["url"])
		#Parse user preference
		if len(media_urls) > 0:
			if kodiutils.get_setting_as_int("format") == 0: url = media_urls[0]; video_info['width'] = 1280; video_info['height'] = 720
			if kodiutils.get_setting_as_int("format") == 1: url = media_urls[1] if len(media_urls) > 1 else media_urls[-1]; video_info['width'] = 854; video_info['height'] = 480
			if kodiutils.get_setting_as_int("format") == 2: url = media_urls[-1]; video_info['width'] = 854; video_info['height'] = 480
	
	#context menu items
	cm = []
	cm.append((kodiutils.get_string(32063), 'XBMC.Action(Info)'))
	

	if url:
		if kodiutils.get_setting_as_bool("download") and kodiutils.get_setting("downloadPath") and xbmcvfs.exists(kodiutils.get_setting("downloadPath")):
			cm.append((kodiutils.get_string(32062), 'XBMC.RunPlugin(plugin://%s/download/%s/%s)' % (ADDON.getAddonInfo("id"),urllib.quote(episode_title, safe=''),urllib.quote(url, safe='')) ))
		liz.setPath("plugin://%s/play/%s" % (ADDON.getAddonInfo("id"),urllib.quote(url, safe='')) )
		liz.setProperty('IsPlayable', 'true')
		liz.addStreamInfo('video', video_info)
		liz.addContextMenuItems(cm, replaceItems=False)
		return liz
	else:
		return None