Skip to content

Commit

Permalink
Begin work on restructuring addon
Browse files Browse the repository at this point in the history
  • Loading branch information
glennguy committed Dec 2, 2017
1 parent 465e1b7 commit b95c60d
Show file tree
Hide file tree
Showing 6 changed files with 87 additions and 83 deletions.
13 changes: 5 additions & 8 deletions default.py
Expand Up @@ -49,20 +49,17 @@
xbmcaddon.Addon().openSettings()
elif params['category'] == 'Team Video':
teams.make_list()
elif params['category'].startswith('Match Replays'):
# Pull season out from end of category name
season = params['category'].split()[-1]
rounds.make_rounds(season)
elif params['category'] == 'All Match Replays':
index.make_seasons_list()
else:
videos.make_list(params_str)
elif 'season' in params:
rounds.make_rounds(params)
elif 'team' in params:
videos.make_list(params_str)
elif 'match_id' in params:
# List of videos (quarters) for a match
play_replay.make_list(params['round_id'], params['match_id'])
elif 'round_id' in params:
# Match list for a round
matches.make_list(params['round_id'])
matches.make_list(params)
elif 'title' in params:
play.play(params_str)
elif 'action' in params:
Expand Down
77 changes: 30 additions & 47 deletions resources/lib/comm.py
Expand Up @@ -271,57 +271,40 @@ def get_live_videos():
return video_list


def get_round(round_id, live=False):
def get_seasons(season=None):
"""Grab the seasons/round list from the API"""
data = json.loads(fetch_url(config.SEASONS_URL, request_token=True))
seasons = data.get('seasons')
if not season:
utils.log('not season')
return seasons
for s in seasons:
utils.log('Checking Seasons')
if s.get('id') == season:
utils.log(s.get('id'))
return s


def get_round(params, live=False):
"""Fetch the round and return the results"""
round_matches = []
round_url = config.ROUND_URL

# Pass a 'latest' string in round_id to get 'this week'
if round_id != 'latest':
round_url = "%s/%s" % (round_url, round_id)

xml = fetch_url(round_url)
try:
rnd = ET.fromstring(xml)
except ET.ParseError:
utils.log('Could not parse XML. Data is: {0}'.format(xml))
raise Exception('Could not parse XML. Service may be '
'currently unavailable.')

matches = rnd.find('matches').getchildren()

for m in matches:
d = dict(m.items())

if d['homeSquadId']:
match = {}
home_team = get_team(d['homeSquadId'])['name']
away_team = get_team(d['awaySquadId'])['name']
match['name'] = "%s v %s" % (home_team, away_team)
match['id'] = d['FixtureId']
match['round_id'] = dict(rnd.items())['id']

# special formatting for the 'upcoming games' list in the live menu
if live:
now = datetime.datetime.now()
timestamp = d['dateTime']
timezone = d['timezone']
ts = datetime.datetime.fromtimestamp(
time.mktime(time.strptime(timestamp,
"%Y-%m-%dT%H:%M:%S")))
delta = now - ts
# remove games that have already been played
if delta > datetime.timedelta(hours=3):
continue
airTime = ts.strftime(" - %A @ %I:%M %p A")
match['name'] = '[COLOR red]{0}{1}{2}[/COLOR]'.format(
match['name'], airTime, timezone)

# Add date/time
round_matches.append(match)

data = json.loads(fetch_url(config.ROUND_URL.format(params.get('round_id')), request_token=True))
videos = data['categories'][0].get('videos')
for video in videos:
v = classes.Video()
attrs = video.get('customAttributes')
if not attrs:
continue
v.id = get_attr(attrs, 'ooyala embed code')
v.title = video.get('title')
v.thumbnail = video.get('thumbnailPath')
if video.get('entitlement'):
v.subscription_required = True
round_matches.append(v)
return round_matches




def get_match_video(round_id, match_id, quality):
match_video = []
Expand Down
17 changes: 6 additions & 11 deletions resources/lib/config.py
Expand Up @@ -34,12 +34,15 @@

# Round URL, which lists the games of the round if they've had their Videos uploaded
# This URL can also take a 'Round ID' added to the end (e.g CD_R201301401)
ROUND_URL = 'http://www.afl.com.au/api/gas/afl/roundVideo'
ROUND_URL = 'https://api.afl.com.au/cfs/afl/videos/round/{0}?pageSize=20&pageNum=1&categories=Match Replays&includeOnlineVideos=false'

# This URL returns a token if POST'ed to. The token is required in the header to any
# reqeusts against the API
TOKEN_URL = 'http://api.afl.com.au/cfs/afl/WMCTok'

# API URL for all seasons and rounds data
SEASONS_URL = 'https://api.afl.com.au/cfs/afl/seasons'

# API URL for current live videos
LIVE_LIST_URL = 'http://api.afl.com.au/cfs/afl/liveMedia?org=AFL&view=full'

Expand Down Expand Up @@ -137,11 +140,7 @@
'Live Matches',
'Team Video',
'Recent Match Replays',
'Match Replays 2017',
'Match Replays 2016',
'Match Replays 2015',
'Match Replays 2014',
'Match Replays 2013',
'All Match Replays',
'Auto-generated Highlights',
'Editorial Highlights',
'Media Conferences',
Expand All @@ -156,11 +155,7 @@
'Live Matches': 'Live Matches',
'Team Video': 'Team Video',
'Recent Match Replays': 'Match Replays&pageSize=50',
'Match Replays 2017': 'Match Replays 2017',
'Match Replays 2016': 'Match Replays 2016',
'Match Replays 2015': 'Match Replays 2015',
'Match Replays 2014': 'Match Replays 2014',
'Match Replays 2013': 'Match Replays 2013',
'All Match Replays': 'All Match Replays',
'Auto-generated Highlights': 'Auto-generated Highlights&pageSize=50',
'Editorial Highlights': 'Editorial Highlights&pageSize=50',
'Media Conferences': 'Media Conferences&pageSize=50',
Expand Down
26 changes: 26 additions & 0 deletions resources/lib/index.py
Expand Up @@ -16,6 +16,7 @@
# along with this add-on. If not, see <http://www.gnu.org/licenses/>.
#

import comm
import config
import sys
import xbmcgui
Expand All @@ -40,3 +41,28 @@ def make_list():
xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
except Exception:
utils.handle_error('Unable build video category list')


def make_seasons_list():
try:
seasons = comm.get_seasons()
sorted_seasons = sorted(
seasons, key=lambda x: x.get('name'), reverse=True)
for season in sorted_seasons:
id = season.get('id')
current_round = season.get('currentRoundId')
name = season.get('name')
url = "{0}?season={1}&current_round={2}&name={3}".format(
sys.argv[0], id, current_round, name)
listitem = xbmcgui.ListItem(name)

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

xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
except Exception:
utils.handle_error('Unable build seasons list')
15 changes: 7 additions & 8 deletions resources/lib/matches.py
Expand Up @@ -24,19 +24,18 @@
from aussieaddonscommon import utils


def make_list(round_id):
utils.log("Fetching match list for round %s..." % round_id)
def make_list(params):
utils.log("Fetching match list for round %s..." % params['round_id'])
try:
matches = comm.get_round(round_id)
matches = comm.get_round(params)
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'])
listitem = xbmcgui.ListItem(label=m.title)
url = "%s?title=%s&ooyalaid=%s&subscription_required=True" % (sys.argv[0],
m.title,
m.id)

# Add the item to the list
ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
Expand Down
22 changes: 13 additions & 9 deletions resources/lib/rounds.py
Expand Up @@ -16,6 +16,7 @@
# along with this add-on. If not, see <http://www.gnu.org/licenses/>.
#

import comm
import config
import sys
import xbmcgui
Expand All @@ -24,23 +25,26 @@
from aussieaddonscommon import utils


def make_rounds(season=2017):
def make_rounds(params):
try:
# ROUNDS_2017 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'])
season = comm.get_seasons(season=params.get('season'))
rounds = reversed(season.get('rounds'))
for r in rounds:
name = r.get('name')
round_id = r.get('roundId')
season_id = r.get('seasonId')
listitem = xbmcgui.ListItem(label=name)
url = '{0}?name={1}&round_id={2}&season_id={3}'.format(
sys.argv[0], name, round_id, season_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))
totalItems=len(season.get('rounds')))

# send notification we're finished, successfully or unsuccessfully
xbmcplugin.endOfDirectory(handle=int(sys.argv[1]), succeeded=ok)
except Exception:
utils.handle_error('Unable to fetch round list')
utils.handle_error('Unable to make round list')

0 comments on commit b95c60d

Please sign in to comment.