def view_tv_provider_details():
    dialog = xbmcgui.Dialog()
    dialog.ok(
        get_string(30380),
        get_string(30390) % adobe_activate_api.get_authentication_expires(),
        get_string(30700) %
        (player_config.get_dma(), player_config.get_timezone()))
示例#2
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)
示例#3
0
def index():
    try:
        req = __session__.get("http://www.rtp.pt/play/",
                              headers=__headers__).text
    except:
        kodiutils.ok(kodiutils.get_string(32000), kodiutils.get_string(32001))
        exit(0)

    match = re.compile(
        '<a title=".+?direto (.+?)" href="(.+?)" class="mask-live "><img alt=".+?" src="(.+?)" class="img-responsive">.+?<span class="small"><b>(.+?)</b>'
    ).findall(req)
    if match:
        for channel, rel_url, img, prog in match:
            liz = ListItem("[B][COLOR blue]{}[/B][/COLOR] ({})".format(
                kodiutils.smart_str(channel), kodiutils.smart_str(prog)))
            if img.startswith("/"):
                img = "http:{}".format(img)

            liz.setArt({"thumb": img, "icon": img, "fanart": kodiutils.FANART})
            liz.setProperty('IsPlayable', 'true')
            liz.setInfo("Video",
                        infoLabels={
                            "plot":
                            html_parser.unescape(kodiutils.smart_str(prog))
                        })

            addDirectoryItem(
                plugin.handle,
                plugin.url_for(play,
                               rel_url=kodiutils.smart_str(rel_url),
                               channel=kodiutils.smart_str(channel),
                               img=kodiutils.smart_str(img),
                               prog=kodiutils.smart_str(prog)), liz, False)

    endOfDirectory(plugin.handle)
示例#4
0
def search():
    query = get_arg("q")
    offset = int(get_arg("offset", 0))
    # remove saved search item
    if bool(get_arg("delete", False)):
        bcfs.remove(query)
        xbmc.executebuiltin("Container.Refresh()")
        return True

    # View saved search menu
    if bool(get_arg("menu", False)):
        add_menu_item(search, "[{}]".format(ku.get_string(32016)),
                      {"new": True})  # [New Search]
        for item in bcfs.retrieve():
            text = item.encode("utf-8")
            add_menu_item(search, text, {"q": text})
        xp.setPluginCategory(plugin.handle, ku.get_string(32007))  # Search
        xp.endOfDirectory(plugin.handle)
        return True

    # look-up
    if bool(get_arg("new", False)):
        query = ku.user_input()
        bcfs.append(query)
        if not query:
            return False

    search_url = bcfs.get_search_url(query=query)
    data = bcfs.get_html(search_url)
    xp.setPluginCategory(
        plugin.handle, "{} '{}'".format(ku.get_string(32007),
                                        bcfs.query_decode(query)))
    parse_results(data)
示例#5
0
def index():
    direto = ListItem("[B]{}[/B]".format(kodiutils.get_string(32004)))
    addDirectoryItem(handle=plugin.handle,
                     listitem=direto,
                     isFolder=True,
                     url=plugin.url_for(live))

    programas = ListItem("[B]{}[/B]".format(kodiutils.get_string(32005)))
    addDirectoryItem(handle=plugin.handle,
                     listitem=programas,
                     isFolder=True,
                     url=plugin.url_for(programs))

    estudoemcasaitem = ListItem("[B]{}[/B]".format(
        kodiutils.get_string(32010)))
    addDirectoryItem(handle=plugin.handle,
                     listitem=estudoemcasaitem,
                     isFolder=True,
                     url=plugin.url_for(estudoemcasa))

    pesquisar = ListItem("[B]{}[/B]".format(kodiutils.get_string(32006)))
    addDirectoryItem(handle=plugin.handle,
                     listitem=pesquisar,
                     isFolder=True,
                     url=plugin.url_for(search))

    endOfDirectory(plugin.handle)
示例#6
0
def get_item_listing_text(event_name,
                          starttime,
                          duration,
                          status,
                          network,
                          blackout,
                          auth_types,
                          requires_package=False,
                          sport=None,
                          sport2=None):
    if sport != sport2 and len(sport2) > 0:
        sport += ' (' + sport2 + ')'
    length = duration
    if len(network) > 0:
        ename = '[B]%s[/B]' % event_name
    else:
        ename = event_name

    if starttime is not None:
        now = time.time()
        etime = time.strftime("%I:%M %p", starttime)
        if status == 'replay':
            etime_local = starttime
            if etime_local.tm_hour == 0 and etime_local.tm_min == 0:
                etime = time.strftime("%m/%d/%Y", starttime)
            else:
                etime = time.strftime("%m/%d %I:%M %p", starttime)
            ename = etime + ' - ' + ename
        elif status == 'live':
            starttime_time = time.mktime(starttime)
            length -= (time.time() - starttime_time)
            ename = ename + ' - ' + etime
        else:
            now_time = time.localtime(now)
            if now_time.tm_year == starttime.tm_year and \
                    now_time.tm_mon == starttime.tm_mon and \
                    now_time.tm_mday == starttime.tm_mday:
                etime = time.strftime("%I:%M %p", starttime)
            else:
                etime = time.strftime("%m/%d %I:%M %p", starttime)
            ename = etime + ' - ' + ename

    blackout_text = ''
    if blackout:
        blackout_text = get_string(30580)
    if len(blackout_text) > 0:
        ename = blackout_text + ' ' + ename
    if len(network) > 0:
        if get_setting_as_bool('NoColors'):
            ename = network + ' ' + ename
        else:
            # ename = '[B]%s[/B] %s' % (network, ename)
            ename = '%s %s' % (network, ename)

    requires_auth = check_auth_types(auth_types)
    if requires_auth and not adobe_activate_api.is_authenticated():
        ename = get_string(40300) + ' - ' + ename
    if requires_package:
        ename = get_string(40310) + ' - ' + ename
    return ename, length
示例#7
0
def check_error(session_json):
    status = session_json['status']
    if not status == 'success':
        dialog = xbmcgui.Dialog()
        dialog.ok(get_string(30037), get_string(30500) % session_json['message'])
        return True
    return False
示例#8
0
def show_episodes(url,offset,show_fanart):
	items = []
	url = urllib.unquote(url)
	url_offset = url+'&offset='+str(offset)
	data = get_page(url_offset)
	total = 0

	if data["content"]:
		content = json.loads(data["content"])
		if "total" in content.keys(): total = content["total"]
		for episode in content["episodes"]:
			liz = build_episode_item(episode,show_fanart)
			if liz:
				items.append((liz.getPath(), liz, False))
	if items:
		totalItems = len(items)
		addDirectoryItems(plugin.handle, items, totalItems=totalItems)
		
		#sort methods
		for method in [SORT_METHOD_UNSORTED,SORT_METHOD_LABEL,SORT_METHOD_EPISODE,SORT_METHOD_VIDEO_RUNTIME]:
			addSortMethod(plugin.handle, sortMethod=method ) 
		
		#next page
		if total and (int(total) - ((int(offset) + 1) * 25)) > 0:
			liz = ListItem(kodiutils.get_string(32016) + " (" + str(int(offset)+2) + ")")
			liz.setInfo( type="Video", infoLabels={"plot":kodiutils.get_string(32016)})
			liz.setArt({"thumb":next_thumb, "fanart": fanart_bg})
			addDirectoryItem(plugin.handle, plugin.url_for(show_episodes, urllib.quote(url, safe=''), int(offset)+1,  urllib.quote(show_fanart, safe='')), liz, True)

		setContent(plugin.handle, 'episodes')
	endOfDirectory(plugin.handle)
示例#9
0
def add_favorite():
    #data = plugin.args['query'][0].split('***')
    path = unquote(plugin.args['path'][0])
    name = unquote(plugin.args['name'][0])
    icon = ""
    if 'icon' in plugin.args:
        icon = unquote(plugin.args['icon'][0])
    fanart = ""
    if 'fanart' in plugin.args:
        fanart = unquote(plugin.args['fanart'][0])
    # load favorites
    global favorites
    if not favorites and xbmcvfs.exists(favorites_file_path):
        favorites_file = xbmcvfs.File(favorites_file_path)
        favorites = json.load(favorites_file)
        favorites_file.close()

    #favorites.update({data[0] : data[1]})
    favorites.update({path : {"name" : name, "icon" : icon, "fanart" : fanart}})
    # load favorites
    favorites_file = xbmcvfs.File(favorites_file_path, 'w')
    json.dump(favorites, favorites_file, indent=2)
    favorites_file.close()

    try:
        kodiutils.notification(kodiutils.get_string(32010), kodiutils.get_string(32011).format(codecs.decode(name, 'utf-8')))
    except TypeError:
        kodiutils.notification(kodiutils.get_string(32010), kodiutils.get_string(32011).format(codecs.decode(bytes(name, 'utf-8'), 'utf-8')))
    xbmc.executebuiltin('Container.Refresh')
    setResolvedUrl(plugin.handle, True, ListItem("none"))
示例#10
0
def index():
    """Main menu"""
    if ku.get_setting_as_bool("show_genres"):
        add_menu_item(themes, 32005, {
            "href": "en/categories/stories",
            "title": ku.get_string(32005)
        }, ku.icon("genres.png"))
    if ku.get_setting_as_bool("show_motions"):
        add_menu_item(themes, 32002, {
            "href": "en/categories/motions",
            "title": ku.get_string(32002)
        }, ku.icon("techniques.png"))
    if ku.get_setting_as_bool("show_characters"):
        add_menu_item(themes, 32003, {
            "href": "en/categories/characters",
            "title": ku.get_string(32003)
        }, ku.icon("characters.png"))
    if ku.get_setting_as_bool("show_authors"):
        add_menu_item(authors, 32004, art=ku.icon("authors.png"))
    if ku.get_setting_as_bool("show_experts"):
        add_menu_item(experts, 32023, art=ku.icon("experts.png"))
    if ku.get_setting_as_bool("show_techniques"):
        add_menu_item(themes, 32006, {
            "href": "en/categories/techniques",
            "title": ku.get_string(32006)
        }, ku.icon("techniques.png"))
    if ku.get_setting_as_bool("show_search"):
        add_menu_item(search, 32007, {"menu": True}, ku.icon("search.png"))
    if ku.get_setting_as_bool("show_settings"):
        add_menu_item(settings, 32010, art=ku.icon("settings.png"), directory=False)
    xp.setPluginCategory(plugin.handle, ADDON_NAME)
    xp.endOfDirectory(plugin.handle)
示例#11
0
def index():
    """Main menu"""
    if ku.get_setting_as_bool("show_home"):
        add_menu_item(show_category, 32009, {
            "href": "free",
            "title": ku.get_string(32009)}, ku.icon("home.png"))
    if ku.get_setting_as_bool("show_new"):
        add_menu_item(show_category, 32004, {
            "href": "free/new",
            "title": ku.get_string(32004)}, ku.icon("new.png"))
    if ku.get_setting_as_bool("show_popular"):
        add_menu_item(show_category, 32005, {
            "href": "free/popular",
            "title": ku.get_string(32005)}, ku.icon("popular.png"))
    if ku.get_setting_as_bool("show_collections"):
        add_menu_item(show_category, 32006, {
            "key": "collection",
            "href": "free/collections",
            "title": ku.get_string(32006),
            "isdir": True
        }, ku.icon("collection.png"))
    if ku.get_setting_as_bool("show_the_cut"):
        add_menu_item(show_category, "The Cut", {
            "key": "the-cut",
            "href": "the-cut",
            "title": "The Cut",
        }, ku.icon("the-cut.png"))
    if ku.get_setting_as_bool("show_search"):
        add_menu_item(search, 32007, {"menu": True}, ku.icon("search.png"))
    if ku.get_setting_as_bool("show_recent"):
        add_menu_item(recent, 32021)
    if ku.get_setting_as_bool("show_settings"):
        add_menu_item(settings, 32010, art=ku.icon("settings.png"), directory=False)
    xp.setPluginCategory(plugin.handle, ADDON_NAME)
    xp.endOfDirectory(plugin.handle)
示例#12
0
def new_index():
    # New index will have the channels listed and then the buckets from the watch
    # web product
    refresh = arg_as_bool('refresh')
    clear_cache = arg_as_bool('clear-cache')
    adobe_activate_api.clean_up_authorization_tokens()
    if clear_cache:
        util.clear_cache(get_v3_url(WATCH_API_V3_LIVE))
        util.clear_cache(get_v3_url(WATCH_API_V3_WEB_HOME))

    parse_json(WATCH_API_V3_LIVE)
    addDirectoryItem(plugin.handle, plugin.url_for(search),
                     ListItem(get_string(40500)), True)
    parse_json(WATCH_API_V3_WEB_HOME)

    current_time = time.strftime("%I:%M %p", time.localtime(time.time()))
    addDirectoryItem(plugin.handle, plugin.url_for(new_index, refresh=True),
                     ListItem(get_string(30850) % current_time), True)
    addDirectoryItem(plugin.handle, plugin.url_for(index),
                     ListItem(get_string(30790)), True)

    endOfDirectory(plugin.handle,
                   succeeded=True,
                   updateListing=refresh,
                   cacheToDisc=False)
示例#13
0
def index():
    icon = get_url(ids.collections_request_url.format(id=ids.icon_id, page="1"))
    live_icon = ""
    highlights_icon = ""
    highlights_id = ids.highlights_id
    mediathek_icon = ""
    mediathek_id = ids.mediathek_id
    tv_programm_icon = ""
    tv_programm_id = ids.tv_programm_id
    if icon != "":
        icon_json = json.loads(icon)
        for element in icon_json["results"]:
            if element["promotion_name"] == "Live":
                image_json = json.loads(element["images_json"])
                live_icon = image_json["menu_icon"]
            elif element["promotion_name"] == "Highlights":
                image_json = json.loads(element["images_json"])
                highlights_icon = image_json["menu_icon"]
                highlights_id = element["id"]
            elif element["promotion_name"] == "Mediathek":
                image_json = json.loads(element["images_json"])
                mediathek_icon = image_json["menu_icon"]
                mediathek_id = element["id"]
            elif element["promotion_name"] == "TV Programm":
                image_json = json.loads(element["images_json"])
                tv_programm_icon = image_json["menu_icon"]
    else:
        kodiutils.notification("ERROR getting URL", "using saved values")
    icon_search = get_url(ids.collections_request_url.format(id=ids.search_icon_id, page="1"))
    search_icon = ""
    settings_icon = ""
    if icon_search != "":
        icon_search_json = json.loads(icon_search)
        for item in icon_search_json["results"]:
            images = json.loads(item["images_json"])
            if item["name"] == "Search":
                if "navbar_icon" in images:
                    search_icon = images["navbar_icon"]
            elif item["name"] == "Service":
                if "navbar_icon" in images:
                    settings_icon = images["navbar_icon"]
    else:
        kodiutils.notification("ERROR getting URL", "using saved values")
    addDirectoryItem(plugin.handle, plugin.url_for(
        show_category, "livestream"), ListItem("Live", iconImage=live_icon, thumbnailImage=live_icon), True)
    addDirectoryItem(plugin.handle, plugin.url_for(
        get_by_collection, collection_id=highlights_id, page="1", recursive="True"), ListItem("Highlights", iconImage=highlights_icon, thumbnailImage=highlights_icon), True)
    addDirectoryItem(plugin.handle, plugin.url_for(
        show_mediathek, mediathek_id), ListItem("Mediathek", iconImage=mediathek_icon, thumbnailImage=mediathek_icon), True)
    addDirectoryItem(plugin.handle, plugin.url_for(
        show_category, "tvprogramm"), ListItem("TV Programm", iconImage=tv_programm_icon, thumbnailImage=tv_programm_icon), True)
    addDirectoryItem(plugin.handle, plugin.url_for(
        show_search), ListItem(kodiutils.get_string(32001), iconImage=search_icon, thumbnailImage=search_icon), True)
    addDirectoryItem(plugin.handle, plugin.url_for(
        show_category, "favorites"), ListItem(kodiutils.get_string(32002)), True)
    addDirectoryItem(plugin.handle, plugin.url_for(
        open_settings), ListItem(kodiutils.get_string(32003), iconImage=settings_icon, thumbnailImage=settings_icon))
    endOfDirectory(plugin.handle)
示例#14
0
def appletv_root_menu():
    trending_mode()
    addDirectoryItem(plugin.handle, plugin.url_for(appletv_featured),
                     make_list_item(get_string(30680)), True)
    addDirectoryItem(plugin.handle, plugin.url_for(appletv_sports),
                     make_list_item(get_string(30550)), True)
    addDirectoryItem(plugin.handle, plugin.url_for(appletv_channels),
                     make_list_item(get_string(30560)), True)
    endOfDirectory(plugin.handle)
示例#15
0
def delete_file(file_):
	file_ = urllib.unquote(file_) 
	#check if the file is in the download folder
	if xbmcvfs.exists(os.path.join(kodiutils.get_setting("downloadPath"),file_.split("/")[-1])):
		xbmcvfs.delete(file_)
		dialog.notification(kodiutils.get_string(32058),kodiutils.get_string(32056),icon=revision_icon)
		xbmc.executebuiltin("Container.Refresh")
	else:
		dialog.notification(kodiutils.get_string(32058),kodiutils.get_string(32057),icon=revision_icon)
示例#16
0
def tvos_root_menu():
    page_api.parse_json(TV_OS_HOME)

    addDirectoryItem(plugin.handle,
                     plugin.url_for(page_api.page_api_url, url=TV_OS_SPORTS),
                     make_list_item(get_string(30550)), True)
    addDirectoryItem(plugin.handle,
                     plugin.url_for(page_api.page_api_url, url=TV_OS_CHANNELS),
                     make_list_item(get_string(30560)), True)
    endOfDirectory(plugin.handle)
示例#17
0
def index():
    #All videos
    liz = ListItem("[I]%s[/I]" % (kodiutils.get_string(32000)))
    liz.setInfo(type="video", infoLabels={"plot": kodiutils.get_string(32001)})
    liz.setArt({"thumb": ICON, "icon": ICON, "fanart": FANART})
    addDirectoryItem(plugin.handle, plugin.url_for(all_videos, playlist="all"), liz, True)
    #Playlists
    for liz in youtubelib.get_playlists():
        addDirectoryItem(plugin.handle, plugin.url_for(all_videos, playlist=liz.getProperty("playlist_id")), liz, True)
    xbmcplugin.setContent(plugin.handle, 'tvshows')
    endOfDirectory(plugin.handle)
示例#18
0
def paginate(query, count, total, offset):
    # type (str, int, int, int) -> None
    """Adds search partition menu items"""
    if count < total and count == bfis.SEARCH_MAX_RESULTS:
        offset += 1
        next_page = "[{} {}]".format(ku.get_string(32011), offset + 1)  # [Page n+1]
        first_page = "[{} 1]".format(ku.get_string(32011))  # [Page 1]
        main_menu = "[{}]".format(ku.get_string(32012))  # [Menu]
        if offset > 1:
            add_menu_item(search, first_page, {"q": query, "offset": 0})
        add_menu_item(search, next_page, {"q": query, "offset": offset})
        add_menu_item(index, main_menu)
示例#19
0
def clear_data():
    try:
        for root, dirs, files in os.walk(addon_profile_path):
            for currentFile in files:
                protected_file = currentFile in KEEP_FILES
                if not protected_file and (
                        currentFile.lower().endswith('.xml')
                        or currentFile.lower().endswith('.json')):
                    os.remove(os.path.join(addon_profile_path, currentFile))
    except OSError:
        pass
    xbmcgui.Dialog().ok(get_string(40530), get_string(40531))
示例#20
0
def paginate(query, offset, count):
    # type (str, int, int) -> None
    """Adds pagination links as required"""
    offset += 1
    next_page = "[{} {}]".format(ku.get_string(32011), offset)  # [Page n+1]
    first_page = "[{} 1]".format(ku.get_string(32011))  # [Page 1]
    main_menu = "[{}]".format(ku.get_string(32012))  # [Menu]
    if offset > 2:
        add_menu_item(search, first_page, {"q": query, "page": 1})
    if count == eafa.SEARCH_MAX_RESULTS:
        add_menu_item(search, next_page, {"q": query, "page": offset})
    add_menu_item(index, main_menu)
示例#21
0
def paginate(query, count, total, offset):
    # type (str, int, int, int) -> None
    """Adds search partition menu items"""
    if count < total and count == bfis.SEARCH_MAX_RESULTS:
        offset += 1
        next_page = "[{} {}]".format(ku.get_string(32011),
                                     offset + 1)  # [Page n+1]
        first_page = "[{} 1]".format(ku.get_string(32011))  # [Page 1]
        main_menu = "[{}]".format(ku.get_string(32012))  # [Menu]
        if offset > 1:
            add_menu_item(search, first_page, {"q": query, "offset": 0})
        add_menu_item(search, next_page, {"q": query, "offset": offset})
        add_menu_item(index, main_menu)
示例#22
0
def paginate(data, method):
    """Adds pagination links as required"""
    if data is None:
        return
    items = data.find_all("li")
    for item in items:
        if "class" in item.attrs and any(x in item.attrs["class"] for x in ["disabled", "active", "prev", "next"]):
            continue
        action = item.find("a")
        add_menu_item(method, "[{} {}]".format(ku.get_string(32011), item.text), {  # [Page n]
            "href": action["href"]
        })
    add_menu_item(index, "[{}]".format(ku.get_string(32012)))  # [Menu]
示例#23
0
def index():
	#Build default menu items
	#0) Downloads folder
	if kodiutils.get_setting_as_bool("download") and kodiutils.get_setting_as_bool("folder") and kodiutils.get_setting("downloadPath") and xbmcvfs.exists(kodiutils.get_setting("downloadPath")):
		liz = ListItem("["+kodiutils.get_string(32012)+"]")
		liz.setInfo( type="Video", infoLabels={"plot":kodiutils.get_string(32012)})
		liz.setArt({"thumb":downloads_thumb, "fanart": fanart_bg})
		addDirectoryItem(plugin.handle, plugin.url_for(downloads), liz, True)
	
	#1) Most Recent
	liz = ListItem("["+kodiutils.get_string(32013)+"]")
	liz.setInfo( type="Video", infoLabels={"plot":kodiutils.get_string(32013)})
	liz.setArt({"thumb":recent_thumb, "fanart": fanart_bg})
	addDirectoryItem(plugin.handle, plugin.url_for(show_episodes, urllib.quote('%sgetEpisodes%s&grouping=latest' % (BASE, KEY), safe=''), 0, urllib.quote(fanart_bg, safe='')), liz, True)
	#2) Featured
	liz = ListItem("["+kodiutils.get_string(32023)+"]")
	liz.setInfo( type="Video", infoLabels={"plot":kodiutils.get_string(32023)}) 
	liz.setArt({"thumb":featured_thumb, "fanart": fanart_bg})
	addDirectoryItem(plugin.handle, plugin.url_for(show_episodes, urllib.quote('%sgetEpisodes%s&grouping=featured' % (BASE, KEY), safe=''), 0, urllib.quote(fanart_bg, safe='')), liz, True)
	#3) Archive shows
	liz = ListItem("["+kodiutils.get_string(32014)+"]")
	liz.setInfo( type="Video", infoLabels={"plot":kodiutils.get_string(32014)})
	liz.setArt({"thumb":archived_thumb, "fanart": fanart_bg})
	addDirectoryItem(plugin.handle, plugin.url_for(list_shows, urllib.quote("%sgetShows%s&grouping=archived" % (BASE,KEY), safe='')), liz, True)
	#List shows 
	list_shows(urllib.quote("%sgetShows%s" % (BASE,KEY), safe=''))
示例#24
0
def search():

    input_text = Dialog().input(kodiutils.get_string(32007), "",
                                INPUT_ALPHANUM)

    try:
        req = requests.get(
            "https://www.rtp.pt/play/pesquisa?q={}".format(input_text),
            headers=HEADERS_VOD).text
    except:
        raise_notification()

    pagei = ListItem("{} [B]{}[/B]".format(kodiutils.get_string(32008),
                                           input_text))
    addDirectoryItem(handle=plugin.handle,
                     listitem=pagei,
                     isFolder=False,
                     url="")

    soup = BeautifulSoup(req, 'html.parser')

    for a in soup.find('section').find_all('a'):
        url = a.get('href')
        title = a.get('title')
        img = a.find('img').get('src')
        metas = a.find_next_sibling('i').find_all('meta')
        description = metas[1].get('content')

        liz = ListItem("{}".format(kodiutils.compat_py23str(title)))
        liz.setArt({"thumb": img, "icon": img, "fanart": kodiutils.FANART})
        liz.setInfo("Video",
                    infoLabels={
                        "plot":
                        kodiutils.strip_html_tags(
                            kodiutils.compat_py23str(description)),
                        "title":
                        kodiutils.compat_py23str(title)
                    })

        addDirectoryItem(
            plugin.handle,
            plugin.url_for(programs_episodes,
                           title=kodiutils.compat_py23str(title),
                           ep=kodiutils.compat_py23str(title),
                           img=kodiutils.compat_py23str(img),
                           description=kodiutils.compat_py23str(description),
                           url=kodiutils.compat_py23str(url),
                           page=1), liz, True)
    endOfDirectory(plugin.handle)
示例#25
0
def check_espn_plus_error(session_json):
    if 'errors' in session_json:
        error_msg = ''
        for error in session_json['errors']:
            if 'description' in error:
                error_msg = error_msg + error['description'] + ' '
            elif 'code' in error:
                code = error['code']
                if code == 'not-entitled':
                    error_msg = error_msg + get_string(40280) + ' '
                elif code == 'access-token.invalid':
                    error_msg = error_msg + get_string(40290) + ' '
        dialog = xbmcgui.Dialog()
        dialog.ok(get_string(30037), get_string(30500) % error_msg)
        return True
示例#26
0
def highlights():
    href = get_arg("href", False)
    xp.setPluginCategory(plugin.handle, get_arg("title", ku.get_string(32006)))  # Highlights
    if not href:
        url = eafa.get_page_url("highlights.aspx")
        data = eafa.get_html(url)
        for item in data.find_all("div", "hl_box"):
            action = item.find("a")
            img = action.find("img")
            title = img["alt"]
            add_menu_item(
                highlights,
                title,
                {"href": action["href"], "title": title},
                art=ku.art(eafa.get_page_url(img["src"]))
            )
        xp.setContent(plugin.handle, "videos")
        xp.endOfDirectory(plugin.handle)
        return
    url = eafa.get_page_url(href)
    data = eafa.get_html(url)
    form = get_form_data(data)
    if form:
        parse_links(data, form)
    else:
        parse_results(data)
示例#27
0
def show_search():
    query = xbmcgui.Dialog().input(kodiutils.get_string(32001))
    if query != "":
        search_id = ids.search_id
        channels = json.loads(get_url(ids.categories_request_url.format(id=search_id), critical=True))
        shows = {}
        for channel in channels["category"]["children"]:
            channel_shows = json.loads(get_url(ids.categories_request_url.format(id=channel["id"]), critical=True))
            for show in channel_shows["category"]["children"]:
                shows.update({show["name"]+" | "+show["top_level_category"]["name"] : show})
        result = {}
        for show in shows.keys():
            if query.lower() in show.lower():
                result.update({show+" | "+shows[show]["top_level_category"]["name"] : shows[show]})
        for show in result:
            icon = ""
            fanart = ""
            if "images_json" in result[show]:
                images = json.loads(result[show]["images_json"])
                if "image_base" in images:
                    icon = images["image_base"]
                if "image_show_big" in images:
                    fanart = images["image_show_big"]
            listitem = ListItem(result[show]["name"]+" | "+result[show]["top_level_category"]["name"])
            listitem.setArt({'icon': icon, 'thumb': icon, 'poster': icon, 'fanart' : fanart})
            addDirectoryItem(plugin.handle, url=plugin.url_for(get_by_category, result[show]["id"]),
                listitem=listitem, isFolder=True)
    endOfDirectory(plugin.handle)
示例#28
0
def upcoming_event(event_id):
    starttime = arg_as_string('starttime')
    event_name = unquote_plus(arg_as_string('event_name'))
    packages = arg_as_list('packages')
    entitlements = espnplus.get_entitlements()
    logging.debug('Upcoming event chosen for %s, %s, %s' %
                  (starttime, packages, entitlements))
    has_entitlement = is_entitled(packages, entitlements)
    logging.debug('Entitled for content? %s' % has_entitlement)
    extra = ''
    if not has_entitlement:
        extra = get_string(40270) % (', '.join(packages))
    dialog = xbmcgui.Dialog()
    dialog.ok(get_string(30035),
              get_string(30036) % (event_name, starttime, extra))
    endOfDirectory(plugin.handle, succeeded=False, updateListing=True)
示例#29
0
def list_sports():
    espn_url = arg_as_string('espn_url')
    if 'action=replay' in espn_url:
        image = defaultreplay
    elif 'action=upcoming' in espn_url:
        image = defaultupcoming
    else:
        image = None
    addDirectoryItem(plugin.handle,
                     plugin.url_for(live_events_mode, espn_url=espn_url),
                     make_list_item(get_string(30034), icon=image), True)
    sports = []
    sport_elements = util.get_url_as_xml_cache(espn_url).findall(
        './/sportDisplayValue')
    for sport in sport_elements:
        sport = sport.text.encode('utf-8')
        if sport not in sports:
            sports.append(sport)
    for sport in sports:
        addDirectoryItem(
            plugin.handle,
            plugin.url_for(live_sport_events_mode,
                           sport=sport,
                           espn_url=espn_url), make_list_item(sport,
                                                              icon=image),
            True)

    xbmcplugin.addSortMethod(plugin.handle,
                             xbmcplugin.SORT_METHOD_VIDEO_SORT_TITLE)
    xbmcplugin.endOfDirectory(plugin.handle)
示例#30
0
def show_epg_programm(channel_id, date):
    icon = ""
    if 'icon' in plugin.args:
        icon = unquote(plugin.args['icon'][0])
    setContent(plugin.handle, 'tvshows')
    programs = json.loads(get_url(ids.epg_request_url.format(channel_id=channel_id, date=date), critical=True))
    for program in programs["programs"]:
        startDATES = datetime(*(time.strptime(program['starts_at'].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('%H:%M')
        goDATE =  LOCALstart.strftime('%d.%m.%Y')

        endDATES = datetime(*(time.strptime(program['ends_at'].split(' +')[0], '%Y/%m/%d %H:%M:%S')[0:6])) # 2019/06/23 14:10:00 +0000
        LOCALend = utc_to_local(endDATES)
        endTIMES = LOCALend.strftime('%H:%M')

        if '\n' in program["name"]:
            name = program["name"].split('\n')[1]
        else:
            name = program["name"]

        listitem = ListItem("[COLOR chartreuse]"+startTIMES+": [/COLOR]"+program["name"].replace("\n", ": "))
        listitem.setInfo(type='Video', infoLabels={'Title': name,
            'Plot': kodiutils.get_string(32016).format(goDATE, startTIMES, endTIMES)+program["description"],
            'mediatype': 'video', 'TvShowTitle': program["name"].split('\n')[0], 'Date': goDATE,
            'Duration': (LOCALend-LOCALstart).total_seconds()})
        images = json.loads(program["images_json"])
        if "image_base" in images:
            listitem.setArt({'icon': images["image_base"], 'thumb': images["image_base"], 'poster': images["image_base"], 'fanart': images["image_base"]})
        else:
            listitem.setArt({'icon': unquote(icon), 'thumb': unquote(icon), 'poster': unquote(icon), 'fanart': unquote(icon)})
        addDirectoryItem(plugin.handle, url=None, listitem=listitem)
    endOfDirectory(plugin.handle)
示例#31
0
def live():
    choice = 0
    live_videos = [video for video in youtubelib.get_live_videos()]
    if not live_videos:
        kodiutils.notification(ADDON_NAME, kodiutils.get_string(32009))
        return

    elif len(live_videos) > 1:
        choice = kodiutils.select(kodiutils.get_string(32010),
                                  [video["label"] for video in live_videos])

    if choice > -1:
        stream = 'plugin://plugin.video.youtube/play/?video_id=%s' % (
            live_videos[choice]["video_id"])
        liz = ListItem()
        liz.setPath(stream)
        xbmcplugin.setResolvedUrl(plugin.handle, True, liz)
示例#32
0
def login_espn_plus():
    if not espnplus.have_valid_login_id_token():
        logging.debug('Requesting login id token')
        semaphore = threading.Semaphore(0)
        result_queue = Queue()

        license_plate, ws = espnplus.perform_license_plate_auth_flow(
            semaphore, result_queue)
        progress_dialog = xbmcgui.DialogProgress()
        progress_dialog.create(get_string(40100), get_string(40110),
                               license_plate)
        espnplus.start_websocket_thread(ws)
        times = 0
        sleep_time = 1
        max_time = 180
        max_times = max_time / sleep_time
        # wait a maximum of 3 minutes
        while times < max_times:
            time.sleep(sleep_time)
            canceled = progress_dialog.iscanceled()
            acquired = semaphore.acquire(blocking=False)
            logging.debug('Canceled: %s Acquired: %s' % (canceled, acquired))
            seconds_left = max_time - times * sleep_time
            minutes, seconds = divmod(seconds_left, 60)
            percent = int(times / max_times)
            progress_dialog.update(percent, get_string(40110), license_plate,
                                   get_string(40120) % (minutes, seconds))
            if canceled or acquired:
                break
            times = times + 1
        ws.close()
        progress_dialog.close()

        token = None
        try:
            token = result_queue.get(block=True, timeout=1)
        except Empty as e:
            logging.error('No result from websocket %s', e)

        if token is not None and 'id_token' in token:
            espnplus.handle_license_plate_token(token)
        else:
            dialog = xbmcgui.Dialog()
            dialog.ok(get_string(30037), get_string(40130))
            set_setting('LoggedInToEspnPlus', False)
            return False

    if not espnplus.has_valid_bam_account_access_token():
        espnplus.request_bam_account_access_token()

    logging.debug('Bam token %s' % espnplus.get_bam_account_access_token())
    dialog = xbmcgui.Dialog()
    dialog.ok(get_string(40000), get_string(40101))
    set_setting('LoggedInToEspnPlus', True)
    return True
示例#33
0
def search():
    query = get_arg("q")
    href = get_arg("href", False)

    # remove saved search item
    if bool(get_arg("delete", False)):
        jafc.remove(query)
        xbmc.executebuiltin("Container.Refresh()")
        return True

    # View saved search menu
    if bool(get_arg("menu", False)):
        add_menu_item(search, "[{}]".format(ku.get_string(32016)), {"new": True})  # [New Search]
        for item in jafc.retrieve():
            text = item.encode("utf-8")
            add_menu_item(search, text, {"q": text})
        xp.setPluginCategory(plugin.handle, ku.get_string(32007))  # Search
        xp.endOfDirectory(plugin.handle)
        return True

    # look-up
    if bool(get_arg("new", False)):
        query = ku.user_input()
        jafc.append(query)
        if not query:
            return False

    url = jafc.get_page_url(href) if href else jafc.get_search_url(query)
    data = jafc.get_html(url)
    results = data.find("ul", "work-results")
    if not results:
        return

    paginate(data.find("ul", "pager-menu"), search)
    for item in results.find_all("li", "work-result"):
        action = item.find("a")
        img = item.find("img", "thumbnail")
        add_menu_item(play_film,
                      item.find("h2").text,
                      {"href": action["href"]},
                      info=get_info(action["href"]),
                      art=ku.art(jafc.get_page_url(img["src"])),
                      directory=False)
    xp.setPluginCategory(plugin.handle, "{} '{}'".format(ku.get_string(32016), query))
    xp.endOfDirectory(plugin.handle)
示例#34
0
def index():
    """Main menu"""
    if ku.get_setting_as_bool("show_highlights"):
        add_menu_item(highlights,
                      ku.get_string(32006),
                      art=ku.icon("highlights.png"))
    if ku.get_setting_as_bool("show_genres"):
        add_menu_item(browse,
                      ku.get_string(32005),
                      {"id": "genre_items", "title": ku.get_string(32005)},
                      ku.icon("genres.png"))
    if ku.get_setting_as_bool("show_subjects"):
        add_menu_item(browse,
                      ku.get_string(32003),
                      {"id": "subject_items", "title": ku.get_string(32003)},
                      ku.icon("subjects.png"))
    if ku.get_setting_as_bool("show_people"):
        add_menu_item(browse,
                      ku.get_string(32004),
                      {"id": "people_items", "title": ku.get_string(32004)},
                      ku.icon("people.png"))
    if ku.get_setting_as_bool("show_search"):
        add_menu_item(search, 32007, {"menu": True}, ku.icon("search.png"))
    if ku.get_setting_as_bool("show_settings"):
        add_menu_item(settings, 32010, art=ku.icon("settings.png"), directory=False)
    xp.setPluginCategory(plugin.handle, ADDON_NAME)
    xp.endOfDirectory(plugin.handle)
示例#35
0
def search():
    search_settings.set_last_search_query('')
    addDirectoryItem(plugin.handle, plugin.url_for(search_input),
                     ListItem('[B]%s[/B]' % get_string(40501)), True)
    for search_history in search_settings.search_history:
        addDirectoryItem(plugin.handle,
                         plugin.url_for(search_results, q=search_history),
                         ListItem(search_history), True)
    endOfDirectory(plugin.handle, succeeded=True, cacheToDisc=False)
示例#36
0
def show_epg(channel_id):
    icon = ""
    if 'icon' in plugin.args:
        icon = plugin.args['icon'][0]
    today = date.today()
    # past epg
    addDirectoryItem(plugin.handle, plugin.url_for(
        show_epg_past, channel_id=channel_id, icon=icon), ListItem(kodiutils.get_string(32014)), True)
    # show epg from today
    addDirectoryItem(plugin.handle, plugin.url_for(
        show_epg_programm, channel_id=channel_id, date=today.strftime("%Y%m%d"), icon=icon),
        ListItem(kodiutils.get_string(32015).format(kodiutils.get_string(32017))), True)
    # future epg
    for i in range(1, 14, 1):
        future_date = today + timedelta(days = i)
        addDirectoryItem(plugin.handle, plugin.url_for(
            show_epg_programm, channel_id=channel_id, date=future_date.strftime("%Y%m%d"), icon=icon),
            ListItem(kodiutils.get_string(32015).format(future_date.strftime("%d.%m.%Y"))), True)
    endOfDirectory(plugin.handle)
示例#37
0
def add_directories(id, page = "1", recursive=False, prefix=""):
    dir = get_url(ids.collections_request_url.format(id=id, page=page), critical=True)
    dir_json = json.loads(dir)
    for item in dir_json["results"]:
        setContent(plugin.handle, 'tvshows')
        images = json.loads(item["images_json"])
        if item["type"] == "Category":
            name = item["name"]
            if "top_level_category" in item:
                if item["top_level_category"]["name"].lower() == item["name"].lower():
                    name = item["promotion_name"]
            listitem = ListItem(name)
            listitem.setArt({'icon': images["image_base"],'thumb': images["image_base"], 'poster': images["image_base"]})
            if "image_show_big" in images:
                listitem.setArt({"fanart" : images["image_show_big"]})
            plot = ""
            if 'description' in item and item['description'] != None:
                try:
                    startDATES = datetime(*(time.strptime(item['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, item["id"]),
                listitem=listitem, isFolder=True)
        elif item["type"] == "Collection":
            if item["ui_tag"] == "":
                add_directories(item["id"], prefix=item["title"]+" ")
            elif recursive:
                add_directories(item["id"])
            else:
                icon = ""
                if "image_base" in images:
                    icon = images["image_base"]
                addDirectoryItem(plugin.handle, url=plugin.url_for(get_by_collection, item["id"], "1"),
                    listitem=ListItem(prefix+item["title"], iconImage=icon, thumbnailImage=icon), isFolder=True)
    if int(dir_json["pagination"]["page"]) * int(dir_json["pagination"]["items_per_page"]) < int(dir_json["pagination"]["total_items"]):
        if kodiutils.get_setting_as_bool("limitlist"):
            addDirectoryItem(plugin.handle, url=plugin.url_for(get_by_collection, id, str(int(page)+1)),
                listitem=ListItem(kodiutils.get_string(32007).format(str(int(page)+1))), isFolder=True)
        else:
            get_by_collection(id, str(int(page)+1))
示例#38
0
def index():
    stream_location = get_input(heading=kodiutils.get_string(32001))

    if stream_location:
        item = make_item(stream_location, play=True)

        addDirectoryItem(plugin.handle, stream_location, item, isFolder=False)
        endOfDirectory(plugin.handle)

    return False
def get_upload_playlist():
    api_endpoint = 'https://www.googleapis.com/youtube/v3/channels?part=contentDetails&id=%s&key=%s' % (CHANNEL_ID,YOUTUBE_API_KEY)
    try:
        resp = requests.get(api_endpoint).json()
    except ValueError:
        kodiutils.log(kodiutils.get_string(32004), xbmc.LOGERROR)
        return None
    if "items" in list(resp.keys()):
        uploads_playlist = resp["items"][0]["contentDetails"]["relatedPlaylists"]["uploads"]
        return uploads_playlist
示例#40
0
def remove_favorite():
    data = unquote(plugin.args['query'][0])
    # load favorites
    global favorites
    if not favorites and xbmcvfs.exists(favorites_file_path):
        favorites_file = xbmcvfs.File(favorites_file_path)
        favorites = json.load(favorites_file)
        favorites_file.close()

    name = favorites[data]["name"]
    del favorites[data]
    # load favorites
    favorites_file = xbmcvfs.File(favorites_file_path, 'w')
    json.dump(favorites, favorites_file, indent=2)
    favorites_file.close()

    kodiutils.notification(kodiutils.get_string(32010), kodiutils.get_string(32012).format(name))
    xbmc.executebuiltin('Container.Refresh')
    setResolvedUrl(plugin.handle, True, ListItem("none"))
def programs_category():
    page = plugin.args["page"][0]
    cat_id = plugin.args["id"][0]
    cat_name = plugin.args["name"][0]

    try:
        req = requests.get("https://www.rtp.pt/play/bg_l_pg/?listcategory={}&page={}".format(
            cat_id,
            page), headers=HEADERS_VOD)
        req.encoding = "latin-1"
        req = req.text
    except:
        raise_notification()
        return

    pagei = ListItem("[B]{}[/B] - {} {}".format(kodiutils.compat_py23str(cat_name), kodiutils.get_string(32009), page))
    pagei.setProperty('IsPlayable', 'false')
    addDirectoryItem(handle=plugin.handle, listitem=pagei, isFolder=False, url="")

    soup = BeautifulSoup(req, 'html.parser')

    for a in soup.find_all('a'):
        url = a.get('href')
        title = a.get('title')
        img = a.find('img').get('src')
        metas = a.find_next_sibling('i').find_all('meta')
        description = metas[1].get('content')
        ep = metas[0].get('content')[-12:]

        liz = ListItem("{} ({})".format(
            kodiutils.compat_py23str(title),
            kodiutils.compat_py23str(ep))
        )
        liz.setArt({"thumb": img,
                    "icon": img,
                    "fanart": kodiutils.FANART})
        liz.setInfo("Video", infoLabels={"plot": kodiutils.strip_html_tags(kodiutils.compat_py23str(description)), "title": kodiutils.compat_py23str(title)})

        addDirectoryItem(
            plugin.handle,
            plugin.url_for(
                programs_episodes,
                title=kodiutils.compat_py23str(title),
                ep=kodiutils.compat_py23str(ep),
                img=img,
                description=kodiutils.compat_py23str(description),
                url=kodiutils.compat_py23str(url),
                page=1
            ), liz, True)

    newpage = str(int(page) + 1)
    nextpage = ListItem("[B]{}[/B] - {} {} >>>".format(kodiutils.compat_py23str(cat_name), kodiutils.get_string(32009), newpage))
    addDirectoryItem(handle=plugin.handle, listitem=nextpage, isFolder=True, url=plugin.url_for(programs_category, name=kodiutils.compat_py23str(cat_name), id=cat_id, page=newpage))

    endOfDirectory(plugin.handle)
示例#42
0
def search():
    query = get_arg("q")
    page = int(get_arg("page", 1))

    # remove saved search item
    if bool(get_arg("delete", False)):
        eafa.remove(query)
        xbmc.executebuiltin("Container.Refresh()")
        return True

    # View saved search menu
    if bool(get_arg("menu", False)):
        add_menu_item(search, "[{}]".format(ku.get_string(32016)), {"new": True})  # [New Search]
        for item in eafa.retrieve():
            text = item.encode("utf-8")
            add_menu_item(search, text, {"q": text})
        xp.setPluginCategory(plugin.handle, ku.get_string(32007))  # Search
        xp.endOfDirectory(plugin.handle)
        return True

    # look-up
    if bool(get_arg("new", False)):
        query = ku.user_input()
        eafa.append(query)
        if not query:
            return False

    form = get_form_data(eafa.get_html(eafa.EAFA_SEARCH_URI))
    if not form:
        return False
    data = eafa.post_html(eafa.EAFA_SEARCH_URI, {
        "__EVENTTARGET": "ctl00$ContentPlaceHolder1$ucSearch$ToolkitScriptManager1",
        "__EVENTARGUMENT": eafa.get_search_params(query, page),
        "__VIEWSTATE": form["state"]
    })
    xp.setPluginCategory(
        plugin.handle,
        "{} '{}'".format(ku.get_string(32007),  # Search 'query'
                         eafa.query_decode(query))
    )
    parse_results(data, page, query)
示例#43
0
def index():
	try:
		req = __session__.get("http://www.rtp.pt/play/", headers=__headers__).text
	except:
		kodiutils.ok(kodiutils.get_string(32000),kodiutils.get_string(32001))
		exit(0)

	match=re.compile('<a title=".+?direto (.+?)" href="(.+?)" class="mask-live "><img alt=".+?" src="(.+?)" class="img-responsive">.+?<span class="small"><b>(.+?)</b>').findall(req)
	if match:
		for channel,rel_url, img, prog in match:
			liz = ListItem("[B][COLOR blue]{}[/B][/COLOR] ({})".format(kodiutils.smart_str(channel), kodiutils.smart_str(prog)))
			if img.startswith("/"):
				img = "http:{}".format(img)
			
			liz.setArt({"thumb": img, "icon": img, "fanart": kodiutils.FANART})
			liz.setProperty('IsPlayable', 'true')
			liz.setInfo("Video", infoLabels={"plot": html_parser.unescape(kodiutils.smart_str(prog))})
			
			addDirectoryItem(plugin.handle, plugin.url_for(play, rel_url=kodiutils.smart_str(rel_url), channel=kodiutils.smart_str(channel), img=kodiutils.smart_str(img), prog=kodiutils.smart_str(prog) ), liz, False)
	
	endOfDirectory(plugin.handle)
示例#44
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)
示例#45
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)
示例#46
0
def show_category():
    key = get_arg("key", "category")
    href = get_arg("href", "free")
    is_dir = bool(get_arg("isdir", False))
    category = get_arg("title", ku.get_string(32008))
    url = bfis.get_page_url(href)
    html = bfis.get_html(url)
    for card in html.findAll(*JIG[key]["card"]):
        action = card.find(*JIG[key]["action"])
        if action is None:
            continue

        title = card.find(*JIG[key]["title"]).text.encode("utf-8")
        info = {
            "mediatype": "video",
            "plot": bfis.html_to_text(card.find(*JIG[key]["plot"]).text.encode("utf-8"))
        }
        if "meta" in JIG[key]:
            try:
                genre, year, duration = card.find_all(*JIG[key]["meta"], limit=3)
                info["genre"] = genre.text.encode("utf-8")
                info["year"] = bfis.text_to_int(year.text.encode("utf-8"))
                info["duration"] = bfis.text_to_int(duration.text.encode("utf-8"))
            except (ValueError, TypeError):
                pass
        add_menu_item(
            show_category if is_dir else play_film,
            title,
            {"href": action["href"], "title": title},
            ku.art(card.find("img").attrs),
            info,
            is_dir
        )
    xp.setPluginCategory(plugin.handle, category)
    xp.setContent(plugin.handle, "videos")
    xp.addSortMethod(plugin.handle, xp.SORT_METHOD_LABEL_IGNORE_THE)
    xp.addSortMethod(plugin.handle, xp.SORT_METHOD_GENRE)
    xp.endOfDirectory(plugin.handle)
示例#47
0
def play():
	rel_url = plugin.args["rel_url"][0]
	channel = plugin.args["channel"][0]
	prog = plugin.args["prog"][0]
	icon = plugin.args["img"][0]
	try:
		req = __session__.get("{}{}".format(__base_url__, rel_url)).text
	except:
		kodiutils.ok(kodiutils.get_string(32000),kodiutils.get_string(32002))
		exit(0)

	is_pseudo_aes = bool(re.findall("var aes = true", req))
		
	streams = re.compile('new RTPPlayer\(.*file\:.+?"(.+?)"', re.DOTALL).findall(req)
	
	if streams:
		print streams
		final_stream_url = None
		for stream in streams:
			if ".m3u8" in stream.split('/')[-1]: 
				final_stream_url = stream
				break

	if is_pseudo_aes:
		try:
			req = __session__.post("http://www.rtp.pt/services/playRequest.php", headers={"RTPPlayUrl":	final_stream_url})
			final_stream_url = req.headers["RTPPlayWW"]
		except:
			kodiutils.ok(kodiutils.get_string(32000),kodiutils.get_string(32002))
			exit(0)		

	if final_stream_url:
		liz = ListItem("[B][COLOR blue]{}[/B][/COLOR] ({})".format(kodiutils.smart_str(channel), kodiutils.smart_str(prog)))
		liz.setArt({"thumb": icon, "icon": icon})
		liz.setProperty('IsPlayable', 'true')
		liz.setPath("{}|User-Agent=Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36&Referer=http://www.rtp.pt/play/".format(final_stream_url))
		setResolvedUrl(plugin.handle, True, liz)
	else:
		kodiutils.ok(kodiutils.get_string(32000),kodiutils.get_string(32002))
		exit(0)
示例#48
0
def search():
    query = get_arg("q")
    offset = int(get_arg("offset", 0))
    # remove saved search item
    if bool(get_arg("delete", False)):
        bfis.remove(query)
        xbmc.executebuiltin("Container.Refresh()")
        return True

    # View saved search menu
    if bool(get_arg("menu", False)):
        add_menu_item(search, "[{}]".format(ku.get_string(32016)), {"new": True})  # [New Search]
        for item in bfis.retrieve():
            text = item.encode("utf-8")
            add_menu_item(search, text, {"q": text})
        xp.setPluginCategory(plugin.handle, ku.get_string(32007))  # Search
        xp.endOfDirectory(plugin.handle)
        return True

    # look-up
    if bool(get_arg("new", False)):
        query = ku.user_input()
        bfis.append(query)
        if not query:
            return False

    search_url = bfis.get_search_url(query, offset)
    data = bfis.get_json(search_url)
    if data is None:
        return False

    hits = data.get("hits", False)
    if not hits:
        return False

    # Results
    results = hits.get("hits", [])
    paginate(query,
             len(results),
             int(hits.get("total", 0)),
             offset)
    for element in results:
        data = element.get("_source", False)
        if not data:
            continue

        title = data.get("title", "")
        duration = data.get("duration", 0)  # can still be NoneType *
        info = {
            "originaltitle": data.get("original_title", ""),
            "plot": bfis.html_to_text(data.get("standfirst", "")),
            "genre": data.get("genre", ""),
            "cast": data.get("cast", ""),
            "director": data.get("director", ""),
            "year": int(data.get("release_date", 0)),
            "duration": 0 if duration is None else int(duration) * 60,  # *
            "mediatype": "video"
        }
        add_menu_item(
            play_film,
            title,
            {"href": data.get("url")},
            ku.art(data.get("image", ["Default.png"])[0]),
            info,
            False)
    xp.setContent(plugin.handle, "videos")
    xp.setPluginCategory(plugin.handle, "{} '{}'".format(ku.get_string(32007), bfis.query_decode(query)))
    xp.addSortMethod(plugin.handle, xp.SORT_METHOD_LABEL_IGNORE_THE)
    xp.addSortMethod(plugin.handle, xp.SORT_METHOD_GENRE)
    xp.addSortMethod(plugin.handle, xp.SORT_METHOD_VIDEO_YEAR)
    xp.addSortMethod(plugin.handle, xp.SORT_METHOD_DURATION)
    xp.endOfDirectory(plugin.handle)
示例#49
0
def raise_notification():
	kodiutils.ok(kodiutils.get_string(32000),kodiutils.get_string(32002))
	exit(0)