Пример #1
0
def display_division_standings(date_str, args_filter, rank_tag='divisionRank', header_tags=('league', 'division')):
    standings_type = 'byDivision'
    display_title = 'Division'
    if date_str is None:
        season_str = time.strftime("%Y")
        url_date_str = ''
    else:
        season_str = datetime.strftime(datetime.strptime(date_str, "%Y-%m-%d"), "%Y")
        url_date_str = '&date=' + date_str
    url = STANDINGS_URL.format(standings_type=standings_type,
                               league_ids=mlbapidata.get_league_ids(args_filter),
                               season=season_str, date=url_date_str)
    json_data = request.request_json(url, 'standings-{}-{}'.format(season_str, standings_type), cache_stale=request.CACHE_SHORT)

    border = displayutil.Border(use_unicode=config.UNICODE)

    outl = list()
    if display_title != '':
        outl.append(_get_title_header(display_title, border))

    needs_line_hr = False
    if args_filter and args_filter in mlbapidata.DIVISION_FILTERS:
        _get_standings_display_for_record(outl, standings_type,
                                          _get_division_record(json_data['records'], args_filter),
                                          header_tags, rank_tag, border, needs_line_hr)
    else:
        for div in mlbapidata.DIVISION_FILTERS:
            div_record = _get_division_record(json_data['records'], div)
            if div_record:
                _get_standings_display_for_record(outl, standings_type, div_record,
                                                  header_tags, rank_tag, border, needs_line_hr)
    print('\n'.join(outl))
Пример #2
0
    def display_game_data(self, game_date, game_records, filter, show_info):
        show_scores = config.CONFIG.parser.getboolean('scores')
        # might as well show linescore if show_info is given
        show_linescore = show_scores and (config.CONFIG.parser.getboolean('linescore') or config.CONFIG.parser.getboolean('boxscore') or show_info)
        show_boxscore = show_scores and config.CONFIG.parser.getboolean('boxscore')
        border = displayutil.Border(use_unicode=config.UNICODE)
        if game_records is None:
            # outl.append("No game data for {}".format(game_date))
            LOG.info("No game data for {}".format(game_date))
            # LOG.info("No game data to display")
            return

        outl = list()  # holds list of strings for output

        # print header
        header = self._get_header(border, game_date, show_scores, show_linescore)
        outl.extend(header)

        games_displayed_count = 0
        for game_pk in game_records:
            if gamedata.apply_filter(game_records[game_pk], filter, FILTERS) is not None:
                games_displayed_count += 1
                outl.extend(self._display_game_details(header, game_pk, game_records[game_pk],
                                                       show_linescore,
                                                       show_boxscore,
                                                       show_info,
                                                       games_displayed_count))
        if games_displayed_count > 0:
            for line in outl:
                print(line)
Пример #3
0
def _display_standings(standings_type,
                       display_title,
                       date_str,
                       args_filter,
                       rank_tag='divisionRank',
                       header_tags=('league', 'division')):
    if date_str is None:
        season_str = time.strftime("%Y")
        url_date_str = ''
    else:
        season_str = datetime.strftime(datetime.strptime(date_str, "%Y-%m-%d"),
                                       "%Y")
        url_date_str = '&date=' + date_str
    url = STANDINGS_URL.format(standings_type=standings_type,
                               league_ids=_get_league_ids(args_filter),
                               season=season_str,
                               date=url_date_str)
    json_data = util.request_json(url, 'standings')

    border = displayutil.Border(use_unicode=config.UNICODE)

    outl = list()
    if display_title != '':
        outl.append(_get_title_header(display_title, border))

    needs_line_hr = False
    for record in json_data['records']:
        if args_filter and standings_type == 'byDivision' and args_filter in DIVISION_FILTERS:
            pass

        _get_standings_display_for_record(outl, standings_type, record,
                                          header_tags, rank_tag, border,
                                          needs_line_hr)

    print('\n'.join(outl))
Пример #4
0
    def _display_game_details(self, header, game_pk, game_rec, show_linescore, show_boxscore, show_info, games_displayed_count):
        show_scores = config.CONFIG.parser.getboolean('scores')
        outl = list()
        if games_displayed_count > 1:
            if show_info or show_linescore or show_boxscore:
                outl.append('')
            if show_info:
                outl.extend(header)
        border = displayutil.Border(use_unicode=config.UNICODE)
        color_on = ''
        color_off = ''
        # odd_even = games_displayed_count % 2
        # if odd_even:
        #     color_on = ANSI.fg('yellow')
        # else:
        #     color_on = display'reset'.ANSI.fg('lightblue')
        color_off = ANSI.reset()
        if gamedata.is_fav(game_rec):
            if config.CONFIG.parser['fav_colour'] != '':
                color_on = ANSI.fg(config.CONFIG.parser['fav_colour'])
                color_off = ANSI.reset()
        if game_rec['abstractGameState'] == 'Live':
            color_on += ANSI.control_code('bold')
            color_off = ANSI.reset()
        if game_rec['doubleHeader'] == 'N':
            series_info = "{sgn}/{gis}".format(sgn=game_rec['seriesGameNumber'], gis=game_rec['gamesInSeries'])
        else:
            # series_info = "DH{gn} {sgn}/{gis}".format(sgn=game_rec['seriesGameNumber'],
            #                                           gis=game_rec['gamesInSeries'],
            #                                           gn=game_rec['gameNumber'])
            series_info = "DH-{gn}".format(gn=game_rec['gameNumber'])
        game_info_str = "{time}: {a1} ({a2}) at {h1} ({h2})"\
            .format(time=util.convert_time_to_local(game_rec['mlbdate']),
                    a1=game_rec['away']['display'], a2=game_rec['away']['abbrev'].upper(),
                    h1=game_rec['home']['display'], h2=game_rec['home']['abbrev'].upper())
        game_state = ''
        game_state_color_on = color_on
        game_state_color_off = color_off

        if game_rec['abstractGameState'] in ('Preview', ):
            if game_rec['detailedState'] != 'Scheduled':
                if 'Delayed' in game_rec['detailedState']:
                    game_state = 'Delayed'
                else:
                    game_state = game_rec['detailedState']
        else:
            if show_scores:
                if game_rec['detailedState'] in ('Critical', ):
                    game_state_color_on = ANSI.fg(config.CONFIG.parser['game_critical_colour'])
                    game_state_color_off = ANSI.reset()
                if game_rec['detailedState'] in ('Final', ):
                    game_state = game_rec['detailedState']
                    if 'currentInning' in game_rec['linescore'] and int(game_rec['linescore']['currentInning']) != 9:
                        game_state += '({})'.format(game_rec['linescore']['currentInning'])
                else:
                    if game_rec['linescore']['inningState'] != '':
                        game_state = '{} {}'.format(game_rec['linescore']['inningState'].title(),
                                                    game_rec['linescore']['currentInningOrdinal'])
                    else:
                        game_state = game_rec['linescore']['currentInningOrdinal']
            else:
                game_state = game_rec['abstractGameState']
                if 'In Progress - ' in game_rec['detailedState']:
                    game_state = game_rec['detailedState'].split('In Progress - ')[-1]
                elif game_rec['detailedState'] not in ('Live', 'Final', 'Scheduled', 'In Progress'):
                    game_state = game_rec['detailedState']

        if show_scores:
            score = ''
            if game_rec['abstractGameState'] not in ('Preview', ) and game_rec['detailedState'] not in ('Postponed', ):
                score = '{}-{}'.format(game_rec['linescore']['away']['runs'], game_rec['linescore']['home']['runs'])

            # linescore
            if show_linescore:
                if games_displayed_count > 1 and not show_info:
                    outl.append('{coloron}{dash}{coloroff}'.format(coloron=ANSI.fg('darkgrey'),
                                                                   dash=border.dash*92,
                                                                   coloroff=ANSI.reset()))
                linescore_dict = self._format_linescore(game_rec)
                """
                18:05: LA Dodgers (LAD) at San Francisco (SF)            1  2  3  4  5  6  7  8  9 10 11 12 13 14  R  H  E
                1/2    Final(14): 5-7                              LAD   0  0  1  0  0  2  1  0  0  0  0  0  0  1  5 12  0
                       Feeds: a,h / cnd,rcp                        SF    1  0  0  2  0  1  0  0  0  0  0  0  0  3  7 17  1
                """
                line_fmt = "{coloron}{ginfo:<50} {lscore}{coloroff}"
                # if game_rec['abstractGameState'] not in ('Live', 'Final'):  # or game_rec['detailedState'] in ('Postponed', ):
                #     outl.append(line_fmt.format(coloron=color_on, coloroff=color_off, ginfo=game_info_str, lscore=''))
                #     return outl

                outl.append(line_fmt.format(coloron=color_on, coloroff=color_off,
                                            ginfo=game_info_str, lscore=linescore_dict['header'], pipe=border.pipe))
                if game_state == '':
                    # game_info_str = '{series:7}Not Started'.format(series=series_info)
                    game_info_str = '{series:7}'.format(series=series_info)
                else:
                    if game_rec['abstractGameState'] in ('Live',) \
                            and game_rec['linescore']['inningState'] != 'Mid' and 'raw' in game_rec['linescore']:
                        outs_info = ', {} out'.format(game_rec['linescore']['raw']['outs'])
                    else:
                        outs_info = ''
                    if score:
                        game_info_str = '{series:7}{gstate}: {score}{outs}'.format(series=series_info,
                                                                                   gstate=game_state, score=score, outs=outs_info)
                    else:
                        game_info_str = '{series:7}{gstate}'.format(series=series_info, gstate=game_state)
                outl.append(line_fmt.format(coloron=color_on, coloroff=color_off,
                                            ginfo=game_info_str, lscore=linescore_dict['away']))

                feeds = self.__get_feeds_for_display(game_rec)
                if feeds:
                    game_info_str = '{:7}Feeds: {feeds}'.format('', feeds=self.__get_feeds_for_display(game_rec))
                    outl.append(line_fmt.format(coloron=color_on, coloroff=color_off,
                                                ginfo=game_info_str, lscore=linescore_dict['home']))
                else:
                    outl.append(line_fmt.format(coloron=color_on, coloroff=color_off,
                                                ginfo='', lscore=linescore_dict['home']))
            else:
                # single-line game score
                outl.append(("{coloron}{ginfo:<48} {series:^7}{coloroff} "
                             "{pipe} {coloron}{score:^5}{coloroff} {pipe} "
                             "{gscoloron}{gstate:<9}{gscoloroff} {pipe} {coloron}{feeds}{coloroff}")
                            .format(coloron=color_on, coloroff=color_off,
                                    ginfo=game_info_str, series=series_info, score=score,
                                    gscoloron=game_state_color_on, gstate=game_state, gscoloroff=game_state_color_off,
                                    feeds=self.__get_feeds_for_display(game_rec), pipe=border.pipe))
        else:  # no scores
            outl.append(("{coloron}{ginfo:<48} {series:^7}{coloroff} {pipe} "
                         "{coloron}{gstate:^9}{coloroff} {pipe} {coloron}{feeds}{coloroff}")
                        .format(coloron=color_on, coloroff=color_off,
                                ginfo=game_info_str, series=series_info, gstate=game_state,
                                feeds=self.__get_feeds_for_display(game_rec), pipe=border.pipe))

        if show_info:
            # found_info = False
            for text_type in ('summary', 'preview'):
                if text_type in game_rec and game_rec[text_type]:
                    # if text_type == 'summary':
                    #     outl.append('')
                    outl.append('')
                    for line in game_rec[text_type]:
                        outl.append('{coloron}{text}{coloroff}'.format(coloron=color_on,
                                                                       text=util.strip_html_tags(line, True),
                                                                       coloroff=color_off))
                    # outl.append('')
                    # only show one of summary or preview
                    break

        if show_boxscore:
            outl.extend(self._get_formatted_boxscore(game_rec, color_on, color_off))

        return outl