Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/tonycpsu/mlbstreamer
Browse files Browse the repository at this point in the history
  • Loading branch information
mkomko committed May 22, 2018
2 parents 36d86e4 + b7263be commit 559d73a
Show file tree
Hide file tree
Showing 8 changed files with 356 additions and 108 deletions.
2 changes: 1 addition & 1 deletion .bumpversion.cfg
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
[bumpversion]
commit = True
tag = True
current_version = 0.0.9.dev0
current_version = 0.0.11.dev0
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(\.(?P<release>[a-z]+)(?P<dev>\d+))?
serialize =
{major}.{minor}.{patch}.{release}{dev}
Expand Down
2 changes: 1 addition & 1 deletion mlbstreamer/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
__version__ = "0.0.9.dev0"
__version__ = "0.0.11.dev0"
226 changes: 191 additions & 35 deletions mlbstreamer/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from panwid.datatable import *
from panwid.listbox import ScrollingListBox
from panwid.dropdown import *
from panwid.dialog import *

import pytz
from orderedattrdict import AttrDict
Expand All @@ -28,6 +29,7 @@
from . import config
from . import play
from . import widgets
from .util import *
from .session import *


Expand Down Expand Up @@ -153,8 +155,6 @@ def keypress(self, size, key):

class GamesDataTable(DataTable):

signals = ["watch"]

columns = [
DataTableColumn("start", width=6, align="right"),
# DataTableColumn("game_type", label="type", width=5, align="right"),
Expand Down Expand Up @@ -231,6 +231,11 @@ def query(self, *args, **kwargs):
line = self.line_score
)

class ResolutionDropdown(Dropdown):

items = MLB_HLS_RESOLUTION_MAP

label = "Resolution"

class Toolbar(urwid.WidgetWrap):

Expand All @@ -239,25 +244,16 @@ def __init__(self):
self.league_dropdown = Dropdown(AttrDict([
("MLB", 1),
("AAA", 11),
]) , label="League: ")
]) , label="League")

self.live_stream_dropdown = Dropdown([
"live",
"from start"
], label="Live streams: ")

self.resolution_dropdown = Dropdown(
AttrDict([
("720p (60fps)", "720p_alt"),
("720p", "720p"),
("540p", "540p"),
("504p", "504p"),
("360p", "360p"),
("288p", "288p"),
("224p", "224p")
]), label="resolution",
default=options.resolution)
], label="Live streams")

self.resolution_dropdown = ResolutionDropdown(
default=options.resolution
)
self.columns = urwid.Columns([
('weight', 1, self.league_dropdown),
('weight', 1, self.live_stream_dropdown),
Expand All @@ -279,6 +275,7 @@ def resolution(self):
def start_from_beginning(self):
return self.live_stream_dropdown.selected_label == "from start"


class DateBar(urwid.WidgetWrap):

def __init__(self, game_date):
Expand All @@ -289,17 +286,143 @@ def __init__(self, game_date):
def set_date(self, game_date):
self.text.set_text(game_date.strftime("%A, %Y-%m-%d"))

class ScheduleView(urwid.WidgetWrap):

def __init__(self):
class WatchDialog(BasePopUp):

signals = ["watch"]

def __init__(self, game_id,
resolution=None, from_beginning=None):

self.game_id = game_id
self.resolution = resolution
self.from_beginning = from_beginning

self.game_data = state.session.schedule(
game_id=self.game_id,
)["dates"][0]["games"][0]
# raise Exception(self.game_data)

self.title = urwid.Text("%s@%s" %(
self.game_data["teams"]["away"]["team"]["abbreviation"],
self.game_data["teams"]["home"]["team"]["abbreviation"],
))

feed_map = sorted([
("%s (%s)" %(e["mediaFeedType"].title(),
e["callLetters"]), e["mediaId"].lower())
for e in state.session.get_media(self.game_id)
], key=lambda v: v[0])
home_feed = next(state.session.get_media(
self.game_id,
preferred_stream = "home"
))
self.live_stream = (home_feed.get("mediaState") == "MEDIA_ON")
self.feed_dropdown = Dropdown(
feed_map,
label="Feed",
default=home_feed["mediaId"]
)
urwid.connect_signal(
self.feed_dropdown,
"change",
lambda s, b, media_id: self.update_inning_dropdown(media_id)
)

self.resolution_dropdown = ResolutionDropdown(
default=resolution
)

self.inning_dropdown_placeholder = urwid.WidgetPlaceholder(urwid.Text(""))
self.update_inning_dropdown(self.feed_dropdown.selected_value)

self.ok_button = urwid.Button("OK")
urwid.connect_signal(self.ok_button, "click", self.watch)

self.cancel_button = urwid.Button("Cancel")
urwid.connect_signal(
self.cancel_button, "click",
lambda b: urwid.signals.emit_signal(self, "close_popup")
)

pile = urwid.Pile([
("pack", self.title),
("weight", 1, urwid.Pile([
("weight", 1, urwid.Filler(
urwid.Columns([
("weight", 1, self.feed_dropdown),
("weight", 1, self.resolution_dropdown),
]))),
("weight", 1, urwid.Filler(self.inning_dropdown_placeholder)),
("weight", 1, urwid.Filler(
urwid.Columns([
("weight", 1, self.ok_button),
("weight", 1, self.cancel_button),
])))
]))
])
super(WatchDialog, self).__init__(pile)

def update_inning_dropdown(self, media_id):
# raise Exception(media_id)
self.timestamps = state.session.media_timestamps(
self.game_id, media_id
)
del self.timestamps["S"]
timestamp_map = AttrDict(
( k if k[0] in "TB" else "Start", k ) for k in self.timestamps.keys()
)
timestamp_map["Live"] = False
self.inning_dropdown = Dropdown(
timestamp_map, label="Begin playback",
default = (
timestamp_map["Start"] if (
not self.live_stream or self.from_beginning
) else timestamp_map["Live"]
)
)
self.inning_dropdown_placeholder.original_widget = self.inning_dropdown


def watch(self, source):
urwid.signals.emit_signal(
self,
"watch",
self.game_id,
self.resolution_dropdown.selected_value,
self.feed_dropdown.selected_value,
self.inning_dropdown.selected_value
)
urwid.signals.emit_signal(self, "close_popup")

def keypress(self, size, key):

if key == "meta enter":
self.ok_button.keypress(size, "enter")
elif key in ["<", ">"]:
self.resolution_dropdown.cycle(1 if key == "<" else -1)
elif key in ["[", "]"]:
self.feed_dropdown.cycle(-1 if key == "[" else 1)
elif key in ["-", "="]:
self.inning_dropdown.cycle(-1 if key == "-" else 1)
else:
# return super(WatchDialog, self).keypress(size, key)
key = super(WatchDialog, self).keypress(size, key)
if key:
return
return key


class ScheduleView(BaseView):

def __init__(self, date):

today = datetime.now().date()
self.game_date = today
self.game_date = date
self.toolbar = Toolbar()
self.datebar = DateBar(self.game_date)
self.table = GamesDataTable(self.toolbar.sport_id, self.game_date) # preseason
urwid.connect_signal(self.table, "watch",
lambda dsource, game_id: self.watch(game_id))
urwid.connect_signal(self.table, "select",
lambda source, selection: self.open_watch_dialog(selection["game_id"]))
self.pile = urwid.Pile([
(1, self.toolbar),
(1, self.datebar),
Expand All @@ -308,47 +431,81 @@ def __init__(self):
self.pile.focus_position = 2
super(ScheduleView, self).__init__(self.pile)

def open_watch_dialog(self, game_id):
dialog = WatchDialog(game_id,
resolution = self.toolbar.resolution,
from_beginning = self.toolbar.start_from_beginning
)
urwid.connect_signal(
dialog,
"watch",
self.watch
)
self.open_popup(dialog, width=30, height=20)

def keypress(self, size, key):

key = super(ScheduleView, self).keypress(size, key)
if key in ["left", "right"]:
self.game_date += timedelta(days= -1 if key == "left" else 1)
self.datebar.set_date(self.game_date)
self.table.set_game_date(self.game_date)
elif key in ["<", ">"]:
self.toolbar.resolution_dropdown.cycle(1 if key == "<" else -1)
elif key in ["-", "="]:
self.toolbar.live_stream_dropdown.cycle(1 if key == "-" else -1)
elif key == "t":
self.game_date = datetime.now().date()
self.datebar.set_date(self.game_date)
self.table.set_game_date(self.game_date)
elif key == "w":
# self._emit("watch", self.table.selection.data.game_id)
self.watch(self.table.selection.data.game_id)
elif key == "w": # watch home stream
self.watch(
self.table.selection.data.game_id,
preferred_stream="home",
resolution=self.toolbar.resolution
)
elif key == "W": # watch away stream
self.watch(
self.table.selection.data.game_id,
preferred_stream="away",
resolution=self.toolbar.resolution
)
else:
return key

def watch(self, game_id,
resolution=None, feed=None,
offset=None, preferred_stream=None):

def watch(self, game_id):
logger.info("playing game %d at %s" %(game_id, self.toolbar.resolution))
try:
state.proc = play.play_stream(
game_id,
self.toolbar.resolution,
offset = (0
if self.toolbar.start_from_beginning
else None),
resolution,
call_letters = feed,
preferred_stream = preferred_stream,
offset = offset
)
except play.MLBPlayException as e:
logger.error(e)



def main():

global options
global logger

today = datetime.now(pytz.timezone('US/Eastern')).date()

config.settings.load()

parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbose", action="store_true")
parser.add_argument("-d", "--date", help="game date",
type=valid_date,
default=today)
parser.add_argument("-r", "--resolution", help="stream resolution",
default="720p")
default=config.settings.default_resolution)
parser.add_argument("-v", "--verbose", action="store_true")
options, args = parser.parse_known_args()

log_file = os.path.join(config.CONFIG_DIR, "mlbstreamer.log")
Expand All @@ -372,7 +529,6 @@ def main():
logger.addHandler(ulh)

logger.debug("mlbstreamer starting")
config.settings.load()

state.session = MLBSession.new()

Expand All @@ -384,7 +540,7 @@ def main():
screen = urwid.raw_display.Screen()
screen.set_terminal_properties(256)

view = ScheduleView()
view = ScheduleView(options.date)

log_console = widgets.ConsoleWindow()
# log_box = urwid.BoxAdapter(urwid.LineBox(log_console), 10)
Expand Down
18 changes: 17 additions & 1 deletion mlbstreamer/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from prompt_toolkit.shortcuts import confirm
from prompt_toolkit.shortcuts import prompt
import getpass
from .util import *

CONFIG_DIR=os.path.expanduser("~/.config/mlbstreamer")
CONFIG_FILE=os.path.join(CONFIG_DIR, "config.yaml")
Expand Down Expand Up @@ -103,7 +104,7 @@ def find_players():

while True:
self.username = prompt(
"MLB.tv username: ",
"MLB.com username: ",
validator=NotEmptyValidator())
self.password = prompt(
'Enter password: ',
Expand Down Expand Up @@ -151,6 +152,21 @@ def find_players():

self.player = player

print()
print("\n".join(
[ "\t%d: %s" %(n, l)
for n, l in enumerate(
MLB_HLS_RESOLUTION_MAP
)]))
choice = int(
prompt(
"Select a default video resolution for MLB.tv streams",
validator=RangeNumberValidator(maximum=len(MLB_HLS_RESOLUTION_MAP))))
if choice:
self.default_resolution = MLB_HLS_RESOLUTION_MAP[
list(MLB_HLS_RESOLUTION_MAP.keys())[choice]
]

print("Your system time zone seems to be %s." %(tz_local))
if not confirm("Is that the time zone you'd like to use? (y/n) "):
while not time_zone:
Expand Down
Loading

0 comments on commit 559d73a

Please sign in to comment.