示例#1
0
def newsfooter(page, category):
    newsconf = _config['pages']['news']

    nextpage = ttxutils.nextpage(page.page)
    lastpage = ttxutils.nextpage(newsconf['main']['last'])
    lastregpage = ttxutils.nextpage(newsconf['regional']['last'])
    if nextpage in [lastpage, lastregpage]:
        fastext = (red() + 'In Depth ' + green() + 'News Indx' + yellow() +
                   'Headlines' + cyan() + 'Main Menu')
    else:
        fastext = (red() + 'Next News' + green() + 'News Indx' + yellow() +
                   'Headlines' + cyan() + 'Main Menu')

    if category:
        lines = [
            '€T€]€GREGIONAL €CHeadlines€G160€CSport   €G390',
            '€D€]€GNATIONAL€C Main menu€G100€CWeather€G 400', fastext
        ]
    else:
        lines = [
            '€D€]€CHome news digest€G141€CWorld digest€G142',
            '€D€]€CNews Index€G102€CFlash€G150€CRegional€G160', fastext
        ]

    line = 22
    for l in lines:
        page.addline(line, ttxutils.decode(l))
        line += 1
    if nextpage > newsconf['regional']['headlines']:
        page.addfasttext(nextpage, newsconf['regional']['headlines'],
                         newsconf['main']['headlines'], 0x100, 0x8ff, 0x199)
    else:
        page.addfasttext(nextpage, newsconf['main']['index'],
                         newsconf['main']['headlines'], 0x100, 0x8ff, 0x199)
示例#2
0
def news_summary(entries, conf):
    summarynum = conf['summary']
    page = ttxpage.TeletextPage(f"News Summary {summarynum:03x}",
                                summarynum,
                                time=15)
    offset = 0
    pagenum = conf['first']
    for subpage in range(2):
        page.header(summarynum, subpage + 1, status=0xc000)
        newsheaders.newsheader(page, 'summary')
        index = f"{subpage + 1}/2 "
        page.addline(4, f"{index:>40}")
        line = 5
        while offset < len(entries):
            contents = entries[offset]
            para = contents['text'][0]
            lines = page.wrapline(line, 21, page.fixup(para), ttxcolour.cyan())
            if lines:
                line += lines
                page.addline(line, f" See {pagenum:03x}")
                line += 2
                pagenum = ttxutils.nextpage(pagenum)
                offset += 1
            else:
                break
        newsheaders.newssummaryfooter(page)
    page.save()
示例#3
0
def cricket():
    pages = _config['pages']['sport']['cricket']
    feed = bbcparse.Feed(rss.bbc_feed(pages['feed']), 'cricket')
    raw_entries = feed.get_entries(sport=True,
                                   max = ttxutils.hexdiff(
                                       pages['last'], pages['first']))

    if not raw_entries:
        return None

    pagenum = pages['first']
    entries = list()
    for contents in raw_entries:
        if '/cricket/' in contents['link']:
            contents['section'] = 'Cricket'
            entries.append(contents)

    for contents in entries:
        sport_page(pagenum, contents)
        pagenum = ttxutils.nextpage(pagenum)
        if pagenum > pages['last']:
            break

    scorecards = cricket_fixtures()
    cricket_index(entries, scorecards)

    return [entries[0], pages['first']]
示例#4
0
def football():
    pages = _config['pages']['sport']['football']
    footballfeed = bbcparse.Feed(rss.bbc_feed(pages['feed']), 'football')
    entries = footballfeed.get_entries(sport=True,
                                       max = ttxutils.hexdiff(
                                           pages['last'], pages['first']))
    if not entries:
        return None

    pagenum = pages['first']
    footentries = list()
    for contents in entries:
        if '/football/' in contents['link']:
            contents['section'] = 'Football'
            footentries.append(contents)

    count = 2
    for contents in footentries:
        sport_page(pagenum, contents, add_to_newsreel=(count>0))
        pagenum = ttxutils.nextpage(pagenum)
        count -= 1
        if pagenum > pages['last']:
            break

    football_index(footentries)

    # league tables go here
    leagues()
    fixtures()
    football_gossip()
    football_guide(pages)

    return [footentries[0], pages['first']]
示例#5
0
def formula1():
    pages = _config['pages']['sport']['formula1']
    f1feed = bbcparse.Feed(rss.bbc_feed(pages['feed']), 'formula1')
    entries = f1feed.get_entries(sport=True,
                                 max = ttxutils.hexdiff(
                                     pages['last'], pages['first']))

    if not entries:
        return None
    pagenum = pages['first']
    f1entries = list()
    for contents in entries:
        if '/formula1/' in contents['link']:
            contents['section'] = 'Formula 1'
            f1entries.append(contents)

    for contents in f1entries:
        sport_page(pagenum, contents)
        pagenum = ttxutils.nextpage(pagenum)
        if pagenum > pages['last']:
            break

    f1_index(f1entries)

    return [f1entries[0], pages['first']]
示例#6
0
def rugby_union():
    pages = _config['pages']['sport']['rugby_union']
    feed = bbcparse.Feed(rss.bbc_feed(pages['feed']), 'rugby_union')
    raw_entries = feed.get_entries(sport=True,
                                   max = ttxutils.hexdiff(
                                       pages['last'], pages['first']))
    if not raw_entries:
        return None

    pagenum = pages['first']
    entries = list()
    for contents in raw_entries:
        if '/rugby-union/' in contents['link']:
            contents['section'] = 'Rugby Union'
            entries.append(contents)

    for contents in entries:
        sport_page(pagenum, contents)
        pagenum = ttxutils.nextpage(pagenum)
        if pagenum > pages['last']:
            break

    rugby_union_index(entries)

    return [entries[0], pages['first']]
示例#7
0
def makenews():

    headlines = []

    region = _config['bbc_news_regions'][_config['bbc_news_region']]
    news = _config['pages']['news']['main']
    regional = _config['pages']['news']['regional']

    newsfeed = bbcparse.Feed(rss.bbc_feed(news['feed']), 'newsmain')
    numstories = ttxutils.hexdiff(news['last'], news['first'])
    stories = newsfeed.get_entries(max=numstories)

    regionalfeed = bbcparse.Feed(rss.bbc_feed(region['feed']), "newsregional")
    numstories = ttxutils.hexdiff(regional['last'], regional['first'])
    regionalstories = regionalfeed.get_entries(max=numstories)

    page = news['first']
    if stories:
        for story in stories:
            news_page(page, story, add_to_newsreel=True)
            page = ttxutils.nextpage(page)
        news_index(stories, news)
        news_headlines(stories, news)
        news_summary(stories, news)
        topstory = copy.deepcopy(stories[0])
        topstory['section'] = 'UK News'
        headlines.append((topstory, news['first']))

    page = regional['first']
    if regionalstories:
        for story in regionalstories:
            news_page(page, story)
            page = ttxutils.nextpage(page)
        news_headlines(regionalstories, regional, region['name'])
        topregstory = copy.deepcopy(regionalstories[0])
        topregstory['section'] += ' News'
        headlines.append((topregstory, regional['first']))

    scitech = _config['pages']['news']['scitech']
    scitechfeed = bbcparse.Feed(rss.bbc_feed(scitech['feed']), "newssci")
    scitechstories = scitechfeed.get_entries()
    if scitechstories:
        news_scitech(scitechstories, scitech)

    return headlines
示例#8
0
def news_index(entries, conf):
    pagenum = conf['index']
    page = ttxpage.TeletextPage("News Index {:03x}".format(pagenum),
                                pagenum,
                                time=15)

    toptitles = []
    subtitles = []
    index = 0
    nextpage = conf['first']
    for contents in entries:
        if index < 3:
            textcolour = ttxcolour.cyan()
        else:
            textcolour = ttxcolour.white()
        headline = page.truncate(contents['short_title'], 35, ' ')
        if index <= 11:
            toptitles.append("{}{:<35}{}{:03x}".format(textcolour, headline,
                                                       ttxcolour.yellow(),
                                                       nextpage))
        else:
            subtitles.append("{}{:<35}{}{:03x}".format(textcolour, headline,
                                                       ttxcolour.yellow(),
                                                       nextpage))
        index += 1
        nextpage = ttxutils.nextpage(nextpage)

    maxsubpage = int((len(subtitles) + 2) / 3)
    for subpage in range(maxsubpage):
        line = 4
        page.header(pagenum, subpage + 1, status=0xc000)
        category = newsheaders.newsheader(page, 'index')
        for t in toptitles:
            if line == 10:
                line += 1
            page.addline(line, t)
            line += 1
        page.addline(
            17, "{}Other News {}/{}".format(ttxcolour.yellow(), subpage + 1,
                                            maxsubpage))
        line = 18

        offset = subpage * 3
        subset = subtitles[offset:offset + 3]
        for t in subset:
            page.addline(line, t)
            line += 1

        newsheaders.newsindexfooter(page)
        if offset + 3 > len(subtitles):
            break

    page.save()
示例#9
0
def entertainment():
    pages = _config['pages']['entertainment']
    feed = bbcparse.Feed(rss.bbc_feed(pages['feed']), 'football')
    entries = feed.get_entries(
        max=ttxutils.hexdiff(pages['last'], pages['first']))

    if not entries:
        return None

    header = [
        "€C€]€U|$xl0l<h<h<t(|$|l4|`<t`<<th<`<t(|$",
        "€C€]€U¬1¬j5j5jwj7} ¬ ¬k5¬j5¬j55¬jwj5¬ ¬",
        "€S#######################################"
    ]
    footer = [
        "€C€]€DTV    520  Lottery   555  Music 530",
        "€C€]€DFilms 540  Newsround 570  Games 550",
        "€ANext News€B FilmIndex€CTV Index€FEntsIndex",
    ]
    fastext = [0x540, 0x520, 0x500]
    pagenum = pages['first']

    for contents in entries:
        nextpage = ttxutils.nextpage(pagenum)
        if nextpage > pages['last']:
            nextpage = pages['index']
        ttxutils.news_page("Entertainment",
                           pages,
                           pagenum,
                           contents,
                           header,
                           footer,
                           fasttext=[nextpage, 0x540, 0x520, 0x500])
        pagenum = ttxutils.nextpage(pagenum)
        if pagenum > pages['last']:
            break

    entertainment_index(pages, entries)

    return (entries[0], pages['first'])
示例#10
0
def news_headlines(entries, conf, region=None):
    pagenum = conf['headlines']
    if region:
        page = ttxpage.TeletextPage(f"Regional Headlines {pagenum:03x}",
                                    pagenum)
        page.header(pagenum)
        category = newsheaders.newsheader(page, region)
        nextpage = conf['first']
        maxlines = 9
    else:
        page = ttxpage.TeletextPage(f"News Headlines {pagenum:03x}", pagenum)
        page.header(pagenum)
        category = newsheaders.newsheader(page, 'headlines')
        nextpage = conf['first']
        maxlines = 8

    line = 4
    count = 0

    for contents in entries:
        if line == 4:
            textattr = ttxcolour.colour(ttxcolour.DOUBLE_HEIGHT)
        else:
            textattr = ttxcolour.colour(ttxcolour.ALPHAWHITE)
        headline = page.truncate(contents['short_title'], 70, ' ')
        headlines = textwrap.wrap(headline, 35)
        page.addline(
            line, '{}{:<35}{}{:03x}'.format(textattr, headlines[0],
                                            ttxcolour.yellow(), nextpage))
        nextpage = ttxutils.nextpage(nextpage)

        if line <= 4:
            line += 2
        else:
            line += 1
        if line >= 22:
            break

        if len(headlines) > 1:
            page.addline(line, '{}  {}'.format(ttxcolour.white(),
                                               headlines[1]))

        if line < 7 and region is None:
            line += 2
        else:
            line += 1
        count += 1
        if count >= maxlines:
            break

    newsheaders.newsheadlinesfooter(page, category)
    page.save()
示例#11
0
def sport_footer(page, section):
    nextpage = ttxutils.nextpage(page.page)
    if nextpage == 0x316:
        nextpage = 0x324
    if is_football(section):
        footer = [
            "€D€]€CCEEFAX FOOTBALL SECTION PAGE 302",
            "€D€]€CBBC WEBSITE: bbc.co.uk/football",
            "€ANext page  €BFootball €CHeadlines €FSport",
        ]
        pages = _config['pages']['sport']['football']
        index = pages['index']
    elif section in [ 'Formula 1', 'formula1' ]:
        footer = [
            "€D€]€CCEEFAX MOTORSPORT SECTION PAGE 360   ",
            "€D€]€CBBC WEBSITE: bbc.co.uk/motorsport    ",
            "€ANext page  €BM/sport  €CHeadlines €FSport ",
        ]
        pages = _config['pages']['sport']['formula1']
        index = pages['index']
    elif section in [ 'Cricket' ]:
        footer= [
            "€D€]€CCEEFAX CRICKET SECTION PAGE 340   ",
            "€D€]€CBBC WEBSITE: bbc.co.uk/cricket    ",
            "€ANext page  €BCricket €CHeadlines €FSport ",
        ]
        pages = _config['pages']['sport']['cricket']
        index = pages['index']
    elif section in [ 'Rugby Union' ]:
        footer= [
            "€D€]€CCEEFAX RUGBY SECTION PAGE 370   ",
            "€D€]€CBBC WEBSITE: bbc.co.uk/rugby    ",
            "€ANext page  €BRugby U €CHeadlines €FSport ",
        ]
        pages = _config['pages']['sport']['rugby_union']
        index = pages['index']
    else:
        footer = [
            "€D€]€CCEEFAX SPORT SECTION PAGE 300",
            "€D€]€CBBC WEBSITE: bbc.co.uk/sport",
            "€ANext page  €BFootball €CHeadlines €FSport",
        ]
        pages = _config['pages']['sport']['football']
        index = pages['index']

    line = 22
    for l in footer:
        page.addline(line, ttxutils.decode(l))
        line += 1
    page.addfasttext(nextpage, index, 0x301, 0x300, 0x8FF, 0x199)
示例#12
0
def cricket_fixtures():
    try:
        with open(f"{_config['cachedir']}/cricket_fixtures.cache", 'rb') as f:
            cache = pickle.load(f)
    except:
        cache = dict()

    scores = _config['cricket_scorecards']['first']
    scores_last = _config['cricket_scorecards']['last']
    scorecards = []

    for page, offsets in _config['cricket_fixtures']:
        links = cricket_fixture_page(page, offsets, cache)
        if links:
            for l in links:
                l = f'https://www.bbc.co.uk{l}'
                if scores <= scores_last:
                    match = cricket_scorecard_page(scores, l, cache)
                    scorecards.append((scores, match))
                    scores = ttxutils.nextpage(scores)

    with open(f"{_config['cachedir']}/cricket_fixtures.cache", 'wb') as f:
        pickle.dump(cache, f)
    return scorecards
示例#13
0
def cricket_scorecard_page(pagenum, url, cache):
    nextpage = ttxutils.nextpage(pagenum)
    page = ttxpage.TeletextPage("Cricket Scorecard",
                                pagenum)

    maxrows = 18
    pages = []
    data = cricket_scorecard_table(url, cache)

    match = data['match'].upper()
    match = match.replace('INTERNATIONAL ','')
    match = match.replace(' -','')
    match = match.replace(' SERIES','')
    match = match.replace('UNDER-','U')
    short_match = match.replace("MATCH", "").strip()
    short_match = re.sub(r"\s*DAY\s+\d+\s+OF\s+\d+.*", r"", short_match)
    match = re.sub(r'DAY\s+(\d+)\s+OF\s+\d+.*',
                   r'(Day \1)', match)
    if data['venue']:
        match += f", {data['venue']}"
    home_line = f"{data['home_name']}: "
    home_line += " & ".join(
        [f.replace(' all out','') for f in data['home_scores']])
    away_line = f"{data['away_name']}: "
    away_line += " & ".join(
        [f.replace(' all out','') for f in data['away_scores']])

    header = [
        f"{ttxcolour.green()}{page.fixup(match)}",
        f"{ttxcolour.yellow()}{page.fixup(home_line)}",
        f"{ttxcolour.yellow()}{page.fixup(away_line)}",
    ]
    for i in data['innings']:
        rows = []
        rows.extend(header)
        r = f"{ttxcolour.white()}{page.fixup(i['name'])}:"
        rows.append(f"{r:<41}")
        for m in i['batting']:
            colour = ttxcolour.cyan()
            if len(m) > 4:
                batsman, how_out, bowler, runs = m[:4]
                batsman = page.fixup(names.shorten(batsman))
                if how_out == 'not out':
                    colour = ttxcolour.white()
                elif how_out.startswith("run out"):
                    s = re.search(r'(\(.+?\))', how_out)
                    how_out = "run out"
                    bowler = s[1]
                else:
                    if ' ' in how_out:
                        how, _, fielder = how_out.partition(' ')
                        how_out = f"{how} {names.shorten(fielder)}"
                if bowler:
                    bowler = page.fixup(bowler)
                    if 'c & b' in bowler:
                        bowler = bowler.replace('c & b', 'b')
                        how_out = 'c &'
                    how, _, name = bowler.partition(' ')
                    bowler = f"{how} {names.shorten(name)}"
                how_out = page.fixup(how_out)
                r = f"{colour}{batsman:<9} {how_out:<12} {bowler:<12} {runs:>3}"
                rows.append(r)
            else:
                extras = page.fixup(m[1].strip())
                runs = m[2]
                extratext = "          Extras "
                if extras:
                    extratext += f"({extras})"
                r = f"{colour}{extratext:<36}{runs:>3}"
                rows.append(r)

        # total row
        runs = i['runs']
        dec = ''
        if "all out" in runs:
            wickets = "all out"
            runs = runs.replace("all out", "").strip()
        else:
            if "dec" in runs:
                runs = re.sub(r'\s*dec$', r'', runs)
                dec = ' dec'
            s = re.search(r'(\d+)-(\d+)', runs)
            runs = s[1]
            wickets = f"for {s[2]} wkts{dec}"
        s = re.search(r'([0-9]+)', i['overs'])

        total = f"TOTAL ({wickets}, {s[1]} ovs)"
        r = f"{ttxcolour.white()}{total:<36}{runs:>3}"
        rows.append(r)

        falls = i['falls']
        if falls:
            falls = [re.sub(r"(\d+-\d+).*", r"\1", f[0]) for f in falls]
            r = "Fall: " + " ".join(falls[:5])
            rows.append(f'{ttxcolour.white()}{r:<39}')
            r = "      " + " ".join(falls[5:])
            rows.append(f'{ttxcolour.white()}{r:<39}')
        else:
            rows.append('')

        r = page.fixup(data['status'].upper())
        rows.append(f'{ttxcolour.yellow()}{r:<39}')
        if len(rows) < 20:
            r = page.fixup(data['toss'])
            rows.append(f'{ttxcolour.cyan()}{r:<39}')

        pages.append(copy.deepcopy(rows))

    subpage = 0
    for p in pages:
        if len(pages) > 1:
            subpage += 1
            page.header(pagenum, subpage, status=0xc000)
        else:
            page.header(pagenum, subpage, status=0x8000)
        sport_header(page, 'Cricket')
        if len(pages) > 1:
            index = f"{subpage}/{len(pages)}"
            p[0] = f"{p[0]:<34.34}{ttxcolour.white()}{index:>5}"
        line = 4
        for r in p:
            if len(r):
                page.addline(line, r)
            line += 1
        footer= [
            "€ANext page  €BCricket €CHeadlines €FSport ",
        ]
        line = 25 - len(footer)
        for l in footer:
            page.addline(line, ttxutils.decode(l))
            line += 1

        pagec = _config['pages']['sport']['cricket']
        index = pagec['index']
        nextpage = ttxutils.nextpage(pagenum)
        page.addfasttext(nextpage, index, 0x301, 0x300, 0x8FF, 0x199)

    page.save()

    return f"{short_match}: {data['home_name']} v {data['away_name']}"
示例#14
0
def football_gossip_page(pagenum, entries):
    nextpage = ttxutils.nextpage(pagenum)
    page = ttxpage.TeletextPage("Football Gossip",
                                pagenum)

    maxrows = 18
    pages = []
    header = f"{ttxcolour.green()}Gossip column"
    p = [header]
    for f in entries:
        h, l, t = f
        h = page.fixup(h)
        l = page.fixup(l)
        t = page.fixup(t)
        lines = textwrap.wrap(f"{h}¬\t{l}",39,
                              expand_tabs=False, replace_whitespace=False)
        rows = []
        colour = ttxcolour.white()
        for ll in lines:
            if '\t' in ll or '¬' in ll:
                ll = ll.replace('¬', '\t')
                ll = ll.replace('\t\t', '\t')
                ll = ll.replace('\t', ttxcolour.cyan())
                rows.append(f"{colour}{ll}")
                colour = ttxcolour.cyan()
            else:
                rows.append(f"{colour}{ll}")
        if len(rows[-1]) + len(t) > 40:
            rows.append(f"{ttxcolour.green()}{t:>39}")
        else:
            rows[-1] += f"{ttxcolour.green()}{t}"
        if ((len(p) + len(rows) <  maxrows)
            or (len(p) == 0 and len(rows) == maxrows)):
            if len(p)>1:
                p.append('')
            p.extend(rows)
        else:
            pages.append(p)
            p = [header]
            p.extend(rows)
    pages.append(p)

    subpage = 0
    for p in pages:
        if len(pages) > 1:
            subpage += 1
            page.header(pagenum, subpage, status=0xc000)
        else:
            page.header(pagenum, subpage, status=0x8000)
        sport_header(page, 'Football')
        if len(pages) > 1:
            index = f"{subpage}/{len(pages)}"
            p[0] = f"{p[0]:<34}{ttxcolour.white()}{index:>5}"
        line = 4
        for r in p:
            if len(r):
                page.addline(line, r)
            line += 1
        sport_footer(page, 'Football')

    page.save()
示例#15
0
def league(pagenum, url, cache):
    nextpage = ttxutils.nextpage(pagenum)
    page = ttxpage.TeletextPage("Football League Table",
                                pagenum)

    league, date, table = league_table(url, cache)

    league = league.upper().replace(" TABLE", "")
    datefmt = date.strftime("%b %d %H:%M")

    subpage = 1
    footers = [
        "€ANext page  €BFootball €CHeadlines €FSport"
    ]

    count = 0
    for r in table:
        count += 1
        if r[8]:
            count += 1

    pages = math.ceil(count / 14)
    if len(table) == 12:
        pages = 1

    newpage = True
    white = True
    row = 1
    pagecount = 0
    status = 0x8000
    if pages > 1:
        status = 0xc000
    for r in table:
        if newpage:
            pagecount += 1
            page.header(pagenum, subpage, status=status)
            sport_header(page, 'Football')
            if pages > 1:
                index = f"{ttxcolour.white()}{pagecount}/{pages}"
            else:
                index = ''

            page.addline(4, f"{ttxcolour.green()} {league:<32} {index}")
            page.addline(6, f"{ttxcolour.white()} {datefmt}    P  W  D  L   F   A Pts")
            line = 8
            newpage = False

        if white:
            colour = ttxcolour.white()
        else:
            colour = ttxcolour.cyan()
        white = not white
        team = r[0]
        team = team.replace("Crystal Palace", "C Palace")
        team = team.replace("Huddersfield", "H'field")
        team = team[:12]

        p = f"{r[1]:>2}"
        w = f"{r[2]:>2}"
        d = f"{r[3]:>2}"
        l = f"{r[4]:>2}"
        f = f"{r[5]:>3}"
        a = f"{r[6]:>3}"
        pts = f"{r[7]:>3}"
        brk = r[8]

        page.addline(line, f"{colour}{row:>2} {team:<12} {p} {w} {d} {l} {f} {a} {pts}")
        row += 1
        line += 1
        if brk and line < 21:
            page.addline(line,
                         "{}```````````````````````````````````````".format(
                             ttxcolour.red()))
            line += 1

        if (line > 21 and len(table)>12) or (line > 22):
            subpage += 1
            newpage = True
            line = 24
            for l in footers:
                page.addline(line, ttxutils.decode(l))
                line += 1
            page.addfasttext(nextpage, 0x302, 0x301, 0x300, 0x8ff, 0x320)

    if not newpage:
        line = 24
        for l in footers:
            page.addline(line, ttxutils.decode(l))
            line += 1
        page.addfasttext(nextpage, 0x302, 0x301, 0x300, 0x8ff, 0x320)
    page.save()
示例#16
0
def fixture_page(pagenum, date, dayname, cache):
    nextpage = ttxutils.nextpage(pagenum)
    page = ttxpage.TeletextPage("Football Fixtures",
                                pagenum)

    maxrows = 18
    isodate = date.isoformat()
    url = f"{_config['football_fixtures_url']}/{isodate}"
    fixes = fixtures_table(url, cache)
    pages = []
    header = f"{ttxcolour.green()}{dayname}"
    p = [header]
    for f in fixes:
        rows = []
        r = f"{ttxcolour.white()}{page.fixup(f['league']).upper()}"
        if f['round_']:
            r += f"{ttxcolour.magenta()}{page.fixup(f['round_'])}"
        rows.append(f"{r:<38}")
        for m in f['matches']:
            home_team = page.fixup(m['home_team'])[:13]
            away_team = page.fixup(m['away_team'])[:13]
            r = f"{ttxcolour.cyan()}{home_team:<13}"
            if m['kickoff']:
                r += f"{ttxcolour.white()}{'v':^5}"
            else:
                r += f"{ttxcolour.white()}{m['home_goals']:>2}"
                r += f"-{m['away_goals']:<2}"
            r += f"{ttxcolour.cyan()}{away_team:<13}"
            if m['kickoff']:
                r += f"{ttxcolour.green()}{page.fixup(m['kickoff']):>5}"
            elif m['status']:
                status = page.fixup(m['status'])[:5]
                r += f"{ttxcolour.yellow()}{status:>5}"
            rows.append(r)
        if ((len(p) + len(rows) <  maxrows)
            or (len(p) == 0 and len(rows) == maxrows)):
            if len(p)>1:
                p.append('')
            p.extend(rows)
        else:
            pages.append(p)
            p = [header]
            p.extend(rows)
    if len(fixes) == 0:
        p.append('')
        p.append(f'{ttxcolour.cyan()}No matches today.')
    pages.append(p)

    subpage = 0
    for p in pages:
        if len(pages) > 1:
            subpage += 1
            page.header(pagenum, subpage, status=0xc000)
        else:
            page.header(pagenum, subpage, status=0x8000)
        sport_header(page, 'Football')
        if len(pages) > 1:
            index = f"{subpage}/{len(pages)}"
            p[0] = f"{p[0]:<34}{ttxcolour.white()}{index:>5}"
        line = 4
        for r in p:
            if len(r):
                page.addline(line, r)
            line += 1
        sport_footer(page, 'Football')

    page.save()
示例#17
0
def cricket_fixture_page(pagenum, dates, cache):
    nextpage = ttxutils.nextpage(pagenum)
    page = ttxpage.TeletextPage("Cricket Fixtures",
                                pagenum)

    maxrows = 18
    pages = []
    links = []
    for offset in dates:
        date = datetime.date.today() + datetime.timedelta(days=offset)
        if offset == 0:
            dayname = "Today"
        elif offset == -1:
            dayname = "Yesterday"
        else:
            dayname = date.strftime("%A")

        isodate = date.isoformat()
        url = f"{_config['cricket_fixtures_url']}/{isodate}"
        fixes = cricket_fixtures_table(url, cache)
        header = f"{ttxcolour.yellow()}{dayname}'s Matches"
        p = [header]
        for f in fixes:
            rows = []
            r = f"{ttxcolour.white()}{page.fixup(f['series']).upper()}"
            rows.append(f"{r:<38}")
            for m in f['matches']:
                if len(rows)>1:
                    rows.append('')
                home_team = page.fixup(m['home_team'])
                away_team = page.fixup(m['away_team'])
                if m['home_batting']:
                    home_team = f"{home_team:<.16}{ttxcolour.yellow()}*"
                    r = f"{ttxcolour.cyan()}{home_team:<18.18}"
                else:
                    r = f"{ttxcolour.cyan()}{home_team:<17.17}"
                r += f"{ttxcolour.white()}v"
                if m['away_batting']:
                    away_team = f"{away_team:<.16}{ttxcolour.yellow()}*"
                    r += f"{ttxcolour.cyan()}{away_team:<18.18}"
                else:
                    r += f"{ttxcolour.cyan()}{away_team:<17.17}"
                rows.append(r)
                if m['title']:
                    rows.append(f"{ttxcolour.green()}{page.fixup(m['title'])}")
                if m['home_score'] or m['away_score']:
                    if offset in [-1, 0]:
                        links.append(m['link'])
                    for innings in range(2):
                        if m['home_score'] and innings < len(m['home_score']):
                            a = page.fixup(m['home_score'][innings])
                        else:
                            a = ''
                        if m['away_score'] and innings < len(m['away_score']):
                            b = page.fixup(m['away_score'][innings])
                        else:
                            b = ''
                        if a or b:
                            r = f"{ttxcolour.cyan()}{a:<17.17}   {b:<17.17}"
                            rows.append(r)

                r = ''
                if m['time']:
                    if m['time'] not in ['LIVE', 'V']:
                        r += page.fixup(m['time'])
                if m['status']:
                    status = page.fixup(m['status'])
                    r += f"¬\t{status}"
                if m['venue']:
                    venue = m['venue'].replace('Venue: ','').strip()
                    venue = page.fixup(venue)
                    r += f"¬\t{venue}"
                colour = ttxcolour.green()
                for ll in textwrap.wrap(r, 39, expand_tabs=False,
                                        replace_whitespace=False):
                    if '\t' in ll or '¬' in ll:
                        ll = ll.replace('¬', '\t')
                        ll = ll.replace('\t\t', '\t')
                        if ll.startswith('\t'):
                            ll = ll.replace('\t','')
                            colour = ttxcolour.magenta()
                        else:
                            ll = ll.replace('\t', ttxcolour.magenta())
                        rows.append(f"{colour}{ll}")
                        colour = ttxcolour.magenta()
                    else:
                        rows.append(f"{colour}{ll}")
            if ((len(p) + len(rows) <  maxrows)
                or (len(p) == 0 and len(rows) == maxrows)):
                if len(p)>1:
                    p.append('')
                p.extend(rows)
            else:
                pages.append(p)
                p = [header]
                p.extend(rows)
        if len(fixes) == 0:
            p.append('')
            p.append(f'{ttxcolour.cyan()}No matches today.')
        pages.append(p)

    subpage = 0
    for p in pages:
        if len(pages) > 1:
            subpage += 1
            page.header(pagenum, subpage, status=0xc000)
        else:
            page.header(pagenum, subpage, status=0x8000)
        sport_header(page, 'Cricket')
        if len(pages) > 1:
            index = f"{subpage}/{len(pages)}"
            p[0] = f"{p[0]:<34.34}{ttxcolour.white()}{index:>5}"
        line = 4
        for r in p:
            if len(r):
                page.addline(line, r)
            line += 1
        sport_footer(page, 'Cricket')

    page.save()
    return links