예제 #1
0
def cl_news_util(args, cache):
    if not cache:
        htmlfile = utils.get_html_file('http://www.theguardian.com/us')
        parser = GUARDIANHTMLParser()
        parser.feed(htmlfile)
        articlelist = parser.articlelist
    else:
        articlelist = cache

    if len(args) > 1:
        if args[1] == '--headlines' or args[1] =='-h':
            utils.gu_headlines(articlelist)
            return articlelist

        if len(args) > 2:

            if args[1] == '--open' or args[1] == '-o':
                index = args[2]
                article = get_gu_article(articlelist, index)
                utils.go_to_page(article['url'])
                return articlelist

            if args[1] == '--read' or args[1] == '-r':
                index = args[2]
                article = get_gu_article(articlelist, index)
                htmlfile = utils.get_html_file(article['url'])
                abbrevurl = article['url'][28:]
                print '\n' + article['title'] + ' -- ' + abbrevurl
                print '==================\n'
                htmlfile = htmlfile.decode('utf-8')
                parser = GUARDIANARTICLEParser()
                parser.feed(htmlfile)
                return articlelist

    utils.handle_error('ap_error')
예제 #2
0
def list_episodes(params):
    try:
        episodes = comm.get_episodes(params)
        listing = []
        if episodes:
            page = episodes[0].page
            for e in episodes:
                li = xbmcgui.ListItem(e.title,
                                      iconImage=e.thumb,
                                      thumbnailImage=e.thumb)
                li.setArt({'fanart': e.fanart})
                url = '{0}?action=listepisodes{1}'.format(
                    _url, e.make_kodi_url())
                is_folder = False
                li.setProperty('IsPlayable', 'true')
                li.setInfo(
                    'video', {
                        'plot': e.desc,
                        'plotoutline': e.desc,
                        'duration': e.duration,
                        'date': e.get_airdate()
                    })
                listing.append((url, li, is_folder))

            if episodes[0].total_episodes - (page * 30) > 30:
                url = '{0}?action=listshows{1}&page={2}'.format(
                    _url, episodes[0].make_kodi_url(), episodes[0].page + 1)
                is_folder = True
                li = xbmcgui.ListItem('next page')
                listing.append((url, li, is_folder))
        xbmcplugin.addDirectoryItems(_handle, listing, len(listing))
        xbmcplugin.endOfDirectory(_handle)
    except Exception as e:
        utils.handle_error('Unable to list episodes', exc=e)
예제 #3
0
def play_video(params):
    try:
        params['url'] += '|User-Agent=%s' % config.USER_AGENT
        play_item = xbmcgui.ListItem(path=params['url'])
        xbmcplugin.setResolvedUrl(_handle, True, play_item)
    except Exception:
        utils.handle_error('Unable to play video')
예제 #4
0
def make_list(url):

    try:
        params = utils.get_url(url)

        category = params.get('category')
        videos = comm.get_videos(category)

        utils.log("Found %s videos" % len(videos))

        # fill media list
        ok = True
        for v in videos:

            listitem = xbmcgui.ListItem(label=v.get_title(),
                                        thumbnailImage=v.get_thumbnail())
            listitem.setInfo('video', v.get_xbmc_list_item())
            listitem.addStreamInfo('video', v.get_xbmc_stream_info())
            listitem.setProperty('IsPlayable', 'true')

            # Build the URL for the program, including the list_info
            url = "%s?%s" % (sys.argv[0], v.make_xbmc_url())

            # Add the program item to the list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                             url=url,
                                             listitem=listitem,
                                             isFolder=False)

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except Exception, e:
        utils.handle_error('Unable to fetch video list', exc=e)
예제 #5
0
def make_programs_list(url):
    try:
        params = utils.get_url(url)
        programs = comm.get_series(params["series_id"])
        num_programs = len(programs)

        ok = True
        for p in programs:

            # Don't show any 'promo' shows. They don't get returned by Brightcove
            if p.duration and p.duration < 1000:
                utils.log("Skipping program %s (duration <19 mins)" % p.get_list_title())
                num_programs -= 1
                continue

            listitem = xbmcgui.ListItem(label=p.get_list_title(), iconImage=p.get_thumbnail(), thumbnailImage=p.get_thumbnail())
            listitem.setInfo('video', p.get_xbmc_list_item())

            if hasattr(listitem, 'addStreamInfo'):
                listitem.addStreamInfo('audio', p.get_xbmc_audio_stream_info())
                listitem.addStreamInfo('video', p.get_xbmc_video_stream_info())

            # Build the URL for the program, including the list_info
            url = "%s?program_id=%s" % (sys.argv[0], p.id)

            # Add the program item to the list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False, totalItems=num_programs)

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except:
        utils.handle_error("Unable to fetch program listing")
예제 #6
0
def make_category_list():

    try:
        iview_config = comm.get_config()
        categories = comm.get_categories(iview_config)
        categories = sorted(categories, key=lambda k: k['name'].lower())
        # All category is disabled for now due to API issues
        # https://github.com/andybotting/xbmc-addon-abc-iview/issues/1454
        #categories.insert(0, {'name':'All', 'keyword':'0-z'})

        ok = True
        for g in categories:
            url = "%s?category=%s" % (sys.argv[0], g['keyword'])
            listitem = xbmcgui.ListItem(g['name'])

            # Add the program item to the list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                             url=url,
                                             listitem=listitem,
                                             isFolder=True)

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except:
        utils.handle_error()
예제 #7
0
def make_programs_list(url):
    try:
        params = utils.get_url(url)
        programs = comm.get_series_from_feed(params['series'], category=params['category'])

        ok = True
        for p in programs:
            listitem = xbmcgui.ListItem(label=p.get_list_title(), iconImage=p.get_thumbnail(), thumbnailImage=p.get_thumbnail())
            listitem.setInfo('video', p.get_xbmc_list_item())
            listitem.setProperty('IsPlayable', 'true')

            if hasattr(listitem, 'addStreamInfo'):
                listitem.addStreamInfo('audio', p.get_xbmc_audio_stream_info())
                listitem.addStreamInfo('video', p.get_xbmc_video_stream_info())

            # Build the URL for the program, including the list_info
            url = "%s?play=true&%s" % (sys.argv[0], p.make_xbmc_url())

            # Add the program item to the list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False, totalItems=len(programs))

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except:
        utils.handle_error('Unable to fetch program list')
예제 #8
0
def play(url):
    try:
        params = utils.get_url(url)
        if 'id' in params:
            video_id = params['id']
            v = comm.get_video(video_id)
        elif 'url' in params or 'ooyalaid' in params:
            v = classes.Video()
            v.parse_xbmc_url(url)
        
        if 'ooyalaid' in params:
            loginToken = ooyalahelper.get_afl_user_token()
            stream_url = ooyalahelper.get_m3u8_playlist(params['ooyalaid'],
                                                        'true', loginToken,
                                                        'AFL')
        else:
            stream_url = v.get_url()

        listitem = xbmcgui.ListItem(label=v.get_title(),
                                    iconImage=v.get_thumbnail(),
                                    thumbnailImage=v.get_thumbnail(),
                                    path=stream_url)

        listitem.addStreamInfo('video', v.get_xbmc_stream_info())
        listitem.setInfo('video', v.get_xbmc_list_item())
         
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem=listitem)
        
    except Exception as e:
        utils.handle_error('', e)
예제 #9
0
def make_list(round_id):
    utils.log("Fetching match list for round %s..." % round_id)
    try:
        matches = comm.get_round(round_id)
        utils.log("Found %s matches" % len(matches))

        ok = True
        for m in matches:

            listitem = xbmcgui.ListItem(label=m['name'])
            url = "%s?round_id=%s&match_id=%s" % (sys.argv[0],
                                                  m['round_id'],
                                                  m['id'])

            # Add the item to the list
            ok = xbmcplugin.addDirectoryItem(
                        handle=int(sys.argv[1]),
                        url=url,
                        listitem=listitem,
                        isFolder=True,
                        totalItems=len(matches))

        # send notification we're finished, successfully or unsuccessfully
        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
    except:
        utils.handle_error('Unable to fetch match list')
예제 #10
0
def cl_news_util(args, cache):
    if not cache:
        htmlfile = utils.get_html_file('http://www.reuters.com/')
        parser = REUTERSHTMLParser()
        parser.feed(htmlfile)
        articlelist = parser.articlelist
    else:
        articlelist = cache

    if len(args) > 1:
        if args[1] == '--headlines' or args[1] == '-h':
            utils.reuters_headlines(articlelist)
            return articlelist

        if len(args) > 2:

            if args[1] == '--open' or args[1] == '-o':
                index = args[2]
                article = get_reuters_article(articlelist, index)
                utils.go_to_page(article['url'])
                return articlelist

            if args[1] == '--read' or args[1] == '-r':
                index = args[2]
                article = get_reuters_article(articlelist, index)
                htmlfile = utils.get_html_file(article['url'])
                abbrevurl = article['url'][28:]
                print '\n' + article['title'] + ' -- ' + abbrevurl
                print '==================\n'
                parser = REUTERSARTICLEParser()
                parser.feed(htmlfile)
                return articlelist

    utils.handle_error('reuters_error')
예제 #11
0
파일: app.py 프로젝트: slapglif/Binance-Bot
def check_sell():
    print("Looking for Sell Opportunities...")
    max_price = 0
    while True:
        try:
            open_orders = db.query(Trades).all()
            for open_order in open_orders:
                if open_order.price:
                    price_action = trade_api.get_price_action(open_order.pair)
                    current_price = round(float(price_action.get("price")), 8)
                    if current_price > max_price:
                        max_price = float(current_price)
                    if current_price >= float(open_order.price) * (1 + trade_api.expected_change_sell / 100):
                        try:
                            print(f"sell on {open_order.pair} at {open_order.price}, current price is {current_price}")
                            order = trade_api.client.order_limit_sell(
                                symbol=open_order.pair,
                                recvWindow=10000,
                                quantity='{0:.2f}'.format(float(open_order.quantity)),
                                price='{0:.8f}'.format(float(current_price)))
                            open_order.orderId = str(order.get("orderId"))
                            db.commit()
                            check_sell_status(open_order.pair)
                        except Exception as e:
                            handle_error(e)
        except Exception as e:
            handle_error(e)
        time.sleep(trade_api.wait_time)
예제 #12
0
def cl_news_util(arguments, cache):
    if not cache:
        htmlfile = utils.get_html_file('http://news.ycombinator.com')
        storylinks = re.findall(r'href="(.+)" class="storylink">(.+)</a><span',
                                htmlfile)
    else:
        storylinks = cache

    if len(arguments) > 1:
        if arguments[1] == '--headlines' or arguments[1] == '-h':
            utils.hn_headlines(storylinks)
            return storylinks

        if arguments[1] == '--open' or arguments[1] == '-o':
            if len(arguments) > 2:
                index = int(arguments[2])
                openpage(storylinks, index)
                return storylinks

        if arguments[1] == '--copy' or arguments[1] == '-cp':
            if len(arguments) > 2:
                utils.copy_file(arguments[2], htmlfile)
                return storylinks

    utils.handle_error('hn_error')
예제 #13
0
def cl_news_util(args, cache):
    if not cache:
        htmlfile = utils.get_html_file('http://bigstory.ap.org/')
        parser = APHTMLParser()
        parser.feed(htmlfile)
        articlelist = parser.articlelist
    else:
        articlelist = cache

    if len(args) > 1:
        if args[1] == '--headlines' or args[1] == '-h':
            utils.ap_headlines(articlelist)
            return articlelist

        if len(args) > 2:

            if args[1] == '--open' or args[1] == '-o':
                index = args[2]
                article = get_ap_article(articlelist, index)
                utils.go_to_page(article['url'])
                return articlelist

            if args[1] == '--read' or args[1] == '-r':
                index = args[2]
                article = get_ap_article(articlelist, index)
                htmlfile = utils.get_html_file(article['url'])
                content = re.search(
                    r'<meta name="description" content="(.+?)" />', htmlfile)
                print_article_header(article['title'], content.group(1))
                return articlelist

    utils.handle_error('ap_error')
예제 #14
0
def make_series_list():
    utils.log("Showing series list")
    try:
        series_list = comm.get_index()
        series_list.sort()

        ok = True
        for s in series_list:
            url = "%s?series_id=%s" % (sys.argv[0], s.id)
            thumbnail = s.get_thumbnail()

            # Thumbnail that doesn't exist breaks XBMC 12
            listitem = xbmcgui.ListItem(s.get_title())
            if thumbnail:
                listitem = xbmcgui.ListItem(s.get_title(), iconImage=thumbnail, thumbnailImage=thumbnail)

            listitem.setInfo("video", {"plot": s.get_description()})

            # add the item to the media list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True)

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content="tvshows")
    except:
        utils.handle_error("Unable to fetch series listing")
예제 #15
0
def cl_news_util(args, cache):
    if not cache:
        htmlfile = utils.get_html_file('https://www.washingtonpost.com')
        htmlfile = htmlfile.decode('utf-8')
        parser = WPHTMLParser()
        parser.feed(htmlfile)
        articlelist = parser.articlelist
    else:
        articlelist = cache

    if len(args) > 1:
        if args[1] == '--headlines' or args[1] == '-h':
            utils.wp_headlines(articlelist)
            return articlelist

        if len(args) > 2:

            if args[1] == '--open' or args[1] == '-o':
                index = args[2]
                article = articlelist[index]
                utils.go_to_page(article['url'])
                return articlelist

            if args[1] == '--read' or args[1] == '-r':
                index = int(args[2]) - 1
                article = articlelist[index]
                htmlfile = utils.get_html_file(article['url'])
                htmlfile = htmlfile.decode('utf-8')
                print '\n' + article['title']
                print '==================\n'
                parser = WPARTICLEParser()
                parser.feed(htmlfile)
                return articlelist

    utils.handle_error('wp_error')
예제 #16
0
파일: cnn.py 프로젝트: mickberber/pystuff
def cl_news_util(args, cache):
    if not cache:
        article_list = get_article_list()
    else:
        article_list = cache

    if len(args) > 1:
        if args[1] == '--headlines' or args[1] == '-h':
            utils.cnn_headlines(article_list)
            return article_list

        if len(args) > 2:
            index = int(args[2]) - 1
            cnn_url = 'http://www.cnn.com/' + article_list[index]['uri']

            if args[1] == '--open' or args[1] == '-o':
                utils.go_to_page(cnn_url)
                return article_list

            if args[1] == '--read' or args[1] == '-r':
                os.system('clear')
                print article_list[index]['headline']
                cnn_article_abbreviator.main(cnn_url)
                return article_list

    utils.handle_error('cnn_error')
예제 #17
0
def make_programs_list(url):
    try:
        params = utils.get_url(url)
        programs = comm.get_series_from_feed(params['series'],
                                             category=params['category'])

        ok = True
        for p in programs:
            listitem = xbmcgui.ListItem(label=p.get_list_title(),
                                        iconImage=p.get_thumbnail(),
                                        thumbnailImage=p.get_thumbnail())
            listitem.setInfo('video', p.get_xbmc_list_item())
            listitem.setProperty('IsPlayable', 'true')

            if hasattr(listitem, 'addStreamInfo'):
                listitem.addStreamInfo('audio', p.get_xbmc_audio_stream_info())
                listitem.addStreamInfo('video', p.get_xbmc_video_stream_info())

            # Build the URL for the program, including the list_info
            url = "%s?play=true&%s" % (sys.argv[0], p.make_xbmc_url())

            # Add the program item to the list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                             url=url,
                                             listitem=listitem,
                                             isFolder=False,
                                             totalItems=len(programs))

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except:
        utils.handle_error('Unable to fetch program list')
예제 #18
0
def make_series_list(url):
    params = utils.get_url(url)

    try:
        category = params["category"]
        series_list = comm.get_programme_from_feed(category)
        series_list.sort()

        ok = True
        for s in series_list:
            url = "%s?%s" % (sys.argv[0],
                             utils.make_url({
                                 'series': s.title,
                                 'category': category
                             }))

            thumbnail = s.get_thumbnail()
            listitem = xbmcgui.ListItem(s.get_list_title(),
                                        iconImage=thumbnail,
                                        thumbnailImage=thumbnail)
            listitem.setInfo('video', {'plot': s.get_description()})

            # add the item to the media list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                             url=url,
                                             listitem=listitem,
                                             isFolder=True)

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='tvshows')
    except:
        utils.handle_error(
            'Unable to fetch program list. Please try again later.')
예제 #19
0
def play_video(params):
    """
    Play a video by the provided path.
    :param path: str
    """
    try:
        stream_method = addon.getSetting('streammethod')

        live = params['live'] == 'true'
        video_id = params['video_id']
        if stream_method == 'HLS (Lower quality)' or live:

            playlist = ooyalahelper.get_m3u8_playlist(video_id, live)
            play_item = xbmcgui.ListItem(path=playlist)
            xbmcplugin.setResolvedUrl(_handle, True, listitem=play_item)

        elif stream_method == 'HDS (Higher quality, no seeking)':
            ooyalahelper.get_nrl_user_token()
            qual = addon.getSetting('HDSQUALITY')
            smil = ooyalahelper.fetch_nrl_smil(video_id)
            url = ooyalahelper.get_nrl_hds_url(smil)
            player = f4mProxyHelper()
            urltoplay, item = player.playF4mLink(
                url,
                '',
                setResolved=True,
                maxbitrate=config.HDS_REPLAY_QUALITY[qual])
            play_item = xbmcgui.ListItem(path=urltoplay)
            xbmcplugin.setResolvedUrl(_handle, True, play_item)
    except Exception as e:
        utils.handle_error('', e)
예제 #20
0
def make_list():
    try:
        for t in config.TEAMS:
            # Add our resources/lib to the python path
            try:
                current_dir = os.path.dirname(os.path.abspath(__file__))
            except:
                current_dir = os.getcwd()

            thumbnail = os.path.join(current_dir, "..", "..", "resources",
                                     "img", t['thumb'])
            listitem = xbmcgui.ListItem(label=t['name'],
                                        iconImage=thumbnail,
                                        thumbnailImage=thumbnail)
            url = "%s?channel=%s" % (sys.argv[0], t['channel'])

            # Add the item to the list
            ok = xbmcplugin.addDirectoryItem(
                        handle=int(sys.argv[1]),
                        url=url,
                        listitem=listitem,
                        isFolder=True,
                        totalItems=len(config.TEAMS))

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except:
        utils.handle_error('Unable to fetch video list')
예제 #21
0
def list_shows(params):
    try:
        shows = comm.get_shows(params)
        genre = ('All'
                 if params['category'] == 'All shows' else params['category'])
        listing = []
        for s in shows:
            if genre == 'All':
                pass
            else:
                if not genre == s.genre:
                    continue
            li = xbmcgui.ListItem(s.title,
                                  iconImage=s.thumb,
                                  thumbnailImage=s.thumb)
            li.setArt({'fanart': s.get_fanart(), 'banner': s.get_banner()})
            url = '{0}?action=listshows&category={1}{2}'.format(
                _url, params['category'], s.make_kodi_url())
            is_folder = True
            listing.append((url, li, is_folder))
        xbmcplugin.addSortMethod(_handle,
                                 xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
        xbmcplugin.addDirectoryItems(_handle, listing, len(listing))
        xbmcplugin.endOfDirectory(_handle)
    except Exception as e:
        utils.handle_error('Unable to list shows', exc=e)
예제 #22
0
def compare_models(code, data, init_params, model, transformed_data, n_runs=2, model_cache=None):

    copy_data = copy.deepcopy(data)
    tensorize_data(data)
    if transformed_data is not None:
        try:
            transformed_data(data)
        except (KeyError, AssertionError) as e:
            return handle_error("run_transformed_data", e)


    lp_vals = []
    #for data in datas:
    for i in range(n_runs):
        reset_initialization_cache()
        params ={}
        try:
            init_params(data, params)
        except (KeyError, AssertionError) as e:
            return handle_error("run_init_params", e)

        init_values = {k: params[k].data.cpu().numpy().tolist() for k in params}
        init_values = {k: (init_values[k][0]) if len(init_values[k])==1 else np.array(init_values[k]) for k in init_values}

        #print(init_values)
        try:
            site_values, s_log_probs = run_stan(copy_data, code, init_values, n_samples=1, model_cache=model_cache)
        except (ValueError, RuntimeError) as e:
            return handle_error("run_stan", e)


        try:
            p_log_probs, n_log_probs = run_pyro(site_values, data, model, transformed_data, n_samples=1, params=params)
        except (RuntimeError, NotImplementedError, AssertionError, RuntimeError, NameError) as e:
            return handle_error("run_pyro", e)


        p_avg = float(np.mean(p_log_probs))/n_log_probs
        s_avg = float(np.mean(s_log_probs))/n_log_probs
        lp_vals.append((p_avg, s_avg))

    assert len(lp_vals) >= 2
    n_lp = len(lp_vals)
    for i in range(n_lp):
        for j in range(i):
            (p1,s1) = lp_vals[i]
            (p2,s2) = lp_vals[j]
            try:
                perc_error = 100*abs((p1-p2) - (s1-s2))/ abs((p1+p2) + (s1+s2))
                check_abs = abs((p1-p2) - (s1-s2)) <= 1e-2
                check_perc = perc_error < 1.
                assert check_perc, "Log-probs check failed -- " \
                                  "Log probs don't match with EPS=1e-2! lp_vals = %s"  % (lp_vals) + \
                                  " p1-p2=%0.5f s1-s2=%0.5f abs((p1-p2) - (s1-s2))=%0.5f" %\
                                  (p1-p2, s1-s2, abs((p1-p2) - (s1-s2)))
            except AssertionError as e:
                return handle_error("log_prob_comparison", e)
    return 0, "success" #""Log probs match"
예제 #23
0
def play(url):

    try:
        p = classes.Program()
        p.parse_xbmc_url(url)

        listitem = xbmcgui.ListItem(label=p.get_list_title(),
                                    iconImage=p.thumbnail,
                                    thumbnailImage=p.thumbnail,
                                    path="%s|X-Forwarded-For=101.188.88.88" %
                                    p.get_url())

        listitem.setInfo('video', p.get_xbmc_list_item())

        #add subtitles if available
        addon = xbmcaddon.Addon(config.ADDON_ID)
        subtitles = None
        if addon.getSetting('subtitles_enabled') == 'true':
            profile = xbmcaddon.Addon().getAddonInfo('profile')
            path = xbmc.translatePath(profile).decode('utf-8')
            if not os.path.isdir(path):
                os.makedirs(path)
            subfile = xbmc.translatePath(
                os.path.join(path, 'subtitles.eng.srt'))
            if os.path.isfile(subfile):
                os.remove(subfile)
            suburl = (config.subtitle_url +
                      p.url[p.url.rfind('/') + 1:p.url.rfind('_')] + '.xml')
            try:
                data = urllib2.urlopen(suburl).read()
                f = open(subfile, 'w')
                f.write(parse.convert_to_srt(data))
                f.close()
                if hasattr(listitem, 'setSubtitles'):
                    # This function only supported from Kodi v14+
                    listitem.setSubtitles([subfile])
                else:
                    subtitles = True
            except:
                utils.log('Subtitles not available for this program')

        if hasattr(listitem, 'addStreamInfo'):
            listitem.addStreamInfo('audio', p.get_xbmc_audio_stream_info())
            listitem.addStreamInfo('video', p.get_xbmc_video_stream_info())

        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem=listitem)

        # Enable subtitles for XBMC v13
        if addon.getSetting('subtitles_enabled') == "true":
            if subtitles == True:
                if not hasattr(listitem, 'setSubtitles'):
                    player = xbmc.Player()
                    while not player.isPlaying():
                        xbmc.sleep(100)  # wait until video is being played
                        player.setSubtitles(subfile)

    except:
        utils.handle_error("Unable to play video")
예제 #24
0
def play(url):

    try:
        p = classes.Program()
        p.parse_xbmc_url(url)

        listitem=xbmcgui.ListItem(label=p.get_list_title(),
                                  iconImage=p.thumbnail,
                                  thumbnailImage=p.thumbnail,
                                  path="%s|X-Forwarded-For=101.188.88.88" % p.get_url())

        listitem.setInfo('video', p.get_xbmc_list_item())

        #add subtitles if available
        addon = xbmcaddon.Addon(config.ADDON_ID)
        subtitles = None
        if addon.getSetting('subtitles_enabled') == 'true':
            profile = xbmcaddon.Addon().getAddonInfo('profile')
            path = xbmc.translatePath(profile).decode('utf-8')
            if not os.path.isdir(path):
                os.makedirs(path)
            subfile = xbmc.translatePath(os.path.join(path, 'subtitles.eng.srt'))
            if os.path.isfile(subfile):
                os.remove(subfile)
            suburl = (config.subtitle_url+p.url[p.url.rfind('/')
                        +1:p.url.rfind('_')]+'.xml')
            try:
                data = urllib2.urlopen(suburl).read()
                f = open(subfile, 'w')
                f.write(parse.convert_to_srt(data))
                f.close()
                if hasattr(listitem, 'setSubtitles'):
                    # This function only supported from Kodi v14+
                    listitem.setSubtitles([subfile])
                else:
                    subtitles = True
            except:
                utils.log('Subtitles not available for this program')

        if hasattr(listitem, 'addStreamInfo'):
            listitem.addStreamInfo('audio', p.get_xbmc_audio_stream_info())
            listitem.addStreamInfo('video', p.get_xbmc_video_stream_info())

        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem=listitem)

        # Enable subtitles for XBMC v13
        if addon.getSetting('subtitles_enabled') == "true":
            if subtitles == True:
                if not hasattr(listitem, 'setSubtitles'):
                    player = xbmc.Player()
                    while not player.isPlaying():
                        xbmc.sleep(100) # wait until video is being played
                        player.setSubtitles(subfile)

    except:
        utils.handle_error("Unable to play video")
예제 #25
0
def make_menu(objects, sort=False):
    try:
        listing = []

        for item in objects:

            li = xbmcgui.ListItem(label=item.get('title'),
                                  iconImage=item.get('icon'),
                                  thumbnailImage=item.get('thumb'))
            url = '{0}?{1}'.format(_url, item.to_kodi_url())

            if item.playable:
                li.setProperty('IsPlayable', 'true')

            if item.has('description'):
                li.setInfo('video', {
                    'plot': item.description,
                    'plotoutline': item.description
                })

            if item.has('duration'):
                li.setInfo('video', {'duration': item.duration})

            if item.has('date'):
                li.setInfo('video', {'date': item.date, 'aired': item.date})

            if item.has('mpaa'):
                li.setInfo('video', {'mpaa': item.mpaa})

            if item.has('season'):
                li.setInfo('video', {'season': item.season})

            if item.has('episode'):
                li.setInfo('video', {'episode': item.episode})

            if item.has('genre'):
                li.setInfo('video', {'genre': item.genre})

            if item.has('fanart'):
                li.setArt({'fanart': item.fanart})

            if item.has('banner'):
                li.setArt({'banner': item.banner})

            listing.append((url, li, not item.playable))

        if sort:
            xbmcplugin.addSortMethod(_handle,
                                     xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)

        xbmcplugin.addDirectoryItems(_handle, listing, len(listing))
        xbmcplugin.endOfDirectory(_handle)

    except Exception:
        utils.handle_error("Unable to make menu")
예제 #26
0
def play_video(params):
    """
    Determine content and pass url to Kodi for playback
    """
    try:
        with session.Session() as sess:
            url = params['hlsurl'] + '|User-Agent=%s' % config.USER_AGENT
        play_item = xbmcgui.ListItem(path=url)
        xbmcplugin.setResolvedUrl(_handle, True, play_item)
    except Exception:
        utils.handle_error('Unable to play video')
def make_category_list(url):
    utils.log("Making category list")
    try:
        params = utils.get_url(url)
        categories = comm.get_category(params['category'])

        ok = True
        if 'children' in categories:
            for c in categories.get('children', []):
                if 'children' in c:
                    url = "%s?%s" % (sys.argv[0], utils.make_url({
                                     'category': params['category'],
                                     'section': c['name']}))
                elif 'url' in c:
                    url = "%s?%s" % (sys.argv[0], utils.make_url({
                                     'entries_url': c['url']}))
                else:
                    #utils.log("Skip category due to no entries or url: '%s'" % c['name'])
                    continue

                # If no thumbnail, make it an empty string as None makes
                # XBMC v12 with a TypeError must be unicode or str
                thumbnail = c.get('thumbnail', '')
                listitem = xbmcgui.ListItem(label=c['name'],
                                            thumbnailImage=thumbnail)
                ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url,
                                                 listitem=listitem, isFolder=True)
        else:
            # 'Coming soon' has no children
            jsonurl = categories['url']
            programs = comm.get_entries(jsonurl)
            for p in sorted(programs):
                thumbnail = p.get_thumbnail()
                listitem = xbmcgui.ListItem(label=p.get_list_title(),
                                            iconImage=thumbnail,
                                            thumbnailImage=thumbnail)
                listitem.setInfo('video', p.get_xbmc_list_item())

                if hasattr(listitem, 'addStreamInfo'):
                    listitem.addStreamInfo('audio', p.get_xbmc_audio_stream_info())
                    listitem.addStreamInfo('video', p.get_xbmc_video_stream_info())

                # Build the URL for the program, including the list_info
                url = "%s?play=true&%s" % (sys.argv[0], p.make_xbmc_url())

                # Add the program item to the list
                ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url,
                                                 listitem=listitem, isFolder=False,
                                                 totalItems=len(programs))

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except:
        utils.handle_error()
예제 #28
0
def play(url):
    try:
        params = utils.get_url(url)
        p = comm.get_program(params["program_id"])

        listitem = xbmcgui.ListItem(
            label=p.get_title(), iconImage=p.thumbnail, thumbnailImage=p.thumbnail, path=p.get_url()
        )
        listitem.setInfo("video", p.get_xbmc_list_item())

        if hasattr(listitem, "addStreamInfo"):
            listitem.addStreamInfo("audio", p.get_xbmc_audio_stream_info())
            listitem.addStreamInfo("video", p.get_xbmc_video_stream_info())

        player = xbmc.Player()

        # Pull subtitles if available
        if addon.getSetting("subtitles_enabled") == "true":
            if p.subtitle:
                utils.log("Enabling subtitles: %s" % p.subtitle)
                profile = addon.getAddonInfo("profile")
                subfilename = xbmc.translatePath(os.path.join(profile, "subtitle.srt"))
                profiledir = xbmc.translatePath(os.path.join(profile))
                if not os.path.isdir(profiledir):
                    os.makedirs(profiledir)

                dfxp_data = urllib2.urlopen(p.subtitle).read().decode("utf-8")
                if dfxp_data:
                    f = open(subfilename, "w")
                    dfxp_subtitle = DFXPReader().read(dfxp_data)
                    srt_subtitle = SRTWriter().write(dfxp_subtitle)
                    srt_unicode = srt_subtitle.encode("utf-8")
                    f.write(srt_unicode)
                    f.close()

                if hasattr(listitem, "setSubtitles"):
                    # This function only supported from Kodi v14+
                    listitem.setSubtitles([subfilename])

        # Play video
        utils.log("Attempting to play: %s" % p.get_title())
        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem=listitem)

        # Enable subtitles for XBMC v13
        if addon.getSetting("subtitles_enabled") == "true":
            if p.subtitle:
                if not hasattr(listitem, "setSubtitles"):
                    while not player.isPlaying():
                        xbmc.sleep(100)  # wait until video is being played
                        player.setSubtitles(subfilename)

    except:
        utils.handle_error("Unable to play video")
예제 #29
0
def play_video(params):
    """
    Determine content and pass url to Kodi for playback
    """
    try:
        with custom_session.Session() as session:
            url = config.BRIGHTCOVE_URL.format(params['id'])
            data = session.get(url).text.splitlines()
        streamurl = utils.parse_m3u8(data)
        play_item = xbmcgui.ListItem(path=streamurl)
        xbmcplugin.setResolvedUrl(_handle, True, play_item)
    except Exception as e:
        utils.handle_error('Unable to play video', exc=e)
예제 #30
0
    def GET(self,page_name,component):
        access = utils.page_access(page_name)
        if access is not None:  return access

        try:
            content = utils.fetch_file(page_name)
            ## We have to textile some fields
            try:
                obj = json.loads(content)
                return utils.callback(json.dumps(obj["components"][component]))
            except:
                utils.handle_error("failed to read file")
        except IOError:
            utils.handle_error("file not found")
예제 #31
0
파일: app.py 프로젝트: slapglif/Binance-Bot
def check_pump():
    """
    Primary market watcher. Creates a threaded loop which uses the
    configured variables to calculate a pump vector and execute a buy
    when the conditions are met. Default configuration is 3% increase in price.
    """
    print("Looking for Buy Opportunities...")
    threading.Thread(target=check_sell).start()
    while True:
        try:
            open_orders = db.query(Trades).all()
            for symbol in trade_api.symbols:
                prices = dict()
                price_action = trade_api.get_price_action(symbol)
                prices[symbol] = '{0:.8f}'.format(round(float(price_action.get('lastPrice')), 8))
                pct_change = float(price_action.get('priceChangePercent'))
                calculation = round(float(prices[symbol]), 8) < float(prices[symbol])*(1 + trade_api.expected_change_buy/100)
                if calculation and pct_change > trade_api.expected_change_buy:
                    current_symbol = symbol
                    if current_symbol not in open_orders:
                        min_price, min_quantity = trade_api.calculate_min(current_symbol)
                        temp_price = float(prices[symbol]) * trade_api.final_buy_price_change
                        final_buy_price = temp_price - (temp_price % float(min_price))
                        temp_quantity = trade_api.buy_quantity_btc / float(final_buy_price)
                        quantity = round((temp_quantity - (temp_quantity % float(min_quantity))), 8)
                        try:
                            trade = Trades.find(symbol)
                            if trade is None:
                                # Place order for buy
                                order = trade_api.client.order_limit_buy(
                                    symbol=current_symbol,
                                    recvWindow=1000,
                                    quantity='{0:.3f}'.format(float(quantity)),
                                    price='{0:.8f}'.format(float(final_buy_price)))
                                print(
                                    f" buy {symbol} at {(float(prices[symbol]) * trade_api.final_buy_price_change)}"
                                    f"from {prices[symbol]} Due to change % {pct_change}"
                                )
                                trade = Trades.get_or_create(symbol)
                                trade.price = str('{0:.8f}'.format(float(prices[symbol])))
                                trade.orderId = order['orderId']
                                trade.quantity = str('{0:.3f}'.format(float(quantity)))
                                db.commit()
                                check_buy_status(symbol)
                        except Exception as e:
                            handle_error(e)
                            pass
                time.sleep(trade_api.wait_time)
        except Exception as e:
            handle_error(e)
예제 #32
0
    def GET(self,page_name,id):
        access = utils.page_access(page_name,utils.PERM_WRITE)
        if access is not None:  return access

        try:
            content = utils.fetch_file(page_name)
            try:
                obj = json.loads(content) 
                if obj["components"].has_key(id):
                    type = obj["components"][id]["type"]
                    del obj["components"][id]

                    ## Remove from order
                    current_order = obj['order'].split(',')
                    x = 0
                    for i in current_order:
                        if int(i) == int(id):
                            del current_order[x]
                        x = x + 1

                    current_order = ",".join(current_order)
                    obj['order'] = current_order

                    try:
                        utils.save_file(page_name,json.dumps(obj))

                        return utils.callback('{"id":"' + id + '", "type":"' + type +'"}')
                    except IOError:
                        utils.handle_error("failed to save file")
                else:
                    utils.handle_error("key not found")
            except:
                utils.handle_error("failed to read file")
        except IOError:
            utils.handle_error("file not found")
예제 #33
0
def make_category_list(url):
    utils.log("Making category list")
    try:
        params = utils.get_url(url)
        categories = comm.get_category(params["category"])

        ok = True
        if "children" in categories:
            for c in categories.get("children", []):
                if "children" in c:
                    url = "%s?%s" % (
                        sys.argv[0],
                        utils.make_url({"category": params["category"], "section": c["name"]}),
                    )
                elif "url" in c:
                    url = "%s?%s" % (sys.argv[0], utils.make_url({"entries_url": c["url"]}))
                else:
                    # utils.log("Skip category due to no entries or url: '%s'" % c['name'])
                    continue

                thumbnail = c.get("thumbnail", None)
                listitem = xbmcgui.ListItem(label=c["name"], iconImage=thumbnail, thumbnailImage=thumbnail)
                ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True)
        else:
            # 'Coming soon' has no children
            jsonurl = categories["url"]
            programs = comm.get_entries(jsonurl)
            for p in sorted(programs):
                thumbnail = p.get_thumbnail()
                listitem = xbmcgui.ListItem(label=p.get_list_title(), iconImage=thumbnail, thumbnailImage=thumbnail)
                listitem.setInfo("video", p.get_xbmc_list_item())

                if hasattr(listitem, "addStreamInfo"):
                    listitem.addStreamInfo("audio", p.get_xbmc_audio_stream_info())
                    listitem.addStreamInfo("video", p.get_xbmc_video_stream_info())

                # Build the URL for the program, including the list_info
                url = "%s?play=true&%s" % (sys.argv[0], p.make_xbmc_url())

                # Add the program item to the list
                ok = xbmcplugin.addDirectoryItem(
                    handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False, totalItems=len(programs)
                )

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content="episodes")
    except:
        utils.handle_error()
예제 #34
0
    def read_checkpoint_file(self):
        """Read the 'checkpoint.json' file and update the class variables accordingly."""
        checkpoint = None
        if os.path.isfile(self.path_checkpoint_file):
            print_positive("Found checkpoint file: {}".format(
                self.path_checkpoint_file))
            print_info("Verifying integrity of checkpoint file...")
            try:
                with open(self.path_checkpoint_file, "r") as fp:
                    try:
                        checkpoint = json.load(fp)
                    except ValueError as e:
                        handle_error(
                            "Failed to open checkpoint file '{0}'. ".format(
                                self.path_checkpoint_file) +
                            "It does not appear to be a valid JSON file.", e)
                        checkpoint = None
            except IOError as e:
                handle_error(
                    "Unable to open checkpoint file '{}' for reading.".format(
                        self.path_checkpoint_file), e)
        ### Failed to find or open checkpoint file. Set some values to 0 and exit
        if checkpoint != None:
            ### Succesfully loaded check point file, gather the data!
            print_positive(
                "Successfully loaded checkpoint! Reading its data...")
            self.epochs_completed = checkpoint['epochs_completed']
            if checkpoint['model'] != settings.MODEL:
                print_warning(
                    "Inconsistency detected: the checkpoint model '{0}' does not match command line argument of '{1}'."
                    .format(checkpoint['model'], settings.MODEL))
                print_info("Discarding checkpoint and starting from scratch.")
                return None
            if checkpoint['exp_name'] != settings.EXP_NAME:
                print_warning(
                    "Inconsistency detected: the checkpoint experiment name '{0}' does not match command line argument of '{1}'."
                    .format(checkpoint['exp_name'], settings.EXP_NAME))
                print_info("Discarding checkpoint and starting from scratch.")
                return None

            self.wall_time = checkpoint['wall_time']
            self.process_time = checkpoint['process_time']
        else:
            self.epochs_completed = 0
            self.wall_time = 0
            self.process_time = 0

        return checkpoint
예제 #35
0
def play_video(params):
    """
    Play a video by the provided path.
    :param path: str
    """
    if 'dummy' in params:
        if params['dummy'] == 'True':
            return
    try:
        live = params['live'] == 'true'
        video_id = params['video_id']
        playlist = ooyalahelper.get_m3u8_playlist(video_id, live)
        play_item = xbmcgui.ListItem(path=playlist)
        xbmcplugin.setResolvedUrl(_handle, True, listitem=play_item)

    except Exception as e:
        utils.handle_error('', e)
def clock_in(config):
    try:
        flag = False

        while True:
            hour = utils.get_local_hour()

            if not flag and hour > 9:
                content = 'have not clock in yet!'
                utils.print_logs(content)

                if config['send_mail']:
                    utils.send_mail(config['mail_config'], 'Oh No', content)
                
            if flag and hour != 1:
                utils.wait_until_next_hour()
                continue

            flag = False

            try:
                headers = utils.sign_in(config['baidu_ocr'], config['sign_in_config'])

            except Exception as e:
                utils.handle_error(e)

            else:
                try:
                    clock_in_config = config['clock_in_config'][config['type_']]
                    utils.clock_in(clock_in_config, headers)

                except Exception as e:
                    utils.handle_error(e)
                    
                else:
                    flag = True
                    
                    content = 'Time to sleep!'

                    if config['send_mail']:
                        utils.send_mail(config['mail_config'], 'Clock In', content)
                        
                    utils.wait_until_next_hour()

    except KeyboardInterrupt:
        utils.print_logs('Stopped by Keyboard. Bye!')
예제 #37
0
def play(url):
    addon = xbmcaddon.Addon(config.ADDON_ID)

    try:
        p = classes.Program()
        p.parse_xbmc_url(url)

        listitem=xbmcgui.ListItem(label=p.get_list_title(), iconImage=p.thumbnail, thumbnailImage=p.thumbnail)
        listitem.setInfo('video', p.get_xbmc_list_item())

        if hasattr(listitem, 'addStreamInfo'):
            listitem.addStreamInfo('audio', p.get_xbmc_audio_stream_info())
            listitem.addStreamInfo('video', p.get_xbmc_video_stream_info())
    
        xbmc.Player().play(p.get_url(), listitem)
    except:
        utils.handle_error("Unable to play video")
예제 #38
0
def play(url):
    try:
        params = utils.get_url(url)
        p = comm.get_program(params["program_id"])

        listitem = xbmcgui.ListItem(label=p.get_title(),
                                    iconImage=p.thumbnail,
                                    thumbnailImage=p.thumbnail)
        listitem.setInfo('video', p.get_xbmc_list_item())

        if hasattr(listitem, 'addStreamInfo'):
            listitem.addStreamInfo('audio', p.get_xbmc_audio_stream_info())
            listitem.addStreamInfo('video', p.get_xbmc_video_stream_info())

        utils.log("Attempting to play: %s" % p.get_title())
        xbmc.Player().play(p.get_url(), listitem)
    except:
        utils.handle_error("Unable to play video")
예제 #39
0
파일: app.py 프로젝트: slapglif/Binance-Bot
def check_buy_status(pair):
    try:
        print("Checking status...")
        open_orders = db.query(Trades).filter_by(pair=pair)
        for open_order in open_orders:
            if open_order.pair and open_order.orderId:
                    check = trade_api.client.get_order(
                        symbol=open_order.pair,
                        recvWindow=10000,
                        orderId=open_order.orderId)
                    # Check if order has been filled
                    if check.get('status') == 'FILLED':
                        print(f"Order {open_order.pair} {check.get('status')}")
                        pass
                    else:
                        print(f"{open_order.pair} Not FILLED yet...")
    except Exception as e:
        handle_error(e)
예제 #40
0
def make_index_list():

    try:
        index = comm.get_index()
        ok = True
        for i in index:
            if 'url' in i:
                url = "%s?%s" % (sys.argv[0], utils.make_url({
                                 'category': i['name']}))
                listitem = xbmcgui.ListItem(i['name'])
                # Add the program item to the list
                ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                                 url=url, listitem=listitem,
                                                 isFolder=True)

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except:
        utils.handle_error()
예제 #41
0
def list_seasons(params):
    try:
        seasons = comm.get_seasons(params)
        listing = []
        for s in seasons:
            li = xbmcgui.ListItem(s.name,
                                  iconImage=s.logo,
                                  thumbnailImage=s.logo)
            url = '{0}?action=listseasons&category={1}{2}'.format(
                _url, params['category'], s.make_kodi_url())
            listing.append((url, li, True))

        xbmcplugin.addSortMethod(_handle,
                                 xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
        xbmcplugin.addDirectoryItems(_handle, listing, len(listing))
        xbmcplugin.endOfDirectory(_handle)

    except Exception:
        utils.handle_error('Unable to list seasons')
예제 #42
0
def play(url):
    addon = xbmcaddon.Addon(config.ADDON_ID)

    try:
        p = classes.Program()
        p.parse_xbmc_url(url)

        listitem = xbmcgui.ListItem(label=p.get_list_title(),
                                    iconImage=p.thumbnail,
                                    thumbnailImage=p.thumbnail)
        listitem.setInfo('video', p.get_xbmc_list_item())

        if hasattr(listitem, 'addStreamInfo'):
            listitem.addStreamInfo('audio', p.get_xbmc_audio_stream_info())
            listitem.addStreamInfo('video', p.get_xbmc_video_stream_info())

        xbmc.Player().play(p.get_url(), listitem)
    except:
        utils.handle_error("Unable to play video")
예제 #43
0
def make_list():
    try:
        # Disabled until team channels has been moved to new API
        # items = []
        # __addon__ = xbmcaddon.Addon()
        # favourite_team =  __addon__.getSetting('TEAM')
        # if favourite_team > 0:
        #     for team in config.TEAMS:
        #         if favourite_team == team['id']:
        #             items.append({'name': team['name'],
        #                           'channel': team['channel']})
        #
        # enumerate through the list of categories and add the item
        # to the media list
        # for i in items:
        #     url = "%s?channel=%s" % (sys.argv[0], i['channel'])
        #     listitem = xbmcgui.ListItem(i['name'])
        #
        #     # add the item to the media list
        #     ok = xbmcplugin.addDirectoryItem(
        #                 handle=int(sys.argv[1]),
        #                 url=url,
        #                 listitem=listitem,
        #                 isFolder=True,
        #             )

        for category in config.CATEGORIES:
            url = "%s?category=%s" % (sys.argv[0], category)
            listitem = xbmcgui.ListItem(category)

            # add the item to the media list
            ok = xbmcplugin.addDirectoryItem(
                        handle=int(sys.argv[1]),
                        url=url,
                        listitem=listitem,
                        isFolder=True,
                        totalItems=len(config.CATEGORIES)
                    )

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
    except:
        utils.handle_error('Unable build video category list')
예제 #44
0
def list_featured():
    try:
        episodes = comm.get_featured()
        listing = []
        for e in episodes:
            li = xbmcgui.ListItem(e.title,
                                  iconImage=e.thumb,
                                  thumbnailImage=e.thumb)
            urlString = '{0}?action=listfeatured&show={1}&id={2}'
            url = urlString.format(_url, e.title, e.id)
            is_folder = False
            li.setInfo('video', {'plot': e.desc, 'plotoutline': e.desc})
            li.setProperty('IsPlayable', 'true')
            listing.append((url, li, is_folder))
        xbmcplugin.addSortMethod(_handle,
                                 xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
        xbmcplugin.addDirectoryItems(_handle, listing, len(listing))
        xbmcplugin.endOfDirectory(_handle)
    except:
        utils.handle_error('Unable to list featured', exc=e)
예제 #45
0
def make_series_list():
    try:
        series_list = comm.get_index()
        series_list.sort()

        ok = True
        for s in series_list:
            url = "%s?series_id=%s" % (sys.argv[0], s.id)
            thumbnail = s.get_thumbnail()

            listitem = xbmcgui.ListItem(s.get_title(), iconImage=thumbnail, thumbnailImage=thumbnail)
            listitem.setInfo('video', { 'plot' : s.get_description() })
            
            # add the item to the media list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True)

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='tvshows')
    except:
        utils.handle_error("Unable to fetch series listing")
예제 #46
0
def make_category_list():

    try:
        iview_config = comm.get_config()
        categories = comm.get_categories(iview_config)
        categories = sorted(categories, key=lambda k: k['name'].lower())
        categories.insert(0, {'name':'All', 'keyword':'0-z'})

        ok = True
        for g in categories:
            url = "%s?category=%s" % (sys.argv[0], g['keyword'])
            listitem = xbmcgui.ListItem(g['name'])

            # Add the program item to the list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True)

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='episodes')
    except:
        utils.handle_error()
예제 #47
0
def cl_news_util(args, cache):
    if not cache:
        htmlfile = utils.get_html_file('https://www.nytimes.com')
        parser = NYTIMESHTMLParser()
        parser.feed(htmlfile)
        articlelist = parser.articlelist
    else:
        articlelist = cache

    if len(args) > 1:
        if args[1] == '--headlines' or args[1] == '-h':
            utils.nyt_headlines(articlelist)
            return articlelist

        if len(args) > 2:
            # NOT CURRENTLY USED
            # if args[1] == '--open' or args[1] == '-o':
            #     index = args[2]
            #     article = get_nyt_article(articlelist, index)
            #     utils.go_to_page(article['url'])
            #     return articlelist

            if args[1] == '--read' or args[1] == '-r':
                try:
                    index = int(args[2]) - 1
                    url = articlelist[index]['url']
                    article = articlelist[index]
                    # This url call is specific to NYT
                    htmlfile = urllib2.build_opener(
                        urllib2.HTTPCookieProcessor).open(url)
                    htmlfile = htmlfile.read()
                    parser = NYTIMESARTICLEParser()
                    print '=========nyt=========\n'
                    print article['title'] + '\n'
                    print '=====================\n'
                    parser.feed(htmlfile)
                    return articlelist
                except:
                    return

    utils.handle_error('nyt_error')
예제 #48
0
    def GET(self,page_name):
        
        access = utils.page_access(page_name)
        if access is not None:  return access

        content = utils.fetch_file(page_name)
        ## We have to textile some fields
        try:
            obj = json.loads(content)
            for component in obj["components"]:
                if obj["components"][component]["type"] == "note":
                    obj["components"][component]["description"] = textile.textile(obj["components"][component]["description"])
                elif obj["components"][component]["type"] == "list":
                    if obj["components"][component].has_key("completed"):
                        for c in obj["components"][component]["completed"]:
                            date = datetime.fromtimestamp(obj["components"][component]["completed"][c]["completed"])
                            obj["components"][component]["completed"][c]["completed"] = date.strftime("%b %d")

            return utils.callback(json.dumps(obj))
        except:
            utils.handle_error("failed to read file")
예제 #49
0
def make_rounds(season=2016):
    try:
        # ROUNDS_2016 variable from config
        rounds_config = getattr(config, 'ROUNDS_'+season)

        for r in rounds_config:
            listitem = xbmcgui.ListItem(label=r['name'])
            url = "%s?round_id=%s" % (sys.argv[0], r['id'])

            # Add the item to the list
            ok = xbmcplugin.addDirectoryItem(
                        handle=int(sys.argv[1]),
                        url=url,
                        listitem=listitem,
                        isFolder=True,
                        totalItems=len(rounds_config))

        # send notification we're finished, successfully or unsuccessfully
        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
    except:
        utils.handle_error('Unable to fetch round list')
예제 #50
0
    def GET(self,page_name,id):

        access = utils.page_access(page_name,utils.PERM_WRITE)
        if access is not None:  return access

        data = web.input(title="",description="")
        try:
            content = utils.fetch_file(page_name)
            try:
                obj = json.loads(content) 
                if obj["components"].has_key(id):
                    obj["components"][id]["title"] = data.title;
                    if ( obj["components"][id]["type"] == "note"):
                        obj["components"][id]["description"] = data.description
                    try:
                        utils.save_file(page_name,json.dumps(obj))
                        if obj["components"][id]["type"] == "note":
                            obj["components"][id]["description"] = textile.textile(obj["components"][id]["description"])
                        obj["components"][id]["id"] = id
                        return utils.callback(json.dumps(obj["components"][id]))
                    except IOError:
                        utils.handle_error("failed to save file")
            except:
                utils.handle_error("failed to read file")
        except IOError:
            utils.handle_error("file not found")
예제 #51
0
def make_series_list(url):
    params = utils.get_url(url)

    try:
        category = params["category"]
        series_list = comm.get_programme_from_feed(category)
        series_list.sort()

        ok = True
        for s in series_list:
            url = "%s?%s" % (sys.argv[0], utils.make_url({'series': s.title, 'category': category}))

            thumbnail = s.get_thumbnail()
            listitem = xbmcgui.ListItem(s.get_list_title(), iconImage=thumbnail, thumbnailImage=thumbnail)
            listitem.setInfo('video', { 'plot' : s.get_description() })

            # add the item to the media list
            ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True)

        xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
        xbmcplugin.setContent(handle=int(sys.argv[1]), content='tvshows')
    except:
        utils.handle_error('Unable to fetch program list. Please try again later.')
예제 #52
0
def play(url):
    addon = xbmcaddon.Addon(config.ADDON_ID)

    try:
        p = classes.Program()
        p.parse_xbmc_url(url)

        # Some programs don't have protected streams. 'Public' streams are
        # set in program.url, otherwise we fetch it separately
        if p.get_url():
            stream_url = p.get_url()
        else:
            stream_url = comm.get_stream(p.id)

        listitem = xbmcgui.ListItem(label=p.get_list_title(), iconImage=p.thumbnail, thumbnailImage=p.thumbnail)
        listitem.setInfo("video", p.get_xbmc_list_item())

        if hasattr(listitem, "addStreamInfo"):
            listitem.addStreamInfo("audio", p.get_xbmc_audio_stream_info())
            listitem.addStreamInfo("video", p.get_xbmc_video_stream_info())

        xbmc.Player().play(stream_url, listitem)
    except:
        utils.handle_error("Unable to play video")
예제 #53
0
    def GET(self,page_name):
        access = utils.page_access(page_name,utils.PERM_WRITE)
        if access is not None:  return access

        data = web.input(order="")
        try:
            content = utils.fetch_file(page_name)
            try:
                obj = json.loads(content) 
                obj["order"] = data.order
                try:
                    utils.save_file(page_name,json.dumps(obj))
                    return utils.callback('{"success":"1"}')
                except IOError:
                    utils.handle_error("failed to save file")
            except:
                utils.handle_error("failed to read file")
        except IOError:
            utils.handle_error("file not found")
예제 #54
0
    def GET(self,page_name):
        access = utils.page_access(page_name,utils.PERM_WRITE)
        if access is not None:  return access

        data = web.input(new_name="")
        ## Fix name
        try:
            content = utils.fetch_file(page_name)
            try:
                obj = json.loads(content)
                obj["name"] = data.new_name
                try:
                    utils.save_file(page_name,json.dumps(obj))
                    new_name = { 'name' : data.new_name }
                    return utils.callback(json.dumps(new_name))
                except IOError:
                    utils.handle_error("failed to save file")
            except:
                utils.handle_error("failed to read file")
        except IOError:
            utils.handle_error("file not found")
예제 #55
0
    def GET(self,page_name,id,list_item_id):
        access = utils.page_access(page_name,utils.PERM_WRITE)
        if access is not None:  return access

        try:
            content = utils.fetch_file(page_name)
            try:
                obj = json.loads(content)
                component = obj["components"][id]
                ## Check items first
                if component["items"].has_key(list_item_id):
                    del component["items"][list_item_id]
                    ## Remove from order
                    if component['order'] != "":
                        current_order = component['order'].split(',')
                    else:
                        current_order = []

                    x = 0
                    for i in current_order:
                        if int(i) == int(list_item_id):
                            del current_order[x]
                        x = x + 1
                    current_order = ",".join(current_order)
                    component['order'] = current_order
                else:
                    ## In the completed section
                    del component["completed"][list_item_id]
                    ## We don't need to remove from order since it's in completed

                try:
                    utils.save_file(page_name,json.dumps(obj))
                    return utils.callback('{"id":"' + id + '", "list_item_id":"' + list_item_id +'"}')

                except IOError:
                    utils.handle_error("failed to save file")
            except:
                utils.handle_error("failed to read file")
        except IOError:
            utils.handle_error("file not found")
예제 #56
0
    def GET(self,page_name,id):
        access = utils.page_access(page_name,utils.PERM_WRITE)
        if access is not None:  return access

        try:
            content = utils.fetch_file(page_name)
            try:
                obj = json.loads(content)
                if obj["components"][id].has_key("completed"):
                    del obj["components"][id]["completed"]
                else:
                    return "{'error': 'no completed items'}"

                try:
                    utils.save_file(page_name,json.dumps(obj))
                    return utils.callback("{'id': " + id + " }")
                except IOError:
                    utils.handle_error("failed to save file")
            except:
                utils.handle_error("failed to read file")
        except IOError:
            utils.handle_error("file not found")
예제 #57
0
    def GET(self,page_name,id,list_id):
        access = utils.page_access(page_name,utils.PERM_WRITE)
        if access is not None:  return access

        data = web.input(title="")
        try:
            content = utils.fetch_file(page_name)
            try:
                obj = json.loads(content)
                obj["components"][id]["items"][list_id]["title"] = data.title

                try:
                    utils.save_file(page_name,json.dumps(obj))

                    component = obj["components"][id]["items"][list_id]
                    component["id"] = id;
                    component["list_item_id"] = list_id
                    return utils.callback(json.dumps(component))
                except IOError:
                    utils.handle_error("failed to save file")
            except:
                utils.handle_error("failed to read file")
        except IOError:
            utils.handle_error("file not found")
예제 #58
0
    def GET(self,page_name,id,list_item_id):
        access = utils.page_access(page_name,utils.PERM_WRITE)
        if access is not None:  return access

        data = web.input(status="")
        try:
            content = utils.fetch_file(page_name)
            try:
                obj = json.loads(content)
                if data.status == "completed":
                    item = obj["components"][id]["items"][list_item_id]
                    # remove the item from items and put in completed

                    if obj["components"][id].has_key("order"):
                        current_order = obj["components"][id]['order'].split(',')
                    else:
                        current_order = ""

                    # remove from the order
                    x = 0
                    for i in current_order:
                        if int(i) == int(list_item_id):
                            del current_order[x]
                        x = x + 1

                    current_order = ",".join(current_order)
                    obj["components"][id]['order'] = current_order
                    item["completed"] = time.time()
                    if obj["components"][id].has_key("completed"): 
                        obj["components"][id]["completed"][list_item_id] = item
                    else:
                        obj["components"][id]["completed"] = {}
                        obj["components"][id]["completed"][list_item_id] = item
                    del  obj["components"][id]["items"][list_item_id]
                else:
                    item = obj["components"][id]["completed"][list_item_id]
                    del item["completed"] 
                    
                    current_order = obj["components"][id]['order'].split(',')
                    current_order.append(list_item_id)
                    current_order = ",".join(current_order)
                    ## How does this happen, an extra comma?
                    current_order = current_order.strip(",")        
 
                    obj["components"][id]['order'] = current_order

                    obj["components"][id]["items"][list_item_id] = item
                    del  obj["components"][id]["completed"][list_item_id]

                try:
                    utils.save_file(page_name,json.dumps(obj))
                    item["id"] = id
                    item["list_item_id"] = list_item_id
                    item["status"] = data.status
                    if item.has_key("completed"):
                        date = datetime.fromtimestamp(item["completed"])
                        item["completed"] = date.strftime("%b %d")
                    return utils.callback(json.dumps(item))
                except IOError:
                    utils.handle_error("failed to save file")
            except:
                utils.handle_error("failed to read file")
        except IOError:
            utils.handle_error("file not found")
예제 #59
0
def play(url):
    addon = xbmcaddon.Addon(config.ADDON_ID)

    try:
        p = classes.Program()
        p.parse_xbmc_url(url)

        # Some programs don't have protected streams. 'Public' streams are
        # set in program.url, otherwise we fetch it separately
        if p.get_url():
            stream_url = p.get_url()
        else:
            stream_url = comm.get_stream(p.id)

        listitem=xbmcgui.ListItem(label=p.get_list_title(),
                                  iconImage=p.thumbnail,
                                  thumbnailImage=p.thumbnail,
                                  path=stream_url)
        listitem.setInfo('video', p.get_xbmc_list_item())

        #add subtitles if available
        if addon.getSetting('subtitles_enabled') == 'true' and p.get_subfilename():
            subtitles = None
            profile = xbmcaddon.Addon().getAddonInfo('profile')
            path = xbmc.translatePath(profile).decode('utf-8')
            if not os.path.isdir(path):
                os.makedirs(path)
            subfile = xbmc.translatePath(os.path.join(path, 'subtitles.eng.srt'))
            if os.path.isfile(subfile):
                os.remove(subfile)
            x = stream_url.find('managed')+8
            subdate = stream_url[x:x+11]
            suburl = config.subtitle_url+subdate+p.get_subfilename()
            try:
                data = urllib2.urlopen(suburl).read()
                f = open(subfile, 'w')
                f.write(data)
                f.close()
                if hasattr(listitem, 'setSubtitles'):
                    # This function only supported from Kodi v14+
                    listitem.setSubtitles([subfile])
                else:
                    subtitles = True
            except:
                utils.log('Subtitles not available for this program')

        if hasattr(listitem, 'addStreamInfo'):
            listitem.addStreamInfo('audio', p.get_xbmc_audio_stream_info())
            listitem.addStreamInfo('video', p.get_xbmc_video_stream_info())

        xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, listitem=listitem)

        # Enable subtitles for XBMC v13
        if addon.getSetting('subtitles_enabled') == "true" and p.get_subfilename():
            if subtitles == True:
                if not hasattr(listitem, 'setSubtitles'):
                    player = xbmc.Player()
                    while not player.isPlaying():
                        xbmc.sleep(100) # wait until video is being played
                        player.setSubtitles(subfile)
    except:
        utils.handle_error("Unable to play video")