Example #1
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 #2
0
def _():
    edb.connect()
    edb.add(plugin.path)
    edb.close()
    response = request(plugin.path)
    document = BeautifulSoup(response.text,
                             'html.parser').find('ul',
                                                 {'class': 'all-episode'})
    items = []

    for a in reversed(document.find_all('a')):
        item = ListItem('[{}] {}'.format(
            a.find('span').text,
            a.find('h3').text.strip('\n ').encode('utf-8')))
        item.setInfo('video', {})
        item.setProperty('IsPlayable', 'true')
        items.append((plugin.url_for(a.attrs['href']), item, False))

    xbmcplugin.setContent(plugin.handle, 'videos')
    xbmcplugin.addDirectoryItems(plugin.handle, items, len(items))
    xbmcplugin.endOfDirectory(plugin.handle)
Example #3
0
def show_search_input():
    s = dialog.input('Search')
    # print s
    # p = Post('http://www.zxzjs.com/index.php?s=vod-search',{ 'wd': s })
    p = Get('https://www.zxzjs.com/vodsearch/-------------.html?wd=%s' % s)
    # print p
    # it = re.finditer( r'<a class=\"v-thumb stui-vodlist__thumb lazyload\" href=\"(.*?)\" title=\"(.*?)\" data-original=\"(.*?)\">', p)
    it = re.finditer(
        r'<a class="stui-vodlist__thumb lazyload" href="(.*?)" title="(.*?)" data-original="(.*?)">',
        p)

    for match in it:
        id = re.search(r'\d+', match.group(1)).group()
        print match.group(2)
        # print id
        addDirectoryItem(
            plugin.handle,
            plugin.url_for(show_detail, id=id, img=match.group(3)),
            ListItem(match.group(2), thumbnailImage=match.group(3)), True)

    endOfDirectory(plugin.handle)
Example #4
0
def _():
    items = [(plugin.url_for('/filter-select/category/korean-drama'),
              ListItem(localized_str(33200)), True),
             (plugin.url_for('/filter-select/category/japanese-drama'),
              ListItem(localized_str(33201)), True),
             (plugin.url_for('/filter-select/category/taiwanese-drama'),
              ListItem(localized_str(33202)), True),
             (plugin.url_for('/filter-select/category/hong-kong-drama'),
              ListItem(localized_str(33203)), True),
             (plugin.url_for('/filter-select/category/chinese-drama'),
              ListItem(localized_str(33204)), True),
             (plugin.url_for('/filter-select/category/other-asia-drama'),
              ListItem(localized_str(33205)), True),
             (plugin.url_for('/filter-select/category/thailand-drama'),
              ListItem(localized_str(33206)), True)]

    xbmcplugin.setContent(plugin.handle, 'videos')
    xbmcplugin.addDirectoryItems(plugin.handle, items, len(items))
    xbmcplugin.endOfDirectory(plugin.handle)
Example #5
0
def list_groups():
    if xbmcvfs.exists(txtfile):
        groups = []
        f = xbmcvfs.File(txtfile)
        try:
            lines = json.load(f)
        except Exception:
            lines = []
        for line in lines:
            if len(line) > 5:
                if group_by == group_by_type:
                    group = line["type"]
                else:
                    group = line["source"]
                if group not in groups:
                    groups.append(group)
                    if group_by == group_by_type:
                        nm = group
                        ic = imgPath + '/resources/' + group + '.png'
                    else:
                        nm = group
                        ads = group.split("/")
                        if len(ads) > 2: nm = ads[2]
                        if group == lang(30002):
                            ic = imgPath + '/resources/movie.png'
                        elif group == lang(30003):
                            ic = imgPath + '/resources/episode.png'
                        elif group == lang(30004):
                            ic = imgPath + '/resources/musicvideo.png'
                        else:
                            try:
                                la = xbmcaddon.Addon(nm)
                                nm = la.getAddonInfo('name')
                                ic = la.getAddonInfo('icon')
                            except Exception:
                                ic = imgPath + '/resources/addons.png'
                    addDirectoryItem(addon_handle,
                                     url({'menu': group.encode("utf-8")}),
                                     ListItem(nm, iconImage=ic), True)
        f.close()
def live():
    # Request dvr
    try:
        req = requests.get("http://www.rtp.pt/play/direto", headers=HEADERS).text
    except:
        raise_notification()
        return

    match = re.compile(r'<a.+?title=".+? - (.+?)" href="/play/(.+?)".*?\n.*?\n.*?<img alt="(.+?)" src="(.+?)".*?\n.*?\n.*?width:(.+?)%').findall(req)

    for prog, key, emissao, img, percent in match:
        dvr = prog
        if img.startswith("/"):
            img = "http:{}".format(img)
        progimg = img
        progpercent = percent
        prefix = "em direto"
        name = emissao[emissao.index(prefix) + len(prefix):].strip() if prefix in emissao else emissao

        liz = ListItem("[B][COLOR blue]{}[/COLOR][/B] ({}) [B]{}%[/B]".format(
            kodiutils.compat_py23str(name),
            kodiutils.strip_html_tags(kodiutils.compat_py23str(dvr)),
            kodiutils.compat_py23str(progpercent))
        )
        liz.setArt({"thumb": progimg,
                    "icon": progimg,
                    "fanart": kodiutils.FANART})
        liz.setProperty('IsPlayable', 'true')
        liz.setInfo("Video", infoLabels={"plot": kodiutils.strip_html_tags(kodiutils.compat_py23str(dvr))})
        addDirectoryItem(
            plugin.handle,
            plugin.url_for(
                live_play,
                label=kodiutils.compat_py23str(name),
                channel=kodiutils.compat_py23str(key.lower()),
                img=kodiutils.compat_py23str(progimg),
                prog=kodiutils.compat_py23str(dvr)
            ), liz, False)

    endOfDirectory(plugin.handle)
Example #7
0
def main_menu():
    ''' The Regio TV plugin main menu '''
    from xbmcgui import ListItem
    import xbmcplugin

    xbmcplugin.setContent(plugin.handle, content='files')
    xbmcplugin.setPluginCategory(plugin.handle, category='Zenders')
    xbmcplugin.setPluginFanart(plugin.handle, image='DefaultAddonPVRClient.png')
    xbmcplugin.addSortMethod(plugin.handle, sortMethod=xbmcplugin.SORT_METHOD_UNSORTED)
    xbmcplugin.addSortMethod(plugin.handle, sortMethod=xbmcplugin.SORT_METHOD_LABEL)

    listing = []
    for channel in CHANNELS:
        is_folder = False
        is_playable = True

        label = '{name} [COLOR gray]| {label}[/COLOR]'.format(**channel)
        plot = '[B]{name}[/B]\nRegio {label}\n\n[I]{description}[/I]\n\n[COLOR yellow]{website}[/COLOR]'.format(**channel)
        list_item = ListItem(label=label, label2=channel.get('label'), offscreen=True)
        list_item.setProperty(key='IsInternetStream', value='true' if is_playable else 'false')
        list_item.setProperty(key='IsPlayable', value='true' if is_playable else 'false')
        list_item.setInfo(type='video', infoLabels=dict(
            lastplayed='',
            mediatype='video',
            playcount=0,
            plot=plot,
        ))
        list_item.setArt(dict(
            icon='DefaultAddonPVRClient.png',
            thumb=channel.get('logo'),
        ))

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

        url = channel.get('live_stream')
        listing.append((url, list_item, is_folder))

    succeeded = xbmcplugin.addDirectoryItems(plugin.handle, listing, len(listing))
    xbmcplugin.endOfDirectory(plugin.handle, succeeded, updateListing=False, cacheToDisc=True)
Example #8
0
def play_episode():
    response = request(plugin.path)
    document = BeautifulSoup(response.text, 'html.parser')
    title = document.find('h1').text.strip()
    all_server = document.find_all('li', {'data-video': True})
    position = Dialog().select('Choose Server',
                               [server.contents[0] for server in all_server])

    if position != -1:
        xbmc.executebuiltin('ActivateWindow(busydialognocancel)')
        resolveurl.add_plugin_dirs(__plugins__)

        try:
            url = resolveurl.resolve(all_server[position].attrs['data-video'])

            if url:
                item = ListItem(title, path=url)
                sub = re.search('&sub=([^&]+)',
                                all_server[position].attrs['data-video'])

                if sub:
                    response = session.get(
                        'https://embed.watchasian.to/player/sub/index.php?id='
                        + sub.group(1))
                    item.setSubtitles([__temp__])

                    with open(__temp__, 'w') as o:
                        for i, text in enumerate(re.split(
                                'WEBVTT\r\n\r\n|\r\n\r\n', response.text)[1:],
                                                 start=1):
                            o.write('{}\r\n{}\r\n\r\n'.format(
                                i, text.encode('utf-8')))

                xbmcplugin.setResolvedUrl(plugin.handle, True, item)
            else:
                raise
        except:
            Dialog().notification('Couldn\'t Resolve Server', '')

        xbmc.executebuiltin('Dialog.Close(busydialognocancel)')
Example #9
0
def play_source():
    plugin = get_router_instance()
    website_name = plugin.args["website_name"][0]
    source_url = plugin.args["source_url"][0]

    logger.debug("Website: " + website_name)
    logger.debug("Source URL: " + source_url)

    embedded_processors = {
        "MP4UPLOAD": mp4upload,
        "STREAMANGO": streamango,
    }

    decrypted_source = None
    processor = embedded_processors.get(
        website_name.split(".")[1].upper(), None)

    try:
        if processor:
            res = requests.get(source_url)
            soup = BeautifulSoup(res.text, 'html.parser')
            if processor:
                (err, decrypted_source) = processor.retrieve_source_url(soup)

                if err:
                    raise err
        else:
            # For sources without custom logic use the urlresolver package
            decrypted_source = resolveurl.resolve(source_url)
            logger.debug(decrypted_source)

        if not processor and not decrypted_source:
            raise AnimePieException(ADDON.getLocalizedString(32001))
        elif decrypted_source:
            play_item = ListItem(path=decrypted_source)
            xbmc.Player().play(decrypted_source, play_item)

    except AnimePieException as e:
        logger.error(e.args)
        xbmc.executebuiltin("Notification(Error," + e.args[0] + ")")
Example #10
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)

	final_stream_url = None
	if streams:
		print streams
		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)
Example #11
0
def __build_folder(xml_element, plex_section_id=None):
    url = "plugin://%s/" % v.ADDON_ID
    key = xml_element.get('fastKey', xml_element.get('key'))
    if not key.startswith('/'):
        key = '/library/sections/%s/%s' % (plex_section_id, key)
    params = {
        'mode': "browseplex",
        'key': key,
    }
    if plex_section_id:
        params['id'] = plex_section_id
    listitem = ListItem(xml_element.get('title'))
    thumb = xml_element.get('thumb') or \
        'special://home/addons/%s/icon.png' % v.ADDON_ID
    art = xml_element.get('art') or \
        'special://home/addons/%s/fanart.jpg' % v.ADDON_ID
    listitem.setThumbnailImage(thumb)
    listitem.setArt({'fanart': art, 'landscape': art})
    xbmcplugin.addDirectoryItem(handle=int(argv[1]),
                                url="%s?%s" % (url, urlencode(params)),
                                isFolder=True,
                                listitem=listitem)
Example #12
0
def play_track_cut(track_id, cut_id, album_id):
    media_url = session.get_media_url(track_id, cut_id=cut_id)
    log("Playing Cut %s: %s" % (cut_id, media_url))
    disableInputstreamAddon = False
    if not media_url.startswith('http://') and not media_url.startswith('https://') and \
        not 'app=' in media_url.lower() and not 'playpath=' in media_url.lower():
        # Rebuild RTMP URL
        if KODI_VERSION >= (17, 0):
            media_url = 'rtmp://%s' % media_url
            disableInputstreamAddon = True
        else:
            host, tail = media_url.split('/', 1)
            app, playpath = tail.split('/mp4:', 1)
            media_url = 'rtmp://%s app=%s playpath=mp4:%s' % (host, app,
                                                              playpath)
    li = ListItem(path=media_url)
    if disableInputstreamAddon:
        # Krypton can play RTMP Audio Streams without inputstream.rtmp Addon
        li.setProperty('inputstreamaddon', '')
    mimetype = 'audio/flac' if session._config.quality == Quality.lossless and session.is_logged_in else 'audio/mpeg'
    li.setProperty('mimetype', mimetype)
    xbmcplugin.setResolvedUrl(plugin.handle, True, li)
Example #13
0
def create_gui_element_from_snap(set_info, image, art_type='unset'):
    """Returns Kodi ListItem element for a snapshot."""

    # set art
    if image:
        dir_split = path.dirname(image).split('/')
        if len(dir_split) < 2:
            art = art_type
        else:
            art = dir_split[-2]
            # dir is the same as swl, then set filename as art
            if art == set_info['swl_name']:
                art = path.basename(image)[:-4]
    else:
        art = art_type

    # create listitem
    list_item = ListItem()
    list_item.setLabel("{}: {} ({})".format(art, set_info['detail'],
                                            set_info['swl_name']))
    list_item.setArt({'icon': image})
    # label to later set
    list_item.setProperty(
        'detail', "{}: {} {}".format(art, set_info['swl_name'],
                                     set_info['detail']))
    aspect = check_image_aspect(set_info)
    if aspect == 'Vertical':
        list_item.setProperty('Vertical', '1')
        list_item.setProperty('Horizontal', '')
        list_item.setProperty('NotScaled', '')
    elif aspect == 'Horizontal':
        list_item.setProperty('Vertical', '')
        list_item.setProperty('Horizontal', '1')
        list_item.setProperty('NotScaled', '')
    elif aspect == 'NotScaled':
        list_item.setProperty('Vertical', '')
        list_item.setProperty('Horizontal', '')
        list_item.setProperty('NotScaled', '1')
    return list_item
Example #14
0
def list_live():
    if current_time - live_data_time > 30 * 60:
        live_data = new_channels.get_live_list()
        with io.open(live_list_file, "w", encoding="utf-8") as f:
            f.write(
                json.dumps(live_data,
                           indent=2,
                           sort_keys=True,
                           ensure_ascii=False))
        addon.setSetting("live_data_time36", str(int(time.time())))
    else:
        with io.open(live_list_file, "r", encoding="utf-8") as f:
            live_data = json.loads(f.read())

    list_items = []
    for day, events in live_data.items():
        for event in events:
            if len(event["channel_list"]) == 0:
                continue
            event_time = time_from_zone(
                datetime.utcfromtimestamp(int(event["start"])).strftime("%c"),
                "%Y-%m-%d %H:%M")
            title = "[{0}] {1}".format(event_time, event["title"])
            li = ListItem(title, offscreen=True)
            li.setProperty("IsPlayable", "true")
            li.setInfo(type="Video",
                       infoLabels={
                           "Title": title,
                           "mediatype": "video"
                       })
            li.setContentLookup(False)
            url = plugin.url_for(event_resolve,
                                 title=event["title"].encode("utf-8"))
            list_items.append((url, li, False))

    xbmcplugin.addSortMethod(plugin.handle, xbmcplugin.SORT_METHOD_LABEL)
    xbmcplugin.addDirectoryItems(plugin.handle, list_items)
    xbmcplugin.setContent(plugin.handle, "videos")
    xbmcplugin.endOfDirectory(plugin.handle)
Example #15
0
def play(video_id):
    urls = nrktv.program(video_id).media_urls
    if not urls:
        return

    # Enrich HTTP headers for foreign viewers
    for index, url in enumerate(urls):
        urls[index] = enrichForForeignViewers(url)

    url = urls[0] if len(urls) == 1 else "stack://" + ' , '.join(urls)

    xbmcplugin.setResolvedUrl(plugin.handle, True, ListItem(path=url))
    player = xbmc.Player()
    subtitle = subs.get_subtitles(video_id)
    if subtitle:
        # Wait for stream to start
        start_time = time.time()
        while not player.isPlaying() and time.time() - start_time < 10:
            time.sleep(1.)
        player.setSubtitles(subtitle)
        if xbmcaddon.Addon().getSetting('showsubtitles') != '1':
            player.showSubtitles(False)
Example #16
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 #17
0
def ParseDetail(url):
    p = Get(url)
    it = re.finditer(
        r"""<h2 class="entry-title"><a href="(.*?)" rel="bookmark">(.*?)</a>.*?<iframe src="(.*?)".*?></iframe>""",
        p)

    for match in it:
        vid = match.group(3)
        title = match.group(2)
        li = ListItem(title)
        li.setInfo('video', {})
        # addDirectoryItem(plugin.handle, plugin.url_for(play_Video, video=vid, title=title), li, False)
        url = ParseUrl(vid)
        print(url)
        addDirectoryItem(plugin.handle, url, li, False)

    mnav = re.search(
        r"""<div class="nav-previous"><a href="(.*?/page/\d+)" >上一頁</a>""", p)
    if mnav:
        return mnav.group(1)
    else:
        return None
Example #18
0
    def __init__( self, *args, **kwargs ):
        self.main = args[ 0 ]

        self.english_xml = "%s/%s/strings.xml" % ( self.main.FolderLanguage, self.main.DefaultLanguage )
        self.current_xml = "%s/%s/strings.xml" % ( self.main.FolderLanguage, self.main.CurrentLanguage )

        # get current_xml source
        temp_strings = ET.getTempStrings( xbmc.translatePath( self.current_xml ) )

        # get english_xml source
        self.listitems = []
        try:
            # parse source
            root = ET.parseSource( xbmc.translatePath( self.english_xml ) )
            strings = root.findall( "string" )

            for count, string in enumerate( strings ):
                id = string.attrib.get( "id" )
                label1 = fixe_line_return( ( temp_strings.get( id ) or "" ) )
                label2 = fixe_line_return( ( string.text or "" ) )

                UnTranslated = ( temp_strings.get( id ) is None )
                UnTranslated = UnTranslated or ( label1 and not label2 ) or ( label2 and not label1 )

                listitem = ListItem( label1, label2 )
                listitem.setProperty( "DefaultString", label1 )
                listitem.setProperty( "id", id )
                listitem.setProperty( "Position", str( count ) )

                listitem.setProperty( "IsModified", "" )
                listitem.setProperty( "UnTranslated", repr( UnTranslated ).lower() )
                
                listitem.setProperty( "CurrentLanguage", self.main.CurrentLanguage )
                listitem.setProperty( "DefaultLanguage", self.main.DefaultLanguage )

                self.listitems.append( listitem )
        except:
            print_exc()
        del temp_strings
Example #19
0
def show_room(day, year, room):
    exp = './day[@index="{}"]/room[@name="{}"]/event'.format(day, room)
    root = fetch_xml(year)
    for event in root.findall(exp):
        if not contains_videos(event.findall('./links/link')):
            continue

        event_id = event.attrib['id']
        title = event.find('title').text
        track = event.find('track').text
        subtitle = event.find('subtitle').text
        persons = [p.text for p in event.find('./persons/person')]
        abstract = event.find('abstract').text
        duration = event.find('duration').text
        if abstract:
            abstract = abstract.replace('<p>', '').replace('</p>', '')

        item = ListItem(title)
        item.setProperty('IsPlayable', 'true')
        item.setInfo(
            'video', {
                'cast': persons,
                'genre': track,
                'plot': abstract,
                'tagline': subtitle,
                'title': title,
            })

        # duration is formatted as 01:30
        hour, minute = duration.split(':')
        seconds = timedelta(hours=int(hour),
                            minutes=int(minute)).total_seconds()

        item.addStreamInfo('video', {'duration': seconds})
        url = plugin.url_for(show_event, year=year, event_id=event_id)
        addDirectoryItem(plugin.handle, url, item, False)
        setContent(plugin.handle, 'videos')

    endOfDirectory(plugin.handle)
Example #20
0
def searchByIMDB(imdb, season=0, episode=0, version=0):
    filename = 'wizdom.imdb.%s.%s.%s.json' % (imdb, season, episode)
    url = "http://json.%s/search.php?action=by_id&imdb=%s&season=%s&episode=%s&version=%s" % (
        myDomain, imdb, season, episode, version)

    wlog("searchByIMDB:%s" % url)
    json = cachingJSON(filename, url)
    subs_rate = []  # TODO remove not in used
    if json != 0:
        for item_data in json:
            listitem = ListItem(label="Hebrew", label2=item_data["versioname"])
            listitem.setArt({'thumb': 'he'})
            # thumbnailImage="he", iconImage="%s" % (item_data["score"]/2)
            if int(item_data["score"]) > 8:
                listitem.setProperty("sync", "true")
            url = "plugin://%s/?action=download&versioname=%s&id=%s&imdb=%s&season=%s&episode=%s" % (
                myScriptID, item_data["versioname"], item_data["id"], imdb,
                season, episode)
            addDirectoryItem(handle=int(sys.argv[1]),
                             url=url,
                             listitem=listitem,
                             isFolder=False)
def list_genre():
    req = s.get(base_url + "/de/genres")
    soup = BeautifulSoup(req.text, "html.parser")
    genres_h3 = soup.find("div", class_="pt-bordered-tiles").find_all(
        "div", class_="pt-movie-tile")
    for h3 in genres_h3:
        link = h3.find("a")
        img = h3.find("img")
        listItem = ListItem(img['alt'])
        listItem.setProperty('IsPlayable', 'false')
        img = img['data-src']
        if img is None:
            img = ICON
        else:
            img = "https:" + img

        listItem.setArt({'thumb': ICON, 'fanart': FANART, 'poster': img})
        addDirectoryItem(_handle,
                         get_url(action='listing', url=link.get("href")),
                         listItem, True)

    endOfDirectory(_handle)
Example #22
0
def vod_list(cat=None):
    if current_time - vod_data_time > cache_time * 60 * 60:
        new_channels.get_api_key()
        vod_data = new_channels.get_vod_list()
        with io.open(vod_list_file, "w", encoding="utf-8") as f:
            f.write(
                json.dumps(vod_data,
                           indent=2,
                           sort_keys=True,
                           ensure_ascii=False))
        addon.setSetting("vod_data_time36", str(int(time.time())))
    else:
        with io.open(vod_list_file, "r", encoding="utf-8") as f:
            vod_data = json.loads(f.read())

    list_items = []
    for channel in vod_data.get("eY2hhbm5lbHNfbGlzdA=="):
        if channel.get("cat_id") == cat:
            title = b64decode(channel.get("ZY19uYW1l")[:-1])
            icon = b64decode(channel.get("abG9nb191cmw=")[1:])
            image = "{0}|{1}".format(icon,
                                     urlencode({"User-Agent": user_agent}))
            c_id = channel.get("rY19pZA==")

            li = ListItem(title, offscreen=True)
            li.setProperty("IsPlayable", "true")
            li.setInfo(type="Video",
                       infoLabels={
                           "Title": title,
                           "mediatype": "video"
                       })
            li.setArt({"thumb": image, "icon": image})
            li.setContentLookup(False)
            url = plugin.url_for(play_vod, c_id=c_id)
            list_items.append((url, li, False))

    xbmcplugin.addDirectoryItems(plugin.handle, list_items)
    xbmcplugin.setContent(plugin.handle, "videos")
    xbmcplugin.endOfDirectory(plugin.handle)
Example #23
0
def playdash(channel_name):
    is_helper = inputstreamhelper.Helper('mpd', drm='com.widevine.alpha')
    if is_helper.check_inputstream():
        play_item = ListItem()
        _auth = _hotstarauth_key()
        url = "http://hotstar.live.cdn.jio.com/hotstar_isl/{0}/master.mpd?hdnea={1}".format(
            channel_name, _auth)
        play_item.setPath(url)
        play_item.setProperty('inputstreamaddon', is_helper.inputstream_addon)
        play_item.setProperty('inputstream.adaptive.manifest_type', 'mpd')
        play_item.setProperty('inputstream.adaptive.license_type',
                              'com.widevine.alpha')
        play_item.setProperty(
            'inputstream.adaptive.license_key',
            'https://ipl.service.expressplay.com/hms/wv/rights/?ExpressPlayToken=BQAAABNlKfMAAAAAAGB5RXIUhuAKhb0o_gG4s6_qdxw4y5xQZyNGjvsbfiltjdLAStqy3hyJnAzQPRNmTknPc1nMTsezyHAxVCdu2VYmI-bCaJTYMefMpfs-fql1lF_B7Zrj-qyxdlafY1xKq42c6z1i9s1FPsE_z8wV6FC8BHNpMw&req_id=2f652cd6|User-Agent=hotstar&Content-Type=application/octet-stream|R{SSM}|'
        )
        play_item.setProperty('inputstream.adaptive.stream_headers',
                              "User-Agent=hotstar")
        play_item.setMimeType('application/dash+xml')
        play_item.setContentLookup(False)

        setResolvedUrl(plugin.handle, True, listitem=play_item)
Example #24
0
def GetJson(imdb, season=0, episode=0, version=0):
    filename = 'wizdom.imdb.%s.%s.%s.json' % (imdb, season, episode)
    url = "http://api.wizdom.xyz/search.id.php?imdb=%s&season=%s&episode=%s&version=%s" % (
        imdb, season, episode, version)

    MyLog("GetJson:%s" % url)
    json_object = Caching(filename, url)
    subs_rate = []
    if json_object <> 0:
        for item_data in json_object:
            listitem = ListItem(label="Hebrew",
                                label2=item_data["versioname"],
                                thumbnailImage="he",
                                iconImage="%s" % (item_data["score"] / 2))
            if int(item_data["score"]) > 8:
                listitem.setProperty("sync", "true")
            url = "plugin://%s/?action=download&versioname=%s&id=%s" % (
                MyScriptID, item_data["versioname"], item_data["id"])
            addDirectoryItem(handle=int(sys.argv[1]),
                             url=url,
                             listitem=listitem,
                             isFolder=False)
Example #25
0
def event(key):
    def itemMaker(source, fn):
        li = ListItem("[%s][%s] %s (%s)" % (
            source.get("quality", "XY"),
            source.get("lang", "Xyz"),
            source.get("channel", "UNKNOWN"),
            fn.NAME,
        ))
        return li
    sources = get_all_sources(key)
    sources_dec = []
    for s in sources:
        source_fn = url_to_source(s["url"])
        sources_dec.append({"el": s, "fn": source_fn})
    items = list(map(lambda s: (PLUGIN.url_for(s["fn"].root,
                                            url=urllib.quote(s["el"]["url"].encode('utf8'), safe='')),
                                itemMaker(s["el"], s["fn"]), True), sources_dec))
    if (len(sources) == 0):
        li = ListItem("No playable sources found")
        addDirectoryItem(PLUGIN.handle, "", li)
    addDirectoryItems(PLUGIN.handle, items)
    endOfDirectory(PLUGIN.handle)
def list_schedule():
    schedule_id = plugin.args['schedule_id'][0]

    if 'day' in plugin.args:
        day = plugin.args['day'][0]

        schedule = e.collection(schedule_id, {
            'include': 'default',
            'pf[day]': day
        })

        videos = schedule.videos(onlyAvailable=False)

        for video in sorted(videos, key=lambda v: video_sort_key(v, False)):
            item = listitem_from_video(schedule,
                                       video,
                                       include_start_time=True)

            addDirectoryItem(plugin.handle,
                             plugin.url_for(play_video, id=video['id']), item,
                             False, len(videos))
    else:
        today = date.today()
        for day_idx in range(14):
            day_delta = day_idx - 7
            day = today + timedelta(days=day_delta)

            day_formatted = day.strftime("%Y-%m-%d")
            item = ListItem(day_formatted)
            item.select(day == today)

            addDirectoryItem(
                plugin.handle,
                plugin.url_for(list_schedule,
                               schedule_id=schedule_id,
                               day=day_formatted), item, True)

    endOfDirectory(plugin.handle)
def show_Genre(showType,genre,pageNumber):
    showsPerPage = 30
    itemIndex=int(pageNumber) * showsPerPage
    url='https://api.cld.dtvce.com/discovery/metadata/genre/v1/service/genres/{0}/programs?itemIndex={1}&itemCount={2}&showType={3}&fisProperties=poster-ni,340,191,dc&clientContext='.format(genre,itemIndex,showsPerPage,showType)
    jsonKey='resources'
    json_source = get_JSON(url,jsonKey)
    
    totalShows = json_source['estimatedMatches']

    if showType == 'shows':
        setContent(plugin.handle, 'tvshows')
    for item in json_source[jsonKey]:
        li = ListItem(item['title'])
        imageUrl = get_image(item['images'][0])
        li.setArt({'icon': imageUrl, 'thumb': imageUrl})
        addDirectoryItem(handle=plugin.handle, url=plugin.url_for(show_Series, query='sectionId={0}'.format(item['resourceId'])), listitem=li, isFolder=True)
    
    currentPage = int(pageNumber) + 1
    totalPages = (totalShows // showsPerPage) + 1
    nextPage = currentPage + 1
    prevPage = currentPage - 1
    nextFive = currentPage + 5
    prevFive = currentPage - 5
    if nextPage > totalPages:
        nextPage = 1
    if prevPage < 1:
        prevPage = totalPages
    if nextFive > totalPages:
        nextFive = nextFive - totalPages
    if prevFive < 1:
        prevFive = prevFive + totalPages
    
    addDirectoryItem(handle=plugin.handle, url=plugin.url_for(show_Genre, 'show', genre, nextPage - 1), listitem=ListItem('Next: Page {0}'.format(nextPage)), isFolder=True)
    addDirectoryItem(handle=plugin.handle, url=plugin.url_for(show_Genre, 'show', genre, prevPage - 1), listitem=ListItem('Previous: Page {0}'.format(prevPage)), isFolder=True)
    addDirectoryItem(handle=plugin.handle, url=plugin.url_for(show_Genre, 'show', genre, nextFive - 1), listitem=ListItem('Forward 5 Pages: Page {0}'.format(nextFive)), isFolder=True)
    addDirectoryItem(handle=plugin.handle, url=plugin.url_for(show_Genre, 'show', genre, prevFive - 1), listitem=ListItem('Back 5 Pages: Page {0}'.format(prevFive)), isFolder=True)
    
    endOfDirectory(plugin.handle)
Example #28
0
def show_conference(conf):
    data = None
    try:
        data = http.fetch_data('conferences/' + conf, wants_insecure())
    except http.FetchError:
        return

    setContent(plugin.handle, 'movies')

    aspect = calc_aspect(maybe_json(data, 'aspect_ratio', '16:9'))

    for event in sorted(data['events'], key=operator.itemgetter('title')):
        item = ListItem(event['title'])
        item.setThumbnailImage(event['thumb_url'])
        item.setProperty('IsPlayable', 'true')

        info = {
            'cast': maybe_json(event, 'persons', []),
            'credits': ", ".join(maybe_json(event, 'persons', [])),
            'genre': " / ".join(maybe_json(event, 'tags', [])),
            'plot': maybe_json(event, 'description', ''),
            'tagline': maybe_json(event, 'subtitle', '')
        }
        json_date_to_info(event, 'date', info)
        item.setInfo('video', info)

        streamInfo = {}
        length = maybe_json(event, 'length', 0)
        if length > 0:
            streamInfo['duration'] = length
        if aspect:
            streamInfo['aspect'] = aspect
        item.addStreamInfo('video', streamInfo)

        url = plugin.url_for(resolve_event,
                             event=event['url'].rsplit('/', 1)[1])
        addDirectoryItem(plugin.handle, url, item, False)
    endOfDirectory(plugin.handle)
    def _generate_listitem(title_item):
        """ Generate a ListItem from a TitleItem
        :type title_item: TitleItem
        :rtype xbmcgui.ListItem
        """
        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 #30
0
def add_radio_channels():
    radio_channels = [
        ("NRK P1", "http://lyd.nrk.no/nrk_radio_p1_ostlandssendingen_mp3"),
        ("NRK P1+", "http://lyd.nrk.no/nrk_radio_p1pluss_mp3_h.m3u"),
        ("NRK P2", "http://lyd.nrk.no/nrk_radio_p2_mp3_h"),
        ("NRK P3", "http://lyd.nrk.no/nrk_radio_p3_mp3_h"),
        ("NRK P13", "http://lyd.nrk.no/nrk_radio_p13_mp3_h"),
        ("Alltid nyheter", "http://lyd.nrk.no/nrk_radio_alltid_nyheter_mp3_h"),
        ("Alltid RR", "http://lyd.nrk.no/nrk_radio_p3_radioresepsjonen_mp3_h"),
        ("Jazz", "http://lyd.nrk.no/nrk_radio_jazz_mp3_h"),
        ("Klassisk", "http://lyd.nrk.no/nrk_radio_klassisk_mp3_h"),
        ("Folkemusikk", "http://lyd.nrk.no/nrk_radio_folkemusikk_mp3_h"),
        ("mP3", "http://lyd.nrk.no/nrk_radio_mp3_mp3_h"),
        ("P3 Urørt", "http://lyd.nrk.no/nrk_radio_p3_urort_mp3_h"),
        ("Sport", "http://lyd.nrk.no/nrk_radio_sport_mp3_h"),
        ("Sápmi", "http://lyd.nrk.no/nrk_radio_sami_mp3_h"),
        ("Super", "http://lyd.nrk.no/nrk_radio_super_mp3_h"),
        ("P1 Buskerud", "http://lyd.nrk.no/nrk_radio_p1_buskerud_mp3_h"),
        ("P1 Finnmark", "http://lyd.nrk.no/nrk_radio_p1_finnmark_mp3_h"),
        ("P1 Hedemark og Oppland", "http://lyd.nrk.no/nrk_radio_p1_hedmark_og_oppland_mp3_h"),
        ("P1 Hordaland", "http://lyd.nrk.no/nrk_radio_p1_hordaland_mp3_h"),
        ("P1 Møre og Romsdal", "http://lyd.nrk.no/nrk_radio_p1_more_og_romsdal_mp3_h"),
        ("P1 Nordland", "http://lyd.nrk.no/nrk_radio_p1_nordland_mp3_h"),
        ("P1 Oslo og Akershus", "http://lyd.nrk.no/nrk_radio_p1_ostlandssendingen_mp3_h"),
        ("P1 Rogaland", "http://lyd.nrk.no/nrk_radio_p1_rogaland_mp3_h"),
        ("P1 Sogn og Fjordane", "http://lyd.nrk.no/nrk_radio_p1_sogn_og_fjordane_mp3_h"),
        ("P1 Sørlandet", "http://lyd.nrk.no/nrk_radio_p1_sorlandet_mp3_h"),
        ("P1 Telemark", "http://lyd.nrk.no/nrk_radio_p1_telemark_mp3_h"),
        ("P1 Troms", "http://lyd.nrk.no/nrk_radio_p1_troms_mp3_h"),
        ("P1 Trøndelag", " http://lyd.nrk.no/nrk_radio_p1_trondelag_mp3_h"),
        ("P1 Vestfold", "http://lyd.nrk.no/nrk_radio_p1_vestfold_mp3_h"),
        ("P1 Østfold", "http://lyd.nrk.no/nrk_radio_p1_ostfold_mp3_h"),
    ]
    for title, url in radio_channels:
        li = ListItem(title,)
        li.setProperty('mimetype', "audio/mpeg")
        li.setProperty('isplayable', 'true')
        addDirectoryItem(plugin.handle, enrichForForeignViewers(url), li, False)