Skip to content

Commit

Permalink
Merge branch 'carlosvargas-upcoming-games'
Browse files Browse the repository at this point in the history
  • Loading branch information
architv committed Mar 28, 2016
2 parents 5eca6d3 + f21bb20 commit 189cd76
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 25 deletions.
32 changes: 18 additions & 14 deletions soccer/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,19 +63,20 @@ def get_live_scores(writer, use_12_hour_format):
click.secho("There was problem getting live scores", fg="red", bold=True)


def get_team_scores(team, time, writer):
def get_team_scores(team, time, writer, show_upcoming, use_12_hour_format):
"""Queries the API and gets the particular team scores"""
team_id = TEAM_NAMES.get(team, None)
time_frame = 'n' if show_upcoming else 'p'
if team_id:
try:
req = _get('teams/{team_id}/fixtures?timeFrame=p{time}'.format(
team_id=team_id, time=time))
req = _get('teams/{team_id}/fixtures?timeFrame={time_frame}{time}'.format(
team_id=team_id, time_frame=time_frame, time=time))
team_scores = req.json()
if len(team_scores["fixtures"]) == 0:
click.secho("No action during past week. Change the time "
"parameter to get more fixtures.", fg="red", bold=True)
else:
writer.team_scores(team_scores, time)
writer.team_scores(team_scores, time, show_upcoming, use_12_hour_format)
except APIErrorException as e:
click.secho(e.args[0],
fg="red", bold=True)
Expand All @@ -98,32 +99,34 @@ def get_standings(league, writer):
fg="red", bold=True)


def get_league_scores(league, time, writer):
def get_league_scores(league, time, writer, show_upcoming, use_12_hour_format):

"""
Queries the API and fetches the scores for fixtures
based upon the league and time parameter
"""
time_frame = 'n' if show_upcoming else 'p'
if league:
try:
league_id = LEAGUE_IDS[league]
req = _get('soccerseasons/{id}/fixtures?timeFrame=p{time}'.format(
id=league_id, time=str(time)))
req = _get('soccerseasons/{id}/fixtures?timeFrame={time_frame}{time}'.format(
id=league_id, time_frame=time_frame, time=str(time)))
fixtures_results = req.json()
# no fixtures in the past week. display a help message and return
if len(fixtures_results["fixtures"]) == 0:
click.secho("No {league} matches in the past week.".format(league=league),
fg="red", bold=True)
return
writer.league_scores(fixtures_results, time)
writer.league_scores(fixtures_results, time, show_upcoming, use_12_hour_format)
except APIErrorException:
click.secho("No data for the given league.", fg="red", bold=True)
else:
# When no league specified. Print all available in time frame.
try:
req = _get('fixtures?timeFrame=p{time}'.format(
time=str(time)))
req = _get('fixtures?timeFrame={time_frame}{time}'.format(
time_frame=time_frame, time=str(time)))
fixtures_results = req.json()
writer.league_scores(fixtures_results, time)
writer.league_scores(fixtures_results, time, show_upcoming, use_12_hour_format)
except APIErrorException:
click.secho("No data available.", fg="red", bold=True)

Expand Down Expand Up @@ -160,6 +163,7 @@ def get_team_players(team, writer):
"See team codes listed in README."))
@click.option('--time', default=6,
help="The number of days in the past for which you want to see the scores")
@click.option('--upcoming', is_flag=True, default=False, help="Displays upcoming games when used with --time command.")
@click.option('--stdout', 'output_format', flag_value='stdout',
default=True, help="Print to stdout")
@click.option('--csv', 'output_format', flag_value='csv',
Expand All @@ -168,7 +172,7 @@ def get_team_players(team, writer):
help='Output in JSON format')
@click.option('-o', '--output-file', default=None,
help="Save output to a file (only if csv or json option is provided)")
def main(league, time, standings, team, live, use12hour, players, output_format, output_file):
def main(league, time, standings, team, live, use12hour, players, output_format, output_file, upcoming):
"""A CLI for live and past football scores from various football leagues"""
try:
if output_format == 'stdout' and output_file:
Expand All @@ -192,10 +196,10 @@ def main(league, time, standings, team, live, use12hour, players, output_format,
get_team_players(team, writer)
return
else:
get_team_scores(team, time, writer)
get_team_scores(team, time, writer, upcoming, use12hour)
return

get_league_scores(league, time, writer)
get_league_scores(league, time, writer, upcoming, use12hour)
except IncorrectParametersException as e:
click.secho(e.message, fg="red", bold=True)

Expand Down
39 changes: 28 additions & 11 deletions soccer/writers.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,21 @@ def live_scores(self, live_scores, use_12_hour_format):
fg=self.colors.TIME)
click.echo()

def team_scores(self, team_scores, time):
def team_scores(self, team_scores, time, show_datetime, use_12_hour_format):
"""Prints the teams scores in a pretty format"""
for score in team_scores["fixtures"]:
if score["status"] == "FINISHED":
click.echo()
click.secho("%s\t" % score["date"].split('T')[0],
fg=self.colors.TIME, nl=False)
self.scores(self.parse_result(score))
elif show_datetime:
click.echo()
self.scores(self.parse_result(score), add_new_line=False)
click.secho(' %s' % Stdout.convert_utc_to_local_time(score["date"],
use_12_hour_format, show_datetime),
fg=self.colors.TIME)


def team_players(self, team):
"""Prints the team players in a pretty format"""
Expand Down Expand Up @@ -172,14 +179,18 @@ def standings(self, league_table, league):
),
fg=self.colors.POSITION)

def league_scores(self, total_data, time):
def league_scores(self, total_data, time, show_datetime, use_12_hour_format):
"""Prints the data in a pretty format"""
seen = set()
for league, data in self.supported_leagues(total_data):
if league not in seen:
seen.add(league)
self.league_header(league)
self.scores(self.parse_result(data))
self.scores(self.parse_result(data), add_new_line=not show_datetime)
if show_datetime:
click.secho(' %s' % Stdout.convert_utc_to_local_time(data["date"],
use_12_hour_format, show_datetime),
fg=self.colors.TIME)
click.echo()

def league_header(self, league):
Expand Down Expand Up @@ -225,24 +236,30 @@ def valid_score(score):
return result

@staticmethod
def convert_utc_to_local_time(time_str, use_12_hour_format):
def convert_utc_to_local_time(time_str, use_12_hour_format, show_datetime=False):
"""Converts the API UTC time string to the local user time."""
if not time_str.endswith(" UTC"):
if not (time_str.endswith(" UTC") or time_str.endswith("Z")):
return time_str

today_utc = datetime.datetime.utcnow()
utc_local_diff = today_utc - datetime.datetime.now()

time_str, _ = time_str.split(" UTC")
utc_time = datetime.datetime.strptime(time_str,'%I:%M %p')
utc_datetime = datetime.datetime(today_utc.year, today_utc.month, today_utc.day,
utc_time.hour, utc_time.minute)
if time_str.endswith(" UTC"):
time_str, _ = time_str.split(" UTC")
utc_time = datetime.datetime.strptime(time_str, '%I:%M %p')
utc_datetime = datetime.datetime(today_utc.year, today_utc.month, today_utc.day,
utc_time.hour, utc_time.minute)
else:
utc_datetime = datetime.datetime.strptime(time_str, '%Y-%m-%dT%H:%M:%SZ')

local_time = utc_datetime - utc_local_diff

if use_12_hour_format:
return datetime.datetime.strftime(local_time,'%I:%M %p')
date_format = '%I:%M %p' if not show_datetime else '%a %d, %I:%M %p'
else:
return datetime.datetime.strftime(local_time,'%H:%M')
date_format = '%H:%M' if not show_datetime else '%a %d, %H:%M'

return datetime.datetime.strftime(local_time, date_format)


class Csv(BaseWriter):
Expand Down

0 comments on commit 189cd76

Please sign in to comment.