-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmlbviewer.py
executable file
·1409 lines (1327 loc) · 56.7 KB
/
mlbviewer.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# coding=UTF-8
import curses
import curses.textpad
import datetime
import time
import calendar
import re
import select
import errno
import signal
import sys
from MLBviewer import *
# used for ignoring sigwinch signal
def donothing(sig, frame):
pass
def doinstall(config,dct,dir=None):
print "Creating configuration files"
if dir:
try:
os.mkdir(dir)
except:
print 'Could not create directory: ' + dir + '\n'
print 'See README for configuration instructions\n'
sys.exit()
# now write the config file
try:
fp = open(config,'w')
except:
print 'Could not write config file: ' + config
print 'Please check directory permissions.'
sys.exit()
fp.write('# See README for explanation of these settings.\n')
fp.write('# user and pass are required except for Top Plays\n')
fp.write('user=\n')
fp.write('pass=\n\n')
for k in dct.keys():
if type(dct[k]) == type(list()):
if len(dct[k]) > 0:
for item in dct[k]:
fp.write(k + '=' + str(dct[k]) + '\n')
fp.write('\n')
else:
fp.write(k + '=' + '\n\n')
else:
fp.write(k + '=' + str(dct[k]) + '\n\n')
fp.close()
print
print 'Configuration complete! You are now ready to use mlbviewer.'
print
print 'Configuration file written to: '
print
print config
print
print 'Please review the settings. You will need to set user and pass.'
sys.exit()
def prompter(win,prompt):
win.clear()
win.addstr(0,0,prompt,curses.A_BOLD)
win.refresh()
responsewin = win.derwin(0, len(prompt))
responsebox = curses.textpad.Textbox(responsewin)
responsebox.edit()
output = responsebox.gather()
return output
def timeShiftOverride(time_shift=None,reverse=False):
try:
plus_minus=re.search('[+-]',time_shift).group()
(hrs,min)=time_shift[1:].split(':')
offset=datetime.timedelta(hours=int(plus_minus + hrs), minutes=int(min))
offset=(offset,offset*-1)[reverse]
except:
offset=datetime.timedelta(0,0)
return offset
def mainloop(myscr,mycfg,mykeys):
# some initialization
log = open(LOGFILE, "a")
DISABLED_FEATURES = []
RESTORE_SPEED = mycfg.get('speed')
# not sure if we need this for remote displays but couldn't hurt
if mycfg.get('x_display'):
os.environ['DISPLAY'] = mycfg.get('x_display')
try:
curses.curs_set(0)
except curses.error:
pass
# mouse events
if mycfg.get('enable_mouse'):
curses.mousemask(1)
# initialize the color settings
if hasattr(curses, 'use_default_colors'):
try:
curses.use_default_colors()
if mycfg.get('use_color'):
try:
if mycfg.get('fg_color'):
mycfg.set('favorite_color', mycfg.get('fg_color'))
if mycfg.get('free_color') is None:
mycfg.set('free_color', COLORS['green'])
curses.init_pair(COLOR_FAVORITE,
COLORS[mycfg.get('favorite_color')],
COLORS[mycfg.get('bg_color')])
curses.init_pair(COLOR_FREE,
COLORS[mycfg.get('free_color')],
COLORS[mycfg.get('bg_color')])
curses.init_pair(COLOR_DIVISION,
COLORS[mycfg.get('division_color')],
COLORS[mycfg.get('bg_color')])
except KeyError:
mycfg.set('use_color', False)
curses.init_pair(1, -1, -1)
except curses.error:
pass
# initialize the input
inputlst = [sys.stdin]
available = []
listwin = MLBListWin(myscr,mycfg,available)
if SPEEDTOGGLE.get(RESTORE_SPEED) is None:
listwin.statusWrite("Invalid speed. Switching to 1200...",wait=2)
mycfg.set('speed','1200')
topwin = MLBTopWin(myscr,mycfg,available)
optwin = MLBOptWin(myscr,mycfg)
helpwin = MLBHelpWin(myscr,mykeys)
rsswin = MLBRssWin(myscr,mycfg)
postwin = None
sbwin = None
linewin = None
boxwin = None
stdwin = None
calwin = None
statwin = None
detailwin = None
stats = MLBStats(mycfg)
# initialize some variables to re-use for 304 caching
boxscore = None
linescore = None
standings = None
# if gameday_audio=True, remap AUDIO to Enter
if mycfg.get('gameday_audio'):
mykeys.set('AUDIO',10)
# now it's go time!
mywin = listwin
mywin.Splash()
mywin.statusWrite('Logging into mlb.com...',wait=0)
session = MLBSession(user=mycfg.get('user'),passwd=mycfg.get('pass'),
debug=mycfg.get('debug'))
try:
session.getSessionData()
except MLBAuthError:
error_str = 'Login was unsuccessful. Check user and pass in ' + myconf
mywin.statusWrite(error_str,wait=2)
except Exception,detail:
error_str = str(detail)
mywin.statusWrite(error_str,wait=2)
mycfg.set('cookies', {})
mycfg.set('cookies', session.cookies)
mycfg.set('cookie_jar' , session.cookie_jar)
try:
log.write('session-key from cookie file: '+session.cookies['ftmu'] +\
'\n')
except:
log.write('no session-key found in cookie file\n')
# Listings
mlbsched = MLBSchedule(ymd_tuple=startdate,
time_shift=mycfg.get('time_offset'),
use_wired_web=mycfg.get('use_wired_web'),
cfg=mycfg,
international=mycfg.get('international'))
milbsched = MiLBSchedule(ymd_tuple=startdate,
time_shift=mycfg.get('time_offset'))
# default to MLB.TV
mysched = mlbsched
# We'll make a note of the date, to return to it later.
today_year = mlbsched.year
today_month = mlbsched.month
today_day = mlbsched.day
try:
available = mysched.getListings(mycfg.get('speed'),
mycfg.get('blackout'))
except (KeyError, MLBXmlError,MLBUrlError), detail:
if mycfg.get('debug'):
#raise Exception, detail
raise
else:
listwin.statusWrite(mysched.error_str,wait=2)
available = []
mywin.data = available
mywin.records = available[0:curses.LINES-4]
mywin.titleRefresh(mysched)
# If favorite is not none, focus the cursor on favorite team
if mycfg.get('favorite') is not None:
try:
favorite=mycfg.get('favorite')
for f in favorite:
for follow in ( 'audio_follow', 'video_follow' ):
if f not in mycfg.get(follow) and not mycfg.get('disable_favorite_follow'):
mycfg.set(follow, f)
mywin.focusFavorite()
except IndexError:
raise Exception,repr(mywin.records)
# PLACEHOLDER - LircConnection() goes here
while True:
myscr.clear()
try:
mywin.Refresh()
except MLBCursesError,detail:
mywin.titleRefresh(mysched)
mywin.statusWrite("ERROR: %s"%detail,wait=2)
except IndexError:
raise Exception,"current_cursor=%s, record_cursor=%s, cl-4=%s, lr=%s,ld=%s" %\
(mywin.current_cursor,mywin.record_cursor,curses.LINES-4,len(mywin.records),len(mywin.data) )
mywin.titleRefresh(mysched)
#pass prefer to statusRefresh but first work it out
#mywin.statusRefresh()
if mywin in ( listwin, sbwin, detailwin ):
try:
prefer = mysched.getPreferred(
listwin.records[listwin.current_cursor], mycfg)
except IndexError:
# this can fail if mlbsched.getSchedule() fails
# that failure already prints out an error, so skip this
pass
elif mywin == postwin:
try:
prefer['video'] = mywin.records[mywin.current_cursor][2]
except:
prefer['video'] = None
if mywin in ( detailwin, ):
mywin.statusRefresh(prefer=prefer)
else:
mywin.statusRefresh()
# And now we do input.
try:
inputs, outputs, excepts = select.select(inputlst, [], [])
except select.error, e:
if e[0] != errno.EINTR:
raise
else:
signal.signal(signal.SIGWINCH, signal.SIG_IGN)
wiggle_timer = float(mycfg.get('wiggle_timer'))
time.sleep(wiggle_timer)
( y , x ) = mywin.getsize()
signal.signal(signal.SIGWINCH, donothing)
curses.resizeterm(y, x)
mywin.resize()
listwin.resize()
if mywin in ( sbwin, detailwin ):
# align the cursors between scoreboard and listings
mywin.setCursors(listwin.record_cursor,
listwin.current_cursor)
continue
if sys.stdin in inputs:
c = myscr.getch()
# MOUSE HANDLING
# Right now, only clicking on a listwin listing will act like a
# VIDEO keypress.
# TODO:
# Check x,y values to see handle some of the toggles.
# Might even overload the "Help" region of interface to allow a
# mouse-friendly overlay.
# Use a cfg setting to disable mouse support altogether so users
# clicking on the window to raise it won't get unexpected results.
if c == curses.KEY_MOUSE:
if mywin != listwin:
continue
id, mousex, mousey, mousez, bstate = curses.getmouse()
#mywin.statusWrite("bstate=%s, mx = %s, my = %s, cc=%s, lr=%s"%(bstate,mousex,mousey,listwin.current_cursor,len(listwin.records)),wait=2)
mousecursor = mousey - 2
if mousey < 2:
continue
if mousecursor < len(listwin.records):
try:
prefer = mysched.getPreferred(listwin.records[mousey-2],
mycfg)
except IndexError:
continue
else:
listwin.current_cursor = mousecursor
# If mouse clicked on a valid listing, push the event
# back to getch() as a VIDEO keypress.
curses.ungetch(mykeys.get('VIDEO')[0])
c = myscr.getch()
else:
continue
# NAVIGATION
if c in mykeys.get('UP'):
if mywin in ( sbwin , detailwin ):
listwin.Up()
mywin.Up()
if c in mykeys.get('DOWN'):
if mywin in ( sbwin , detailwin ):
listwin.Down()
mywin.Down()
# TODO: haven't changed this binding but probably won't
if c in ('Page Down', curses.KEY_NPAGE):
mywin.PgDown()
# TODO: haven't changed this binding but probably won't
if c in ('Page Up', curses.KEY_PPAGE):
mywin.PgUp()
if c in mykeys.get('JUMP'):
if mywin not in ( listwin, sbwin, calwin, detailwin ):
continue
jump_prompt = 'Date (m/d/yy)? '
if datetime.datetime(mysched.year,mysched.month,mysched.day) <> \
datetime.datetime(today_year,today_month,today_day):
jump_prompt += '(<enter> returns to today) '
query = listwin.prompter(listwin.statuswin, jump_prompt)
# Special case. If the response is blank, we jump back to
# today.
if query == '':
listwin.statusWrite('Jumping back to today',wait=1)
listwin.statusWrite('Refreshing listings...',wait=1)
# Really jump to today and not mlbsched date
now = datetime.datetime.now()
dif = datetime.timedelta(1)
if now.hour < 9:
now = now - dif
ymd_tuple = (now.year, now.month, now.day)
try:
available = mysched.Jump(ymd_tuple,
mycfg.get('speed'),
mycfg.get('blackout'))
listwin.data = available
listwin.records = available[0:curses.LINES-4]
listwin.record_cursor = 0
listwin.current_cursor = 0
listwin.focusFavorite()
except (KeyError,MLBXmlError),detail:
if mycfg.get('debug'):
raise Exception,detail
available = []
listwin.data = []
listwin.records = []
listwin.current_cursor = 0
if mywin != calwin:
listwin.statusWrite("There was a parser problem with the listings page",wait=2)
mywin = listwin
continue
# recreate calendar if current screen
if mywin == calwin:
calwin.Jump(ymd_tuple)
continue
# recreate master scoreboard if current screen
elif mywin in ( sbwin, ):
GAMEID = listwin.records[listwin.current_cursor][6]
if sbwin in ( None, [] ):
sbwin = MLBMasterScoreboardWin(myscr,mycfg,GAMEID)
try:
sbwin.getScoreboardData(GAMEID)
except MLBUrlError:
sbwin.statusWrite(self.error_str,wait=2)
continue
# align the cursors between scoreboard and listings
sbwin.setCursors(listwin.record_cursor,
listwin.current_cursor)
mywin = sbwin
elif mywin == detailwin:
game=listwin.records[listwin.current_cursor]
gameid=game[6]
detail = MLBMediaDetail(mycfg,listwin.data)
games = detail.parseListings()
detailwin = MLBMediaDetailWin(myscr,mycfg,gameid,games)
detailwin.getMediaDetail(gameid)
mywin = detailwin
mywin.setCursors(listwin.record_cursor,
listwin.current_cursor)
continue
try:
# Try 4-digit year first
jumpstruct=time.strptime(query.strip(),'%m/%d/%Y')
except ValueError:
try:
# backwards compatibility 2-digit year?
jumpstruct=time.strptime(query.strip(),'%m/%d/%y')
except ValueError:
listwin.statusWrite("Date not in correct format",wait=2)
continue
listwin.statusWrite('Refreshing listings...')
mymonth = jumpstruct.tm_mon
myday = jumpstruct.tm_mday
myyear = jumpstruct.tm_year
try:
available = mysched.Jump((myyear, mymonth, myday),
mycfg.get('speed'),
mycfg.get('blackout'))
listwin.data = available
listwin.records = available[0:curses.LINES-4]
listwin.record_cursor = 0
listwin.current_cursor = 0
listwin.focusFavorite()
except (KeyError,MLBXmlError,MLBUrlError),detail:
if mycfg.get('debug'):
raise Exception,detail
available = []
listwin.statusWrite("There was a parser problem with the listings page",wait=2)
listwin.data = []
listwin.records = []
listwin.current_cursor = 0
# recreate calendar if current screen
if mywin == calwin:
calwin.Jump((myyear,mymonth,myday))
continue
# recreate master scoreboard if current screen
elif mywin in ( sbwin, ):
GAMEID = listwin.records[listwin.current_cursor][6]
if sbwin in ( None, [] ):
sbwin = MLBMasterScoreboardWin(myscr,mycfg,GAMEID)
try:
sbwin.getScoreboardData(GAMEID)
except MLBUrlError:
sbwin.statusWrite(self.error_str,wait=2)
continue
sbwin.setCursors(listwin.record_cursor,
listwin.current_cursor)
mywin = sbwin
elif mywin == detailwin:
game=listwin.records[listwin.current_cursor]
gameid=game[6]
detail = MLBMediaDetail(mycfg,listwin.data)
games = detail.parseListings()
detailwin = MLBMediaDetailWin(myscr,mycfg,gameid,games)
detailwin.getMediaDetail(gameid)
mywin = detailwin
mywin.setCursors(listwin.record_cursor,
listwin.current_cursor)
if c in mykeys.get('LEFT') or c in mykeys.get('RIGHT'):
if mywin not in ( listwin, sbwin, linewin, calwin, detailwin ):
continue
if mywin in ( listwin, sbwin, calwin, detailwin ):
listwin.statusWrite('Refreshing listings...')
# handle linescore separately - this is for scrolling through
# extra innings - calendar navigation is also different
if mywin in ( linewin, calwin ):
if c in mykeys.get('LEFT'):
mywin.Left()
else:
mywin.Right()
continue
try:
if c in mykeys.get('LEFT'):
available = mysched.Back(mycfg.get('speed'),
mycfg.get('blackout'))
else:
available = mysched.Forward(mycfg.get('speed'),
mycfg.get('blackout'))
except (KeyError, MLBXmlError, MLBUrlError), detail:
if mycfg.get('debug'):
raise Exception,detail
available = []
status_str = "There was a parser problem with the listings page"
mywin.statusWrite(status_str,wait=2)
listwin.data = available
listwin.records = available[0:curses.LINES-4]
listwin.current_cursor = 0
listwin.record_cursor = 0
listwin.focusFavorite()
# recreate the master scoreboard view if current screen
if mywin in ( sbwin, ):
try:
GAMEID = listwin.records[listwin.current_cursor][6]
except IndexError:
sbwin.sb = []
continue
if sbwin in ( None, [] ):
sbwin = MLBMasterScoreboardWin(myscr,mycfg,GAMEID)
try:
sbwin.getScoreboardData(GAMEID)
except MLBUrlError:
sbwin.statusWrite(self.error_str,wait=2)
continue
sbwin.setCursors(listwin.record_cursor,
listwin.current_cursor)
mywin = sbwin
elif mywin in ( detailwin, ):
if not len(listwin.records):
listwin.statusWrite("No listings for today.",wait=2)
mywin = listwin
continue
game=listwin.records[listwin.current_cursor]
gameid=game[6]
detail = MLBMediaDetail(mycfg,listwin.data)
games = detail.parseListings()
detailwin = MLBMediaDetailWin(myscr,mycfg,gameid,games)
detailwin.getMediaDetail(gameid)
mywin = detailwin
mywin.setCursors(listwin.record_cursor,
listwin.current_cursor)
# DEBUG : NEEDS ATTENTION FOR SCROLLING
if c in mykeys.get('MEDIA_DEBUG'):
if mywin in ( optwin, helpwin, stdwin ):
continue
if mywin == topwin:
try:
gameid = mywin.records[topwin.current_cursor][4]
except IndexError:
listwin.statusWrite("No media debug available.",wait=2)
continue
elif mywin == calwin:
try:
gameid = mywin.gamedata[mywin.game_cursor][0]
except IndexError:
mywin.statusWrite("No media debug available.",wait=2)
continue
elif mywin in ( rsswin, boxwin ):
if mywin == boxwin:
title_str="BOX SCORE LINE DEBUG"
else:
title_str="RSS ELEMENT DEBUG"
try:
myscr.clear()
mywin.titlewin.addstr(0,0,title_str)
mywin.titlewin.hline(1, 0, curses.ACS_HLINE, curses.COLS-1)
myscr.addstr(2,0,repr(mywin.records[mywin.current_cursor]))
myscr.refresh()
mywin.titlewin.refresh()
mywin.statusWrite('Press a key to continue...',wait=-1)
continue
except:
raise
else:
try:
gameid = listwin.records[listwin.current_cursor][6]
except IndexError:
listwin.statusWrite("No media debug available.",wait=2)
continue
myscr.clear()
mywin.titlewin.clear()
mywin.titlewin.addnstr(0,0,'LISTINGS DEBUG FOR ' + gameid,
curses.COLS-2)
mywin.titlewin.hline(1, 0, curses.ACS_HLINE, curses.COLS-1)
myscr.addnstr(2,0,'getListings() for current_cursor:',curses.COLS-2)
if mywin in ( sbwin , boxwin, detailwin ):
myscr.addstr(3,0,repr(listwin.records[listwin.current_cursor]))
elif mywin in ( calwin, ):
myscr.addnstr(3,0,repr(calwin.gamedata[calwin.game_cursor]),
(curses.LINES-4)*(curses.COLS)-1)
else:
myscr.addstr(3,0,repr(mywin.records[mywin.current_cursor]))
# hack for scrolling - don't display these lines if screen too
# small
if curses.LINES-4 > 14 and mywin not in ( calwin, statwin ):
myscr.addstr(11,0,'preferred media for current cursor:')
myscr.addstr(12,0,repr(prefer))
myscr.refresh()
mywin.titlewin.refresh()
mywin.statusWrite('Press a key to continue...',wait=-1)
# MEDIA DETAIL
if c in mykeys.get('MEDIA_DETAIL'):
game=listwin.records[listwin.current_cursor]
gameid=game[6]
detail = MLBMediaDetail(mycfg,listwin.data)
games = detail.parseListings()
detailwin = MLBMediaDetailWin(myscr,mycfg,gameid,games)
detailwin.getMediaDetail(gameid)
mywin = detailwin
detailwin.setCursors(listwin.record_cursor,
listwin.current_cursor)
# SCREENS - NEEDS WORK FOR SCROLLING
if c in mykeys.get('HELP'):
helpwin = MLBHelpWin(myscr,mykeys)
mywin = helpwin
#mywin.helpScreen()
# postseason
if c in mykeys.get('POSTSEASON'):
if mywin not in ( listwin, sbwin ):
continue
try:
event_id = listwin.records[listwin.current_cursor][2][0][3]
except:
mywin.statusWrite('No postseason angles available.',wait=1)
continue
mywin.statusWrite('Retrieving postseason camera angles...')
try:
cameras = mysched.getMultiAngleListing(event_id)
except:
cameras = []
postwin = MLBPostseason(myscr,mycfg,cameras)
mywin = postwin
# NEEDS ATTENTION FOR SCROLLING
if c in mykeys.get('OPTIONS'):
optwin = MLBOptWin(myscr,mycfg)
mywin = optwin
if c in mykeys.get('STATS'):
# until I have triple crown stats implemented, point them at
# the mlbstats app
mywin.statusWrite('See mlbstats.py for statistics.',wait=2)
continue
if mycfg.get('milbtv'):
mywin.statusWrite("Stats are not supported for MiLB",wait=2)
continue
mywin.statusWrite('Retrieving stats...')
mycfg.set('league','MLB')
if mycfg.get('stat_type') is None or mycfg.get('stat_type') == 'hitting':
mycfg.set('stat_type','pitching')
mycfg.set('sort_column','era')
else:
mycfg.set('stat_type','hitting')
mycfg.set('sort_column','avg')
mycfg.set('player_id',0)
mycfg.set('sort_team',0)
mycfg.set('active_sw',0)
mycfg.set('season_type','ANY')
mycfg.set('sort_order','default')
try:
stats.getStatsData()
except MLBUrlError:
raise
statwin = MLBStatsWin(myscr,mycfg,stats.data,stats.last_update)
mywin=statwin
if c in mykeys.get('STANDINGS'):
if mycfg.get('milbtv'):
mywin.statusWrite('Standings are not supported for MiLB',wait=2)
continue
mywin.statusWrite('Retrieving standings...')
if standings is None:
standings = MLBStandings()
try:
(year, month, day) = (mysched.year, mysched.month, mysched.day)
log.write('getStandingsData((%s,%s,%s))\n'%(year, month, day))
log.flush()
standings.getStandingsData((year,month,day))
except MLBUrlError:
mywin.statusWrite(standings.error_str,wait=2)
continue
stdwin = MLBStandingsWin(myscr,mycfg,standings.data,
standings.last_update,year)
mywin = stdwin
if c in mykeys.get('RSS'):
if mywin == rsswin:
rsswin.getFeedFromUser()
continue
rsswin.data = []
feeds = []
if len(mycfg.get('favorite')) > 0:
for team in mycfg.get('favorite'):
if team in TEAMCODES.keys():
feeds.append(team)
if len(feeds) < 1:
feeds.append('mlb')
else:
feeds.append('mlb')
for team in feeds:
rsswin.getRssData(team=team)
mywin = rsswin
if c in mykeys.get('CALENDAR'):
if mycfg.get('milbtv'):
# for now, not going to support calendar for milb
mywin.statusWrite('Calendar not supported for MiLB.',wait=2)
continue
( year, month ) = ( None, None )
if mywin not in ( calwin, ):
if len(mycfg.get('favorite')) > 0:
team = mycfg.get('favorite')[0]
else:
team = 'ana'
try:
year = mysched.year
month = mysched.month
except IndexError:
now=datetime.datetime.now()
year = now.year
month = now.month
else:
team = calwin.getTeamFromUser()
year = calwin.year
month = calwin.month
if team is None:
continue
try:
teamid = int(TEAMCODES[team][0])
except:
teamid = int(TEAMCODES['ana'][0])
mywin.statusWrite('Retrieving calendar for %s %s %s...' % \
(team.upper(), calendar.month_name[month], year ) )
if calwin is None:
calwin = MLBCalendarWin(myscr,mycfg)
calwin.getData(teamid,year,month)
mywin = calwin
if c in mykeys.get('MASTER_SCOREBOARD'):
# weird statwin crash related to window resizing
if mywin == statwin:
try:
sbwin.statusRefresh()
sbwin.titleRefresh()
sbwin.Refresh()
mywin = sbwin
except:
mywin = listwin
if mycfg.get('milbtv'):
# for now, not going to support master scoreboard for milb
mywin.statusWrite('Master scoreboard not supported for MiLB.',wait=2)
continue
#mycfg.set('milbtv', False)
#listwin.PgUp()
if mywin == calwin:
prefer = calwin.alignCursors(mysched,listwin)
try:
GAMEID = listwin.records[listwin.current_cursor][6]
except IndexError:
mywin.statusWrite("No games today. Cannot switch to master scoreboard from here.",wait=2)
continue
mywin.statusWrite('Retrieving master scoreboard for %s...' % GAMEID)
if sbwin in ( None, [] ):
sbwin = MLBMasterScoreboardWin(myscr,mycfg,GAMEID)
try:
sbwin.getScoreboardData(GAMEID)
except MLBUrlError:
sbwin.statusWrite(sbwin.error_str,wait=2)
continue
sbwin.setCursors(listwin.record_cursor,
listwin.current_cursor)
mywin = sbwin
# And also refresh the listings
listwin.statusWrite('Refreshing listings...',wait=1)
try:
available = mysched.getListings(mycfg.get('speed'),
mycfg.get('blackout'))
except:
pass
listwin.data = available
listwin.records = available[listwin.record_cursor:listwin.record_cursor+curses.LINES-4]
if c in mykeys.get('BOX_SCORE'):
if len(mywin.records) == 0:
continue
elif mywin == calwin and len(calwin.gamedata) == 0:
continue
if mywin in ( stdwin, statwin ):
continue
if mywin in ( calwin, ):
GAMEID = calwin.gamedata[calwin.game_cursor][0]
prefer = calwin.alignCursors(mysched,listwin)
elif mywin == linewin:
GAMEID = linewin.data['game']['id']
else:
try:
GAMEID = listwin.records[listwin.current_cursor][6]
except IndexError:
mywin.statusWrite('Listings out of sync. Please refresh.',wait=2)
continue
mywin.statusWrite('Retrieving box score for %s...' % GAMEID)
if boxscore in ( None, [] ):
boxscore=MLBBoxScore(GAMEID)
try:
data = boxscore.getBoxData(GAMEID)
except MLBUrlError:
listwin.statusWrite(boxscore.error_str,wait=2)
continue
boxwin = MLBBoxScoreWin(myscr,mycfg,data)
mywin = boxwin
if c in mykeys.get('LINE_SCORE'):
if len(mywin.records) == 0:
continue
elif mywin == calwin and len(calwin.gamedata) == 0:
continue
if mywin in ( stdwin, ):
continue
if mywin in ( calwin, ):
GAMEID = calwin.gamedata[calwin.game_cursor][0]
prefer = calwin.alignCursors(mysched,listwin)
elif mywin == boxwin:
GAMEID = boxwin.boxdata['game']['game_id']
else:
try:
GAMEID = listwin.records[listwin.current_cursor][6]
except IndexError:
mywin.statusWrite('Listings out of sync. Please refresh.',wait=2)
continue
mywin.statusWrite('Retrieving linescore for %s...' % GAMEID)
# TODO: might want to embed linescore code in MLBLineScoreWin
# and create a MLBLineScoreWin.getLineData() method like scoreboard
if linescore in ( None, ):
linescore = MLBLineScore(GAMEID)
try:
data = linescore.getLineData(GAMEID)
except MLBUrlError:
listwin.statusWrite(linescore.error_str,wait=2)
continue
linewin = MLBLineScoreWin(myscr,mycfg,data)
mywin = linewin
if c in mykeys.get('HIGHLIGHTS'):
if mywin in ( optwin, helpwin, stdwin ):
continue
try:
GAMEID = listwin.records[listwin.current_cursor][6]
except IndexError:
continue
topwin = MLBTopWin(myscr,mycfg,available)
topwin.data = listwin.records
listwin.statusWrite('Fetching Top Plays list...')
try:
if mywin == calwin:
prefer = calwin.alignCursors(mysched,listwin)
available = mysched.getTopPlays(GAMEID,mycfg.get('use_nexdef'))
except:
if mycfg.get('debug'):
raise
listwin.statusWrite('Could not fetch highlights.',wait=2)
available = listwin.data
continue
mywin = topwin
mywin.current_cursor = 0
mywin.data = available
mywin.records = available[0:curses.LINES-4]
mywin.record_cursor = 0
if c in mykeys.get('HIGHLIGHTS_PLAYLIST'):
if mywin in ( optwin, helpwin, stdwin ):
continue
try:
GAMEID = listwin.records[listwin.current_cursor][6]
except IndexError:
listwin.statusWrite('Could not find gameid for highlights',wait=2)
continue
listwin.statusWrite('Creating Top Plays Playlist...')
try:
temp = mysched.getTopPlays(GAMEID)
except:
listwin.statusWrite('Could not build highlights playlist.',wait=2)
fp = open(HIGHLIGHTS_LIST, 'w')
for highlight in temp:
fp.write(highlight[2]+'\n')
fp.close()
mediaUrl = '-playlist %s' % HIGHLIGHTS_LIST
eventId = listwin.records[listwin.current_cursor][6]
streamtype = 'highlight'
mediaStream = MediaStream(prefer['video'], session, mycfg,
prefer['video'][1],
streamtype=streamtype)
cmdStr = mediaStream.preparePlayerCmd(mediaUrl, eventId,streamtype)
# NEEDS ATTENTION FOR SCROLLING
if mycfg.get('show_player_command'):
myscr.clear()
myscr.addstr(0,0,cmdStr)
#if mycfg.get('use_nexdef') and streamtype != 'audio':
# pos=6
#else:
# pos=14
#myscr.hline(pos,0,curses.ACS_HLINE, curses.COLS-1)
#myscr.addstr(pos+1,0,'')
myscr.refresh()
time.sleep(1)
play = MLBprocess(cmdStr)
play.open()
play.waitInteractive(myscr)
# TODO: Needs attention for calendar
if c in mykeys.get('INNINGS'):
if mycfg.get('milbtv'):
mywin.statusWrite('Jump to inning not supported for MiLB.',wait=2)
continue
if len(mywin.records) == 0:
continue
elif mywin==calwin and len(calwin.gamedata)==0:
continue
if mywin in ( optwin, helpwin, stdwin ):
continue
if mywin==calwin:
prefer = calwin.alignCursors(mysched,listwin)
if mycfg.get('use_nexdef') or \
listwin.records[listwin.current_cursor][5] in ('F', 'CG') or \
listwin.records[listwin.current_cursor][7] == 'media_archive':
pass
else:
error_str = 'ERROR: Jump to innings only supported for NexDef mode and archived games.'
listwin.statusWrite(error_str,wait=2)
continue
innwin = MLBInningWin(myscr, mycfg,
listwin.records[listwin.current_cursor],
mysched)
innwin.Refresh()
innwin.titleRefresh()
try:
start_time = innwin.selectToPlay()
except:
raise
if start_time is not None:
if prefer['video'] is None:
mywin.errorScreen('ERROR: Requested media not available.')
continue
mediaStream = MediaStream(prefer['video'],
session,mycfg,
coverage=prefer['video'][1],
streamtype='video',
start_time=start_time)
try:
mediaUrl = mediaStream.locateMedia()
except:
mywin.errorScreen('ERROR: %s'%\
mediaStream.error_str)
continue
try:
mediaUrl = mediaStream.prepareMediaStreamer(mediaUrl)
except:
mywin.errorScreen('ERROR: %s'%\
mediaStream.error_str)
continue
cmdStr = mediaStream.preparePlayerCmd(mediaUrl,
listwin.records[listwin.current_cursor][6])
play = MLBprocess(cmdStr)
play.open()
play.waitInteractive(myscr)
if c in mykeys.get('LISTINGS') or c in mykeys.get('REFRESH') or \
c in mykeys.get('MILBTV'):
if mywin == calwin:
try:
prefer = calwin.alignCursors(mysched,listwin)
except:
prefer = dict()
prefer['audio'] = None
prefer['video'] = None
mywin = listwin
# refresh
mywin.statusWrite('Refreshing listings...',wait=1)
if c in mykeys.get('MILBTV'):
# only need to reset listings to top first time
# else, remember our place
if not mycfg.get('milbtv'):
listwin.PgUp()
mycfg.set('milbtv', True)
try:
milbsession
except:
mywin.statusWrite('Logging into milb.com...',wait=0)
milb_user=(mycfg.get('user') ,\
mycfg.get('milb_user'))[mycfg.data.has_key('milb_user')]
milb_pass=(mycfg.get('pass') ,\
mycfg.get('milb_pass'))[mycfg.data.has_key('milb_pass')]
milbsession = MiLBSession(user=milb_user,
passwd=milb_pass,
debug=mycfg.get('debug'))
try:
milbsession.getSessionData()
except MLBAuthError:
error_str = 'Login was unsuccessful. Check user and pass in ' + myconf
mywin.statusWrite(error_str,wait=2)
except Exception,detail:
error_str = str(detail)
mywin.statusWrite(error_str,wait=2)
# align with mlbsched listings
(y,m,d) = (mlbsched.year,mlbsched.month,mlbsched.day)
try:
milbsched.Jump((y,m,d),mycfg.get('speed'), mycfg.get('blackout'))
except: