summaryrefslogtreecommitdiff
path: root/plugin.video.mlbtv
diff options
context:
space:
mode:
authoreracknaphobia <eracknaphobia@hotmail.com>2017-03-08 08:31:41 -0500
committerenen92 <enen92@users.noreply.github.com>2017-03-08 13:31:41 +0000
commite752d764bb2d6e10df5dd235569809728debd0c9 (patch)
treef2d345dccf4a734362181470341a962083a3169d /plugin.video.mlbtv
parent5a7da8304ae62fb897651bfeb5ebb58134d13df3 (diff)
[plugin.video.mlbtv] 2017.3.7 (#1035)
* [plugin.video.mlbtv] 2017.3.7 * Fixed xbmc.python version * Fix Language Issues
Diffstat (limited to 'plugin.video.mlbtv')
-rw-r--r--plugin.video.mlbtv/LICENSE.txt339
-rw-r--r--plugin.video.mlbtv/README.md2
-rw-r--r--plugin.video.mlbtv/addon.xml31
-rw-r--r--plugin.video.mlbtv/changelog.txt61
-rw-r--r--plugin.video.mlbtv/fanart.jpgbin0 -> 295597 bytes
-rw-r--r--plugin.video.mlbtv/icon.pngbin0 -> 38861 bytes
-rw-r--r--plugin.video.mlbtv/main.py1014
-rw-r--r--plugin.video.mlbtv/resources/__init__.py1
-rw-r--r--plugin.video.mlbtv/resources/language/resource.language.en_gb/strings.po101
-rw-r--r--plugin.video.mlbtv/resources/lib/__init__.py1
-rw-r--r--plugin.video.mlbtv/resources/lib/globals.py550
-rw-r--r--plugin.video.mlbtv/resources/settings.xml27
12 files changed, 2127 insertions, 0 deletions
diff --git a/plugin.video.mlbtv/LICENSE.txt b/plugin.video.mlbtv/LICENSE.txt
new file mode 100644
index 0000000..d159169
--- /dev/null
+++ b/plugin.video.mlbtv/LICENSE.txt
@@ -0,0 +1,339 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License along
+ with this program; if not, write to the Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
diff --git a/plugin.video.mlbtv/README.md b/plugin.video.mlbtv/README.md
new file mode 100644
index 0000000..51c1fb0
--- /dev/null
+++ b/plugin.video.mlbtv/README.md
@@ -0,0 +1,2 @@
+Watch MLB tv in KODI
+
diff --git a/plugin.video.mlbtv/addon.xml b/plugin.video.mlbtv/addon.xml
new file mode 100644
index 0000000..5c3463b
--- /dev/null
+++ b/plugin.video.mlbtv/addon.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<addon id="plugin.video.mlbtv" name="MLB.TVĀ®" version="2017.3.7" provider-name="eracknaphobia">
+ <requires>
+ <import addon="xbmc.python" version="2.25.0"/>
+ <import addon="script.module.simplejson" version="3.3.0"/>
+ <import addon="script.module.pytz" version="2014.2" />
+ <import addon="script.module.beautifulsoup4" version="4.3.1" />
+ <import addon="script.module.pil" version="1.1.7"/>
+ </requires>
+ <extension point="xbmc.python.pluginsource" library="main.py">
+ <provides>video</provides>
+ </extension>
+ <extension point="xbmc.addon.metadata">
+ <platform>all</platform>
+ <summary lang="en_GB">Watch every out-of-market regular season game in the office or on the go. The #1 LIVE Streaming Sports Service</summary>
+ <description lang="en_GB">Watch every out-of-market regular season game in the office or on the go. The #1 LIVE Streaming Sports Service</description>
+ <disclaimer lang="en_GB"></disclaimer>
+ <news>
+- Bumped xbmc python version
+- Converted xml strings file to po file
+- Code clean up
+ </news>
+ <language>en</language>
+ <platform>all</platform>
+ <license>GNU GENERAL PUBLIC LICENSE. Version 2, June 1991</license>
+ <forum></forum>
+ <website></website>
+ <email></email>
+ <source>https://github.com/eracknaphobia/plugin.video.mlbtv</source>
+ </extension>
+</addon>
diff --git a/plugin.video.mlbtv/changelog.txt b/plugin.video.mlbtv/changelog.txt
new file mode 100644
index 0000000..b1fddf2
--- /dev/null
+++ b/plugin.video.mlbtv/changelog.txt
@@ -0,0 +1,61 @@
+2017.3.7
+- Bumped xbmc python version
+- Converted xml strings file to po file
+- Code clean up
+
+2016.7.28
+- Fixed view all recap / condensed for date
+- Fixed play all highlights skipping first highlight video
+
+2016.7.13
+- Fixed error loading MLB plus games
+- Fixed error when single or no games for day (thanks bontibon)
+- Fixed issue when game is only aired nationally
+
+2016.4.29.1
+- Fixed choose stream bug
+
+2016.4.29
+- Changed Full Games selection to use the teams abbreviated name instead of Home/Away
+- Highlights option now avaiable for Live and Archive games (no MLB tv account required)
+- Play individual highlights or select Play All to watch all highlights of the selected game
+- Display recap / condensed game not available message instead of erroring out
+- Added check for invalid username/password
+
+2016.4.19
+- Free games are now highlighted green
+- Changed wording on single team subscription to include free game subscription
+- Added not authorized message when user attempts to request a stream their account is not authorized to access
+- Added blackout lift time in blackout message if game has finished
+- Added logic to catch a username or password change and perform a fresh login
+
+2016.4.12
+- Added Single Team Subscription setting
+- Fixed Full Game not obeying the stream quality setting
+
+2016.4.11
+- Fixed recap, condensed not using stream quality setting
+
+2016.4.7.2
+- Fixed Recap and Condensed switched in single game selection
+
+2016.4.7
+- Replaced Highlights option with Recap (~3 min) and Condensed (~15 min) options for archive games
+- The date menu item can now be selected in order to watch the entire days recaps or condensed clips
+- Reversed stream quality selection dialog so better streams are on top
+- Fixed blackout message not displaying bug
+- Greatly reduced the size of the plugin string
+
+2016.3.24
+- Updated stream qualities values to match newer masterfiles
+- Added "Always Ask" stream quality selection
+
+2016.3.16
+- Added Logout feature in add-on settings
+- Added Highlights (60fps supported)
+
+2016.3.7
+- Added live audio support
+
+2016.3.4
+- Beta released \ No newline at end of file
diff --git a/plugin.video.mlbtv/fanart.jpg b/plugin.video.mlbtv/fanart.jpg
new file mode 100644
index 0000000..8e71f3f
--- /dev/null
+++ b/plugin.video.mlbtv/fanart.jpg
Binary files differ
diff --git a/plugin.video.mlbtv/icon.png b/plugin.video.mlbtv/icon.png
new file mode 100644
index 0000000..3edf563
--- /dev/null
+++ b/plugin.video.mlbtv/icon.png
Binary files differ
diff --git a/plugin.video.mlbtv/main.py b/plugin.video.mlbtv/main.py
new file mode 100644
index 0000000..022789d
--- /dev/null
+++ b/plugin.video.mlbtv/main.py
@@ -0,0 +1,1014 @@
+from resources.lib.globals import *
+
+
+def categories():
+ addDir('Today\'s Games',100,ICON,FANART)
+ addDir('Yesterday\'s Games',105,ICON,FANART)
+ #addDir('Favorite Team Recent Games','favteam',500,ICON,FANART)
+ addDir('Goto Date',200,ICON,FANART)
+
+
+def todaysGames(game_day):
+ if game_day == None:
+ game_day = localToEastern()
+
+ settings.setSetting(id='stream_date', value=game_day)
+
+ display_day = stringToDate(game_day, "%Y-%m-%d")
+ url_game_day = display_day.strftime('year_%Y/month_%m/day_%d')
+ prev_day = display_day - timedelta(days=1)
+
+ addDir('[B]<< Previous Day[/B]',101,PREV_ICON,FANART,prev_day.strftime("%Y-%m-%d"))
+
+ date_display = '[B][I]'+ colorString(display_day.strftime("%A, %m/%d/%Y"),GAMETIME_COLOR)+'[/I][/B]'
+
+ addPlaylist(date_display,str(game_day),900,ICON,FANART)
+
+ #addPlaylist(date_display,display_day,'/playhighlights',999,ICON,FANART)
+
+ url = 'http://gdx.mlb.com/components/game/mlb/'+url_game_day+'/grid_ce.json'
+
+ req = urllib2.Request(url)
+ req.add_header('Connection', 'close')
+ req.add_header('User-Agent', UA_PS4)
+
+ try:
+ response = urllib2.urlopen(req)
+ json_source = json.load(response)
+ response.close()
+ except HTTPError as e:
+ xbmc.log('The server couldn\'t fulfill the request.')
+ xbmc.log('Error code: ', e.code)
+ sys.exit()
+
+
+ global RECAP_PLAYLIST
+ global EXTENDED_PLAYLIST
+ RECAP_PLAYLIST.clear()
+ EXTENDED_PLAYLIST.clear()
+
+ try:
+ itr = json_source['data']['games']['game']
+ if not isinstance(itr, list):
+ itr = [itr]
+ for game in itr:
+ createGameListItem(game, game_day)
+ except:
+ # if there are no games on this date
+ pass
+
+ next_day = display_day + timedelta(days=1)
+ addDir('[B]Next Day >>[/B]',101,NEXT_ICON,FANART,next_day.strftime("%Y-%m-%d"))
+
+
+def createGameListItem(game, game_day):
+ icon = getGameIcon(game['home_team_id'],game['away_team_id'])
+ #http://mlb.mlb.com/mlb/images/devices/ballpark/1920x1080/2681.jpg
+ #B&W
+ #fanart = 'http://mlb.mlb.com/mlb/images/devices/ballpark/1920x1080/'+game['venue_id']+'.jpg'
+ #Color
+ fanart = 'http://www.mlb.com/mlb/images/devices/ballpark/1920x1080/color/'+game['venue_id']+'.jpg'
+
+ if TEAM_NAMES == "0":
+ away_team = game['away_team_name']
+ home_team = game['home_team_name']
+ else:
+ away_team = game['away_name_abbrev']
+ home_team = game['home_name_abbrev']
+
+
+ fav_game = False
+
+ if game['away_team_name'].encode('utf-8') in FAV_TEAM :
+ fav_game = True
+ away_team = colorString(away_team,getFavTeamColor())
+
+ if game['home_team_name'].encode('utf-8') in FAV_TEAM:
+ fav_game = True
+ home_team = colorString(home_team,getFavTeamColor())
+
+
+ game_time = ''
+ if game['status'] == 'Preview':
+ game_time = game_day+' '+game['event_time']
+ game_time = stringToDate(game_time, "%Y-%m-%d %I:%M %p")
+ game_time = easternToLocal(game_time)
+
+ if TIME_FORMAT == '0':
+ game_time = game_time.strftime('%I:%M %p').lstrip('0')
+ else:
+ game_time = game_time.strftime('%H:%M')
+
+ game_time = colorString(game_time,UPCOMING)
+
+ else:
+ game_time = game['status']
+
+ if game_time == 'Final':
+ game_time = colorString(game_time,FINAL)
+
+ elif 'In Progress' in game_time:
+ if game['top_inning'] == 'Y':
+ #up triangle
+ #top_bottom = u"\u25B2"
+ top_bottom = "T"
+ else:
+ #down triangle
+ #top_bottom = u"\u25BC"
+ top_bottom = "B"
+
+ inning = game['inning']
+ if int(inning) % 10 == 1 and int(inning) != 11:
+ ordinal_indicator = "st"
+ elif int(inning) % 10 == 2 and int(inning) != 12:
+ ordinal_indicator = "nd"
+ elif int(inning) % 10 == 3 and int(inning) != 13:
+ ordinal_indicator = "rd"
+ else:
+ ordinal_indicator = "th"
+
+ game_time = top_bottom + ' ' + inning + ordinal_indicator
+
+ if int(inning) >= 9:
+ color = CRITICAL
+ else:
+ color = LIVE
+
+ game_time = colorString(game_time,color)
+
+ else:
+ game_time = colorString(game_time,LIVE)
+
+
+ event_id = str(game['calendar_event_id'])
+ gid = game['id']
+
+ live_feeds = 0
+ archive_feeds = 0
+ teams_stream = game['away_code'] + game['home_code']
+ stream_date = str(game_day)
+
+
+ desc = ''
+ hide_spoilers = 0
+ if NO_SPOILERS == '1' or (NO_SPOILERS == '2' and fav_game) or (NO_SPOILERS == '3' and game_day == localToEastern()) or (NO_SPOILERS == '4' and game_day < localToEastern()) or game['status'] == 'Preview':
+ name = game_time + ' ' + away_team + ' at ' + home_team
+ hide_spoilers = 1
+ else:
+ name = game_time + ' ' + away_team + ' ' + colorString(str(game['away_score']),SCORE_COLOR) + ' at ' + home_team + ' ' + colorString(str(game['home_score']),SCORE_COLOR)
+
+
+ name = name.encode('utf-8')
+ if fav_game:
+ name = '[B]'+name+'[/B]'
+
+ title = away_team + ' at ' + home_team
+ title = title.encode('utf-8')
+
+ #Label free game of the day if applicable
+ try:
+ if game['game_media']['homebase']['media'][0]['free'] == "ALL":
+ #and game_day >= localToEastern():
+ name = colorString(name, FREE)
+ except:
+ pass
+
+ #Set audio/video info based on stream quality setting
+ audio_info, video_info = getAudioVideoInfo()
+ #'duration':length
+ info = {'plot':desc,'tvshowtitle':'MLB','title':title,'originaltitle':title,'aired':game_day,'genre':LOCAL_STRING(700),'mediatype':'video'}
+
+ #Create Playlist for the days recaps and condensed
+ '''
+ try:
+ recap_url, condensed_url = getHighlightLinks(teams_stream, stream_date)
+ global RECAP_PLAYLIST
+ listitem = xbmcgui.ListItem(title, thumbnailImage=icon)
+ listitem.setInfo( type="Video", infoLabels={ "Title": title })
+ RECAP_PLAYLIST.add(recap_url, listitem)
+
+ global EXTENDED_PLAYLIST
+ listitem = xbmcgui.ListItem(title, thumbnailImage=icon)
+ listitem.setInfo( type="Video", infoLabels={ "Title": title } )
+ EXTENDED_PLAYLIST.add(condensed_url, listitem)
+ except:
+ pass
+ '''
+ addStream(name,title,event_id,gid,icon,fanart,info,video_info,audio_info,teams_stream,stream_date)
+
+
+
+def streamSelect(event_id, gid, teams_stream, stream_date):
+ display_day = stringToDate(stream_date, "%Y-%m-%d")
+ url_game_day = display_day.strftime('year_%Y/month_%m/day_%d')
+ url = 'http://gdx.mlb.com/components/game/mlb/'+url_game_day+'/grid_ce.json'
+
+ req = urllib2.Request(url)
+ req.add_header('Connection', 'close')
+ req.add_header('User-Agent', UA_PS4)
+
+ try:
+ response = urllib2.urlopen(req)
+ json_source = json.load(response)
+ response.close()
+ except HTTPError as e:
+ xbmc.log('The server couldn\'t fulfill the request.')
+ xbmc.log('Error code: ', e.code)
+ sys.exit()
+
+ #Find selected game
+ teams = {}
+ itr = json_source['data']['games']['game']
+ if type(itr) is not list:
+ itr = [itr]
+ #xbmc.log(str(itr))
+ for game in itr:
+ xbmc.log(game['id'])
+ xbmc.log(gid)
+
+ if gid == game['id']:
+ try:
+ epg = game['game_media']['homebase']['media']
+ teams={'Home':game['home_name_abbrev'],'Away':game['away_name_abbrev']}
+ break
+ except:
+ #no stream info, abort! abort!
+ msg = "No playable streams found."
+ dialog = xbmcgui.Dialog()
+ ok = dialog.ok('Streams Not Found', msg)
+ sys.exit()
+
+
+ stream_title = []
+ content_id = []
+ free_game = []
+ media_state = []
+ playback_scenario = []
+ archive_type = ['Highlights','Recap','Condensed','Full Game']
+ #archive_type = ['Recap','Condensed','Full Game']
+ try:
+ for item in epg:
+ xbmc.log(str(item))
+ xbmc.log(str(item['playback_scenario']))
+ xbmc.log(PLAYBACK_SCENARIO)
+ if str(item['playback_scenario']) == PLAYBACK_SCENARIO:
+
+ if item['enhanced'] == 'Y':
+ title = 'Enhanced'
+ stream_title.append(title)
+ else:
+ title = str(item['type'])[6:].title()
+ try:
+ stream_title.append(teams[title] + " ("+item['display']+")")
+ except:
+ stream_title.append(title+ " ("+item['display']+")")
+
+ media_state.append(item['state'])
+ content_id.append(item['id'])
+ playback_scenario.append(str(item['playback_scenario']))
+
+ elif str(item['playback_scenario']) == "HTTP_CLOUD_AUDIO" and item['state'] != 'MEDIA_OFF':
+ title = str(item['type']).title()
+ title = title.replace('_', ' ')
+ stream_title.append(title + " ("+item['display']+")")
+ media_state.append(item['state'])
+ content_id.append(item['id'])
+ playback_scenario.append(str(item['playback_scenario']))
+ except:
+ pass
+ '''
+ elif str(item['playback_scenario']) == "FLASH_2500K_1280X720" and item['type'] != 'condensed_game':
+ title = str(item['type']).title()
+ title = title.replace('_', ' ')
+ stream_title.append(title + " ("+item['display']+")")
+ media_state.append(item['state'])
+ content_id.append(item['id'])
+ playback_scenario.append("HTTP_CLOUD_WIRED_60")
+ '''
+ #All past games should have highlights
+ if len(stream_title) == 0 and stream_date > localToEastern():
+ msg = "No playable streams found."
+ dialog = xbmcgui.Dialog()
+ ok = dialog.ok('Streams Not Found', msg)
+ sys.exit()
+
+ #Reverse Order for display purposes
+ #stream_title.reverse()
+ #ft.reverse()
+ xbmc.log("MEDIA STATE")
+ xbmc.log(str(media_state))
+
+ stream_url = ''
+ media_auth = ''
+
+ play_highlights = 0
+ if len(media_state) > 0:
+ if media_state[0] == 'MEDIA_ARCHIVE':
+ dialog = xbmcgui.Dialog()
+ a = dialog.select('Choose Archive', archive_type)
+
+ if a > -1:
+ if a < 3:
+ recap, condensed, highlights = getHighlightLinks(teams_stream, stream_date)
+ if a == 0:
+ play_highlights = 1
+ elif a == 1:
+ try:
+ stream_url = recap['url']
+ except:
+ dialog = xbmcgui.Dialog()
+ ok = dialog.ok('Recap Not Available', 'The recap for this game is not yet available. \nPlease check back later.')
+ else:
+ try:
+ stream_url = condensed['url']
+ except:
+ dialog = xbmcgui.Dialog()
+ ok = dialog.ok('Condensed Game Not Available', 'The condensed game is not yet available. \nPlease check back later.')
+
+
+ if QUALITY == 'Always Ask' and ((len(highlights) > 0 and play_highlights == 1) or stream_url != '') :
+ bandwidth = getStreamQuality(str(highlights[0][0]))
+ else:
+ bandwidth = find(QUALITY,'(',' kbps)')
+
+ stream_url = createHighlightStream(stream_url, bandwidth)
+ elif a == 3:
+ dialog = xbmcgui.Dialog()
+ n = dialog.select('Choose Stream', stream_title)
+ if n > -1:
+ stream_url, media_auth = fetchStream(content_id[n],event_id,playback_scenario[n])
+ stream_url = createFullGameStream(stream_url,media_auth,media_state[n])
+ else:
+ #Add Highlights option to live games
+ stream_title.insert(0,'Highlights')
+ dialog = xbmcgui.Dialog()
+ n = dialog.select('Choose Stream', stream_title)
+ if n > -1:
+ if stream_title[n] == 'Highlights':
+ recap, condensed, highlights = getHighlightLinks(teams_stream, stream_date)
+ if len(highlights) > 0:
+ play_highlights = 1
+ if QUALITY == 'Always Ask':
+ bandwidth = getStreamQuality(str(highlights[0][0]))
+ else:
+ bandwidth = find(QUALITY,'(',' kbps)')
+ else:
+ try:
+ n = n -1
+ stream_url, media_auth = fetchStream(content_id[n],event_id,playback_scenario[n])
+ stream_url = createFullGameStream(stream_url,media_auth,media_state[n])
+ except:
+ pass
+ else:
+ archive_type = ['Highlights']
+ dialog = xbmcgui.Dialog()
+ a = dialog.select('Choose Archive', archive_type)
+ if a == 0:
+ #getHighlightLinks(teams_stream, stream_date)
+ play_highlights = 1
+
+
+ listitem = xbmcgui.ListItem(path=stream_url)
+
+ if '.m3u8' in stream_url:
+ xbmcplugin.setResolvedUrl(handle=addon_handle, succeeded=True, listitem=listitem)
+
+ elif play_highlights == 1:
+ highlight_name = ['Play All']
+ highlight_url = ['junk']
+ for i in range(0,len(highlights)-1):
+ #highlights.append([clip_url,headline,icon])
+ highlight_url.append(highlights[i][0])
+ highlight_name.append(highlights[i][1])
+
+
+ dialog = xbmcgui.Dialog()
+ a = dialog.select('Choose Highlight', highlight_name)
+ if a > 0:
+ #listitem = xbmcgui.ListItem(thumbnailImage=highlights[a-1][2], path=highlights[a-1][0])
+ listitem = xbmcgui.ListItem(path=createHighlightStream(highlight_url[a], bandwidth))
+ listitem.setInfo( type="Video", infoLabels={ "Title": highlight_name[a] })
+ xbmcplugin.setResolvedUrl(handle=addon_handle, succeeded=True, listitem=listitem)
+ elif a == 0:
+ HIGHLIGHT_PLAYLIST= xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
+ HIGHLIGHT_PLAYLIST.clear()
+ xbmc.log(str(highlights))
+
+ listitem = xbmcgui.ListItem('dummy', thumbnailImage='')
+ listitem.setInfo( type="Video", infoLabels={ "Title": 'dummy' })
+ HIGHLIGHT_PLAYLIST.add('http://cdn.gravlab.net/sparse/v1d30/2013/nightskyHLS/Lapse2.m3u8', listitem)
+
+ for i in range(0,len(highlights)-1):
+ #highlights.append([clip_url,headline,icon])
+ listitem = xbmcgui.ListItem(highlights[i][1], thumbnailImage=highlights[i][2])
+ listitem.setInfo( type="Video", infoLabels={ "Title": highlights[i][1] })
+ HIGHLIGHT_PLAYLIST.add(createHighlightStream(highlights[i][0], bandwidth), listitem)
+
+
+ else:
+ #xbmcplugin.setResolvedUrl(addon_handle, False, listitem)
+ xbmc.executebuiltin('Dialog.Close(all,true)')
+
+
+
+def playAllHighlights():
+ stream_title = ['Recap','Condensed']
+ dialog = xbmcgui.Dialog()
+ n = dialog.select('View All', stream_title)
+
+ if n == 0:
+ xbmc.Player().play(RECAP_PLAYLIST)
+ elif n == 1:
+ xbmc.Player().play(EXTENDED_PLAYLIST)
+
+
+def getGamesForDate(stream_date):
+ stream_date_new = stringToDate(stream_date, "%Y-%m-%d")
+ year = stream_date_new.strftime("%Y")
+ month = stream_date_new.strftime("%m")
+ day = stream_date_new.strftime("%d")
+
+ url = 'http://gdx.mlb.com/components/game/mlb/year_'+year+'/month_'+month+'/day_'+day+'/'
+ req = urllib2.Request(url)
+ req.add_header('Connection', 'close')
+ req.add_header('User-Agent', UA_IPAD)
+
+ try:
+ response = urllib2.urlopen(req)
+ html_data = response.read()
+ response.close()
+ except HTTPError as e:
+ xbmc.log('The server couldn\'t fulfill the request.')
+ xbmc.log('Error code: ', e.code)
+ sys.exit()
+
+ #<li><a href="gid_2016_03_13_arimlb_chamlb_1/"> gid_2016_03_13_arimlb_chamlb_1/</a></li>
+ match = re.compile('<li><a href="gid_(.+?)/">(.+?)</a></li>',re.DOTALL).findall(html_data)
+ global RECAP_PLAYLIST
+ global EXTENDED_PLAYLIST
+ RECAP_PLAYLIST.clear()
+ EXTENDED_PLAYLIST.clear()
+
+ pDialog = xbmcgui.DialogProgressBG()
+ pDialog.create('MLB Highlights', 'Retrieving Streams ...')
+ match_count = len(match)
+ if match_count == 0:
+ match_count = 1 # prevent division by zero when no games
+ perc_increments = 100/match_count
+ first_time_thru = True
+ bandwidth = find(QUALITY,'(',' kbps)')
+
+ for gid, junk in match:
+ pDialog.update(perc_increments, message='Downloading '+gid)
+ try:
+ recap, condensed, highlights = getHighlightLinks(None, stream_date, gid)
+
+ if first_time_thru and QUALITY == 'Always Ask':
+ bandwidth = getStreamQuality(str(recap['url']))
+ first_time_thru = False
+
+
+ listitem = xbmcgui.ListItem(recap['title'], thumbnailImage=recap['icon'])
+ listitem.setInfo( type="Video", infoLabels={ "Title": recap['title'] })
+ RECAP_PLAYLIST.add(createHighlightStream(recap['url'],bandwidth), listitem)
+
+ listitem = xbmcgui.ListItem(condensed['title'], thumbnailImage=condensed['icon'])
+ listitem.setInfo( type="Video", infoLabels={ "Title": condensed['title'] } )
+ EXTENDED_PLAYLIST.add(createHighlightStream(condensed['url'],bandwidth), listitem)
+ except:
+ pass
+
+ perc_increments += perc_increments
+
+
+ pDialog.close()
+
+
+def createHighlightStream(url, bandwidth):
+ if bandwidth != '' and int(bandwidth) < 4500:
+ url = url.replace('master_tablet_60.m3u8', 'asset_'+bandwidth+'K.m3u8')
+
+ url = url + '|User-Agent='+UA_IPAD
+
+ return url
+
+
+def getHighlightLinks(teams_stream, stream_date, gid=None, bandwidth=None):
+ #global HIGHLIGHT_PLAYLIST
+ #HIGHLIGHT_PLAYLIST.clear()
+ stream_date = stringToDate(stream_date, "%Y-%m-%d")
+ year = stream_date.strftime("%Y")
+ month = stream_date.strftime("%m")
+ day = stream_date.strftime("%d")
+
+ if gid == None:
+ away = teams_stream[:3].lower()
+ home = teams_stream[3:].lower()
+ url = 'http://gdx.mlb.com/components/game/mlb/year_'+year+'/month_'+month+'/day_'+day+'/gid_'+year+'_'+month+'_'+day+'_'+away+'mlb_'+home+'mlb_1/media/mobile.xml'
+ else:
+ url = 'http://gdx.mlb.com/components/game/mlb/year_'+year+'/month_'+month+'/day_'+day+'/gid_'+gid+'/media/mobile.xml'
+
+ req = urllib2.Request(url)
+ req.add_header('Connection', 'close')
+ req.add_header('User-Agent', UA_IPAD)
+ try:
+ response = urllib2.urlopen(req)
+ xml_data = response.read()
+ response.close()
+ except HTTPError as e:
+ xbmc.log('The server couldn\'t fulfill the request.')
+ xbmc.log('Error code: ', e.code)
+ sys.exit()
+
+ match = re.compile('<media id="(.+?)"(.+?)<headline>(.+?)</headline>(.+?)<thumb type="22">(.+?)</thumb>(.+?)<url playback-scenario="HTTP_CLOUD_TABLET_60">(.+?)</url>',re.DOTALL).findall(xml_data)
+ bandwidth = find(QUALITY,'(',' kbps)')
+
+ recap = {}
+ condensed = {}
+ highlights = []
+
+ for media_id, media_tag, headline, junk1, icon, junk2, clip_url in match:
+ if 'media-type="T"' in media_tag:
+ #if bandwidth != '' and int(bandwidth) < 4500:
+ #clip_url = clip_url.replace('master_tablet_60.m3u8', 'asset_'+bandwidth+'K.m3u8')
+
+ #clip_url = clip_url + '|User-Agent='+UA_IPAD
+ highlights.append([clip_url,headline,icon])
+
+
+ if 'media-type="R"' in media_tag:
+ #icon = 'http://mediadownloads.mlb.com/mlbam/'+year+'/'+month+'/'+day+'/images/mlbf_'+media_id+'_th_43.jpg'
+ title = headline
+ recap = {'url':clip_url, 'icon':icon, 'title':headline}
+ elif 'media-type="C"' in media_tag:
+ #icon = 'http://mediadownloads.mlb.com/mlbam/'+year+'/'+month+'/'+day+'/images/mlbf_'+media_id+'_th_43.jpg'
+ title = headline
+ condensed = {'url':clip_url, 'icon':icon, 'title':headline}
+
+ return recap, condensed, highlights
+
+
+
+def createFullGameStream(stream_url, media_auth, media_state):
+ #SD (800 kbps)|SD (1600 kbps)|HD (3000 kbps)|HD (5000 kbps)
+ bandwidth = ''
+ bandwidth = find(QUALITY,'(',' kbps)')
+
+ if QUALITY == 'Always Ask':
+ bandwidth = getStreamQuality(stream_url)
+
+ #Only set bandwidth if it's explicitly set
+ if bandwidth != '':
+ if media_state == 'MEDIA_ARCHIVE':
+ #ARCHIVE
+ #http://mlblive-akc.mlb.com/ls04/mlbam/2016/03/02/MLB_GAME_VIDEO_DETNYA_HOME_20160302/master_wired.m3u8
+ #http://mlblive-akc.mlb.com/ls04/mlbam/2016/03/02/MLB_GAME_VIDEO_DETNYA_HOME_20160302/1800K/1800_complete-trimmed.m3u8
+ stream_url = stream_url.replace(MASTER_FILE_TYPE, bandwidth+'K/'+bandwidth+'_complete-trimmed.m3u8')
+
+ elif media_state == 'MEDIA_ON':
+ #LIVE
+ #5000K/5000_slide.m3u8 OR #3500K/3500_complete.m3u8
+ # Slide = Live, Complete = Watch from beginning?
+ stream_url = stream_url.replace(MASTER_FILE_TYPE, bandwidth+'K/'+bandwidth+'_complete.m3u8')
+
+
+
+ #cj = cookielib.LWPCookieJar()
+ #cj.load(os.path.join(ADDON_PATH_PROFILE, 'cookies.lwp'),ignore_discard=True)
+ stream_url = stream_url + '|User-Agent='+UA_PS4+'&Cookie='+media_auth
+
+ return stream_url
+
+
+
+
+def fetchStream(content_id,event_id,playback_scenario):
+ stream_url = ''
+ media_auth = ''
+ identity_point_id = ''
+ fingerprint = ''
+
+ expired_cookies = True
+ try:
+ cj = cookielib.LWPCookieJar(os.path.join(ADDON_PATH_PROFILE, 'cookies.lwp'))
+ cj.load(os.path.join(ADDON_PATH_PROFILE, 'cookies.lwp'),ignore_discard=True)
+
+ #Check if cookies have expired
+ at_least_one_expired = False
+ num_cookies = 0
+ for cookie in cj:
+ num_cookies += 1
+ if cookie.is_expired():
+ at_least_one_expired = True
+ break
+
+ if not at_least_one_expired:
+ expired_cookies = False
+ except:
+ pass
+
+ if expired_cookies or num_cookies == 0 or USERNAME != OLD_USERNAME or PASSWORD != OLD_PASSWORD:
+ #Remove cookie file
+ cookie_file = xbmc.translatePath(os.path.join(ADDON_PATH_PROFILE+'cookies.lwp'))
+ try:
+ os.remove(cookie_file)
+ except:
+ pass
+ login()
+
+
+ cj = cookielib.LWPCookieJar(os.path.join(ADDON_PATH_PROFILE, 'cookies.lwp'))
+ cj.load(os.path.join(ADDON_PATH_PROFILE, 'cookies.lwp'),ignore_discard=True)
+ for cookie in cj:
+ if cookie.name == "ipid":
+ identity_point_id = cookie.value
+ elif cookie.name == "fprt":
+ fingerprint = cookie.value
+
+ if identity_point_id == '' or fingerprint == '':
+ return stream_url, media_auth
+
+
+ session_key = getSessionKey(content_id,event_id,identity_point_id,fingerprint)
+ #Reload Cookies
+ cj = cookielib.LWPCookieJar(os.path.join(ADDON_PATH_PROFILE, 'cookies.lwp'))
+ cj.load(os.path.join(ADDON_PATH_PROFILE, 'cookies.lwp'),ignore_discard=True)
+ opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
+
+ if session_key == '':
+ return stream_url, media_auth
+ elif session_key == 'blackout':
+ msg = "The game you are trying to access is not currently available due to local or national blackout restrictions.\n Full game archives will be available 48 hours after completion of this game."
+ dialog = xbmcgui.Dialog()
+ ok = dialog.ok('Game Blacked Out', msg)
+ return stream_url, media_auth
+
+
+ #epoch_time_now = str(int(round(time.time()*1000)))
+
+ #-------------------------
+ #Playback Scenario's
+ #-------------------------
+ '''
+ HTTP_CLOUD_WIRED
+ HTTP_CLOUD_WIRED_ADS
+ HTTP_CLOUD_WIRED_IRDETO
+ HTTP_CLOUD_WIRED_WEB
+ HTTP_CLOUD_TABLET
+ FMS_CLOUD
+ HTTP_CLOUD_WIRED_60
+ HTTP_CLOUD_WIRED_ADS_60
+ HTTP_CLOUD_WIRED_IRDETO_60
+ FLASH_500K_400X224
+ HTTP_CLOUD_AUDIO
+ AUDIO_FMS_32K
+ HTTP_CLOUD_AUDIO_TS
+
+ PS4 Calls
+ "MF": "https://mlb-ws-mf.media.mlb.com/pubajaxws/bamrest/MediaService2_0/op-findUserVerifiedEvent/v-2.3?",
+ "mfPlay": "playbackScenario={playbackScenario}&platform={platform}&contentId={contentID}&identityPointId={identityPointID}&fingerprint={fingerprint}&format=json&auth=cookie",
+ "mfCatalog": "platform={platform}&subject=LIVE_EVENT_COVERAGE&format=json&eventId={eventId}&fingerprint={fingerprint}&identityPointId={identityPointId}&auth=cookie",
+ '''
+
+ #https://mlb-ws.mlb.com/pubajaxws/bamrest/MediaService2_0/op-findUserVerifiedEvent/v-2.3?identityPointId=31998790&fingerprint=dUVQMTF5bjRrd1N4Rnp0NlVTUk5wR1NMV0E4PXwxNDU3Mzc0NjI0MDU1fGlwdD1lbWFpbC1wYXNzd29yZA==&eventId=14-469489-2016-03-07&platform=WIN8&playbackScenario=HTTP_CLOUD_AUDIO&contentId=546192183&sessionKey=&subject=LIVE_EVENT_COVERAGE
+ url = 'https://mlb-ws-mf.media.mlb.com/pubajaxws/bamrest/MediaService2_0/op-findUserVerifiedEvent/v-2.3'
+ #url = 'https://mlb-ws.mlb.com/pubajaxws/bamrest/MediaService2_0/op-findUserVerifiedEvent/v-2.3'
+ url = url + '?identityPointId='+identity_point_id
+ url = url + '&fingerprint='+fingerprint
+ url = url + '&contentId='+content_id
+ url = url + '&eventId='+event_id
+ url = url + '&playbackScenario='+playback_scenario
+ url = url + '&subject=LIVE_EVENT_COVERAGE'
+ url = url + '&sessionKey='+urllib.quote_plus(session_key)
+ url = url + '&platform=PS4'
+ url = url + '&format=json'
+ #url = url + '&frameworkURL=https%3A%2F%2Fmlb-ws-mf.media.mlb.com&frameworkEndPoint=%2Fpubajaxws%2Fbamrest%2FMediaService2_0%2Fop-findUserVerifiedEvent%2Fv-2.3'
+ #url = url + '&_='+epoch_time_now
+ req = urllib2.Request(url)
+ req.add_header("Accept", "*/*")
+ req.add_header("Accept-Encoding", "deflate")
+ req.add_header("Accept-Language", "en-US,en;q=0.8")
+ req.add_header("Connection", "keep-alive")
+ req.add_header("User-Agent", UA_PS4)
+
+ response = opener.open(req)
+ json_source = json.load(response)
+ response.close()
+
+
+
+ if json_source['status_code'] == 1:
+ uv_media_item = json_source['user_verified_event'][0]['user_verified_content'][0]['user_verified_media_item'][0]
+ if 'BLACKOUT' in str(uv_media_item ['blackout_status']).upper():
+ msg = "We're sorry. We have determined that you are blacked out of watching the game you selected due to Major League Baseball exclusivities."
+ #try:
+ if str(uv_media_item ['media_item']['state']).upper() == 'MEDIA_ARCHIVE':
+ #cc_url = str(json_source['user_verified_event'][0]['user_verified_content'][0]['domain_specific_attributes'][3]['value'])
+ for attribute in json_source['user_verified_event'][0]['user_verified_content'][0]['domain_specific_attributes']:
+ if str(attribute['name']).lower() == 'inning_index_location_xml':
+ inning_xml_url = str(attribute['value'])
+ #inning_xml_url = "http://mlb.mlb.com/mlb/mmls2016/447002.xml"
+ blackout_lift_min, blackout_lift_time = getBlackoutLiftTime(inning_xml_url)
+ msg = msg + " This blackout will expire in "+str(blackout_lift_min)+" minutes at approximately "+str(blackout_lift_time)+"."
+ break
+
+ dialog = xbmcgui.Dialog()
+ ok = dialog.ok('Game Blacked Out', msg)
+ sys.exit()
+ xbmc.executebuiltin('Dialog.Close(all,true)')
+ elif str(uv_media_item ['auth_status']) == 'NotAuthorizedStatus':
+ msg = "You do not have an active MLB.TV premium subscription. If you are using a Single Team or Free subscription please check this is enabled in the addon settings."
+ dialog = xbmcgui.Dialog()
+ ok = dialog.ok('Account Not Authorized', msg)
+ sys.exit()
+ xbmc.executebuiltin('Dialog.Close(all,true)')
+ else:
+ stream_url = uv_media_item ['url']
+ #Find subtitles
+ '''
+ for item in json_source['user_verified_event'][0]['user_verified_content'][0]['domain_specific_attributes']:
+ if item['name'] == 'closed_captions_location_ttml':
+ subtitles_url = item['value']
+ convertSubtitles(subtitles_url)
+ '''
+ session_key = json_source['session_key']
+ #Update Session Key
+ settings.setSetting(id='session_key', value=session_key)
+ else:
+ msg = json_source['status_message']
+ dialog = xbmcgui.Dialog()
+ ok = dialog.ok('Error Fetching Stream', msg)
+
+
+ for cookie in cj:
+ if cookie.name == "mediaAuth":
+ media_auth = "mediaAuth="+cookie.value
+ settings.setSetting(id='media_auth', value=media_auth)
+
+ cj.save(ignore_discard=True)
+
+ return stream_url, media_auth
+
+
+
+
+def getSessionKey(content_id,event_id,identity_point_id,fingerprint):
+ #session_key = ''
+ session_key = str(settings.getSetting(id="session_key"))
+
+ if session_key == '':
+ cj = cookielib.LWPCookieJar(os.path.join(ADDON_PATH_PROFILE, 'cookies.lwp'))
+ cj.load(os.path.join(ADDON_PATH_PROFILE, 'cookies.lwp'),ignore_discard=True)
+ opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
+
+ epoch_time_now = str(int(round(time.time()*1000)))
+ url = 'https://mlb-ws-mf.media.mlb.com/pubajaxws/bamrest/MediaService2_0/op-findUserVerifiedEvent/v-2.3'
+ url = url + '?identityPointId='+identity_point_id
+ url = url + '&fingerprint='+fingerprint
+ url = url + '&eventId='+event_id
+ url = url + '&subject=LIVE_EVENT_COVERAGE'
+ url = url + '&platform=WIN8'
+ url = url + '&frameworkURL=https://mlb-ws-mf.media.mlb.com&frameworkEndPoint=/pubajaxws/bamrest/MediaService2_0/op-findUserVerifiedEvent/v-2.3'
+ url = url + '&_='+epoch_time_now
+
+ req = urllib2.Request(url)
+ req.add_header("Accept", "*/*")
+ req.add_header("Accept-Encoding", "deflate")
+ req.add_header("Accept-Language", "en-US,en;q=0.8")
+ req.add_header("Connection", "keep-alive")
+ req.add_header("User-Agent", UA_PC)
+ req.add_header("Origin", "http://m.mlb.com")
+ req.add_header("Referer", "http://m.mlb.com/tv/e"+event_id+"/v"+content_id+"/?&media_type=video&clickOrigin=Media Grid&team=mlb&forwardUrl=http://m.mlb.com/tv/e"+event_id+"/v"+content_id+"/?&media_type=video&clickOrigin=Media%20Grid&team=mlb&template=mp5default&flowId=registration.dynaindex&mediaTypeTemplate=video")
+
+ response = opener.open(req)
+ xml_data = response.read()
+ response.close()
+
+ session_key = find(xml_data,'<session-key>','</session-key>')
+ settings.setSetting(id='session_key', value=session_key)
+
+ '''
+ if json_source['status_code'] == 1:
+ if json_source['user_verified_event'][0]['user_verified_content'][0]['user_verified_media_item'][0]['blackout_status']['status'] == 'BlackedOutStatus':
+ msg = "You do not have access to view this content. To watch live games and learn more about blackout restrictions, please visit NHL.TV"
+ session_key = 'blackout'
+ else:
+ session_key = str(json_source['session_key'])
+ settings.setSetting(id='session_key', value=session_key)
+ else:
+ msg = json_source['status_message']
+ dialog = xbmcgui.Dialog()
+ ok = dialog.ok('Error Fetching Stream', msg)
+ '''
+ return session_key
+
+
+def myTeamsGames():
+ if FAV_TEAM != 'None':
+ fav_team_id = getFavTeamId()
+
+ end_date = localToEastern()
+ end_date = stringToDate(end_date, "%Y-%m-%d")
+ start_date = end_date - timedelta(days=30)
+ start_date = start_date.strftime("%Y%m%d")
+ end_date = end_date.strftime("%Y%m%d")
+ season = start_date.strftime("%Y")
+
+
+ url = 'http://mlb.mlb.com/lookup/named.schedule_vw.bam?end_date='+end_date+'&season='+season+'&team_id='+fav_team_id+'&start_date='+start_date
+ #${expand},schedule.ticket&${optionalParams}'
+ req = urllib2.Request(url)
+ req.add_header('User-Agent', UA_IPAD)
+ response = urllib2.urlopen(req)
+ json_source = json.load(response)
+ response.close()
+
+ #<row game_pk="469406" record_source="S" game_id="2016/03/01/pitmlb-detmlb-1" game_type="S" month="3" game_date="2016-03-01T00:00:00" month_abbrev="Mar" month_full="March" day="3" day_abbrev="Tue" game_day="Tuesday" double_header_sw="N" gameday_sw="Y" interleague_sw="" game_nbr="1" series_nbr="1" series_game_nbr="1" game_time_et="2016-03-01T13:05:00" if_necessary="N" scheduled_innings="9" inning="9" top_inning_sw="N" away_team_id="134" away_all_star_sw="N" away_team_file_code="pit" away_team_city="Pittsburgh" away_team_full="Pittsburgh Pirates" away_team_brief="Pirates" away_team_abbrev="PIT" away_league_id="104" away_league="NL" away_sport_code="mlb" away_parent_id="" away_parent_org="" away_split_squad="N" home_team_id="116" home_all_star_sw="N" home_team_file_code="det" home_team_city="Detroit" home_team_full="Detroit Tigers" home_team_brief="Tigers" home_team_abbrev="DET" home_league_id="103" home_league="AL" home_sport_code="mlb" home_parent_id="" home_parent_org="" home_split_squad="N" venue_id="2511" venue="Joker Marchant Stadium" venue_short="" venue_city="Lakeland" venue_state="FL" venue_country="USA" milbtv_sw="N" home_tunein="" away_tunein="" game_time_local="3/1/2016 1:05:00 PM" time_zone_local="EST" game_time_home="3/1/2016 1:05:00 PM" time_zone_home="EST" game_time_away="3/1/2016 1:05:00 PM" time_zone_away="EST" resumed_on="" resumed_at="" resumed_from="" rescheduled_to="" rescheduled_at="" rescheduled_from="" game_status_ind="F" game_status_text="Final" reason="" home_probable_id="571510" home_probable="Boyd, Matt" home_probable_wl="0-0" home_probable_era="-.--" away_probable_id="543456" away_probable="Lobstein, Kyle" away_probable_wl="0-0" away_probable_era="-.--" home_team_wl="0-1" away_team_wl="1-0" home_score="2" away_score="4" home_result="L" away_result="W" win_pitcher_id="543746" win_pitcher="Scahill, Rob" win_pitcher_wl="1-0" win_pitcher_era="18.00" loss_pitcher_id="434137" loss_pitcher="Kensing, Logan" loss_pitcher_wl="0-1" loss_pitcher_era="18.00" editorial_stats_type="S" editorial_stats_season="2016"/>
+ match = re.compile('<row (.+?)/">').findall(link)
+
+ for game_row in match:
+
+ for game in date['games']:
+ createGameListItem(game, date['date'])
+
+
+ else:
+ msg = "Please select your favorite team from the addon settings"
+ dialog = xbmcgui.Dialog()
+ ok = dialog.ok('Favorite Team Not Set', msg)
+
+
+def login():
+ #Check if username and password are provided
+ global USERNAME
+ if USERNAME == '':
+ dialog = xbmcgui.Dialog()
+ USERNAME = dialog.input('Please enter your username', type=xbmcgui.INPUT_ALPHANUM)
+ settings.setSetting(id='username', value=USERNAME)
+
+ global PASSWORD
+ if PASSWORD == '':
+ dialog = xbmcgui.Dialog()
+ PASSWORD = dialog.input('Please enter your password', type=xbmcgui.INPUT_ALPHANUM, option=xbmcgui.ALPHANUM_HIDE_INPUT)
+ settings.setSetting(id='password', value=PASSWORD)
+
+
+ if USERNAME != '' and PASSWORD != '':
+ settings.setSetting("old_username",USERNAME)
+ settings.setSetting("old_password",PASSWORD)
+ cj = cookielib.LWPCookieJar(os.path.join(ADDON_PATH_PROFILE, 'cookies.lwp'))
+ opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
+
+ url = 'https://securea.mlb.com/authenticate.do'
+ login_data = 'uri=%2Faccount%2Flogin_register.jsp&registrationAction=identify&emailAddress='+USERNAME+'&password='+PASSWORD+'&submitButton='
+
+
+ req = urllib2.Request(url, data=login_data, headers=
+ {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
+ "Accept-Encoding": "gzip, deflate",
+ "Accept-Language": "en-US,en;q=0.8",
+ "Content-Type": "application/x-www-form-urlencoded",
+ "Origin": "https://securea.mlb.com",
+ "Connection": "keep-alive",
+ #"Cookie": "SESSION_1=wf_forwardUrl===http://m.mlb.com/tv/e14-469412-2016-03-02/v545147283/?&media_type=video&clickOrigin=Media%20Grid&team=mlb~wf_flowId===registration.dynaindex~wf_template===mp5default~wf_mediaTypeTemplate===video~stage===3~flowId===registration.dynaindex~forwardUrl===http://m.mlb.com/tv/e14-469412-2016-03-02/v545147283/?&media_type=video&clickOrigin=Media%20Grid&team=mlb;",
+ "Cookie": "SESSION_1=wf_forwardUrl%3D%3D%3Dhttp%3A%2F%2Fm.mlb.com%2Ftv%2Fe14-469412-2016-03-02%2Fv545147283%2F%3F%26media_type%3Dvideo%26clickOrigin%3DMedia%2520Grid%26team%3Dmlb%7Ewf_flowId%3D%3D%3Dregistration.dynaindex%7Ewf_template%3D%3D%3Dmp5default%7Ewf_mediaTypeTemplate%3D%3D%3Dvideo%7Estage%3D%3D%3D3%7EflowId%3D%3D%3Dregistration.dynaindex%7EforwardUrl%3D%3D%3Dhttp%3A%2F%2Fm.mlb.com%2Ftv%2Fe14-469412-2016-03-02%2Fv545147283%2F%3F%26media_type%3Dvideo%26clickOrigin%3DMedia%2520Grid%26team%3Dmlb%3B",
+ "User-Agent": UA_PC})
+
+
+
+
+ try:
+ response = opener.open(req)
+ # if url has not changed the login was not valid.
+ if response.geturl() == url:
+ msg = "Please check that your username and password are correct"
+ dialog = xbmcgui.Dialog()
+ ok = dialog.ok('Invalid Login', msg)
+ sys.exit()
+ else:
+ cj.save(ignore_discard=True);
+ except HTTPError as e:
+ xbmc.log('The server couldn\'t fulfill the request.')
+ xbmc.log('Error code: ', e.code)
+ xbmc.log(url)
+
+ #Error 401 for invalid login
+ if e.code == 401:
+ msg = "Please check that your username and password are correct"
+ dialog = xbmcgui.Dialog()
+ ok = dialog.ok('Invalid Login', msg)
+
+ #response = opener.open(req)
+ #user_data = response.read()
+ response.close()
+
+
+def logout():
+ #Just delete the cookie file
+ cookie_file = xbmc.translatePath(os.path.join(ADDON_PATH_PROFILE+'cookies.lwp'))
+ try:
+ os.remove(cookie_file)
+ except:
+ pass
+
+ settings.setSetting(id='session_key', value='')
+ dialog = xbmcgui.Dialog()
+ title = "Logout Successful"
+ dialog.notification(title, 'Logout completed successfully', ICON, 5000, False)
+
+
+
+params=get_params()
+name=None
+mode=None
+game_day=None
+event_id=None
+gid=None
+teams_stream=None
+stream_date=None
+
+try:
+ name=urllib.unquote_plus(params["name"])
+except:
+ pass
+try:
+ mode=int(params["mode"])
+except:
+ pass
+try:
+ game_day=urllib.unquote_plus(params["game_day"])
+except:
+ pass
+try:
+ event_id=urllib.unquote_plus(params["event_id"])
+except:
+ pass
+try:
+ gid=urllib.unquote_plus(params["gid"])
+except:
+ pass
+try:
+ teams_stream=urllib.unquote_plus(params["teams_stream"])
+except:
+ pass
+try:
+ stream_date=urllib.unquote_plus(params["stream_date"])
+except:
+ pass
+
+if mode==None:
+ categories()
+
+elif mode == 100:
+ #Todays Games
+ todaysGames(None)
+
+elif mode == 101:
+ #Prev and Next
+ todaysGames(game_day)
+
+elif mode == 104:
+ streamSelect(event_id, gid, teams_stream, stream_date)
+
+elif mode == 105:
+ #Yesterday's Games
+ game_day = localToEastern()
+ display_day = stringToDate(game_day, "%Y-%m-%d")
+ prev_day = display_day - timedelta(days=1)
+ todaysGames(prev_day.strftime("%Y-%m-%d"))
+
+elif mode == 200:
+ #Goto Date
+ search_txt = ''
+ dialog = xbmcgui.Dialog()
+ game_day = dialog.input('Enter date (yyyy-mm-dd)', type=xbmcgui.INPUT_ALPHANUM)
+ mat=re.match('(\d{4})-(\d{2})-(\d{2})$', game_day)
+ if mat is not None:
+ todaysGames(game_day)
+ else:
+ if game_day != '':
+ msg = "The date entered is not in the format required."
+ dialog = xbmcgui.Dialog()
+ ok = dialog.ok('Invalid Date', msg)
+
+ sys.exit()
+
+elif mode == 400:
+ logout()
+
+elif mode == 500:
+ myTeamsGames()
+
+elif mode == 900:
+ getGamesForDate(stream_date)
+ playAllHighlights()
+
+elif mode == 999:
+ sys.exit()
+
+if mode == 100:
+ xbmcplugin.endOfDirectory(addon_handle, cacheToDisc=False)
+elif mode == 101:
+ xbmcplugin.endOfDirectory(addon_handle, cacheToDisc=False, updateListing=True)
+else:
+ xbmcplugin.endOfDirectory(addon_handle) \ No newline at end of file
diff --git a/plugin.video.mlbtv/resources/__init__.py b/plugin.video.mlbtv/resources/__init__.py
new file mode 100644
index 0000000..2b620f6
--- /dev/null
+++ b/plugin.video.mlbtv/resources/__init__.py
@@ -0,0 +1 @@
+# dummy file to init directory \ No newline at end of file
diff --git a/plugin.video.mlbtv/resources/language/resource.language.en_gb/strings.po b/plugin.video.mlbtv/resources/language/resource.language.en_gb/strings.po
new file mode 100644
index 0000000..a2538c2
--- /dev/null
+++ b/plugin.video.mlbtv/resources/language/resource.language.en_gb/strings.po
@@ -0,0 +1,101 @@
+# Kodi Media Center language file
+# Addon Name: MLB.TV
+# Addon id: plugin.video.mlbtv
+# Addon Provider: eracknaphobia
+msgid ""
+msgstr ""
+"Project-Id-Version: Kodi Addons\n"
+"Report-Msgid-Bugs-To: alanwww1@xbmc.org\n"
+"POT-Creation-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
+"Last-Translator: Kodi Translation Team\n"
+"Language-Team: English (http://www.transifex.com/projects/p/xbmc-addons/language/en/)\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Language: en\n"
+"Plural-Forms: nplurals=2; plural=(n != 1);\n"
+
+msgctxt "#100"
+msgid "Login"
+msgstr ""
+
+msgctxt "#140"
+msgid "Username"
+msgstr ""
+
+msgctxt "#150"
+msgid "Password"
+msgstr ""
+
+msgctxt "#151"
+msgid "Single Team / Free Game Subscription"
+msgstr ""
+
+msgctxt "#156"
+msgid "Logout"
+msgstr ""
+
+msgctxt "#159"
+msgid "Visual"
+msgstr ""
+
+msgctxt "#160"
+msgid "Stream Quality"
+msgstr ""
+
+msgctxt "#170"
+msgid "Hide Scores"
+msgstr ""
+
+msgctxt "#1700"
+msgid "Off"
+msgstr ""
+
+msgctxt "#1701"
+msgid "On"
+msgstr ""
+
+msgctxt "#1702"
+msgid "Favorite Team Only"
+msgstr ""
+
+msgctxt "#1703"
+msgid "Live Games Only"
+msgstr ""
+
+msgctxt "#1704"
+msgid "Archive Games Only"
+msgstr ""
+
+msgctxt "#180"
+msgid "Favorite Team"
+msgstr ""
+
+msgctxt "#190"
+msgid "Display Team Name as"
+msgstr ""
+
+msgctxt "#1901"
+msgid "Team (ex. Pirates)"
+msgstr ""
+
+msgctxt "#1903"
+msgid "Abbreviated (ex. PIT)"
+msgstr ""
+
+msgctxt "#200"
+msgid "Time Format"
+msgstr ""
+
+msgctxt "#2000"
+msgid "12 Hour Clock (ex. 6:00 pm)"
+msgstr ""
+
+msgctxt "#2001"
+msgid "24 Hour Clock (ex. 18:00)"
+msgstr ""
+
+msgctxt "#700"
+msgid "Sports"
+msgstr "" \ No newline at end of file
diff --git a/plugin.video.mlbtv/resources/lib/__init__.py b/plugin.video.mlbtv/resources/lib/__init__.py
new file mode 100644
index 0000000..2b620f6
--- /dev/null
+++ b/plugin.video.mlbtv/resources/lib/__init__.py
@@ -0,0 +1 @@
+# dummy file to init directory \ No newline at end of file
diff --git a/plugin.video.mlbtv/resources/lib/globals.py b/plugin.video.mlbtv/resources/lib/globals.py
new file mode 100644
index 0000000..cd47c53
--- /dev/null
+++ b/plugin.video.mlbtv/resources/lib/globals.py
@@ -0,0 +1,550 @@
+# coding=utf-8
+import sys
+import xbmc, xbmcplugin, xbmcgui, xbmcaddon
+import re, os, time
+import calendar
+import pytz
+import urllib, urllib2
+import json
+import cookielib
+import time
+import math
+from bs4 import BeautifulSoup
+from datetime import date, datetime, timedelta
+from urllib2 import URLError, HTTPError
+from PIL import Image
+from cStringIO import StringIO
+
+
+addon_handle = int(sys.argv[1])
+
+
+#Addon Info
+ADDON = xbmcaddon.Addon()
+ADDON_ID = ADDON.getAddonInfo('id')
+ADDON_VERSION = ADDON.getAddonInfo('version')
+ADDON_PATH = xbmc.translatePath(ADDON.getAddonInfo('path'))
+ADDON_PATH_PROFILE = xbmc.translatePath(ADDON.getAddonInfo('profile'))
+XBMC_VERSION = float(re.findall(r'\d{2}\.\d{1}', xbmc.getInfoLabel("System.BuildVersion"))[0])
+LOCAL_STRING = ADDON.getLocalizedString
+ROOTDIR = xbmcaddon.Addon(id='plugin.video.mlbtv').getAddonInfo('path')
+
+#Settings
+settings = xbmcaddon.Addon(id='plugin.video.mlbtv')
+USERNAME = str(settings.getSetting(id="username"))
+PASSWORD = str(settings.getSetting(id="password"))
+OLD_USERNAME = str(settings.getSetting(id="old_username"))
+OLD_PASSWORD = str(settings.getSetting(id="old_password"))
+ROGERS_SUBSCRIBER = str(settings.getSetting(id="rogers"))
+QUALITY = str(settings.getSetting(id="quality"))
+NO_SPOILERS = settings.getSetting(id="no_spoilers")
+FAV_TEAM = str(settings.getSetting(id="fav_team"))
+TEAM_NAMES = settings.getSetting(id="team_names")
+TIME_FORMAT = settings.getSetting(id="time_format")
+SINGLE_TEAM = str(settings.getSetting(id='single_team'))
+
+
+#Colors
+SCORE_COLOR = 'FF00B7EB'
+GAMETIME_COLOR = 'FFFFFF66'
+#FAV_TEAM_COLOR = 'FFFF0000'
+FREE_GAME_COLOR = 'FF43CD80'
+
+#Game Time Colors
+UPCOMING = 'FFD2D2D2'
+LIVE = 'FFF69E20'
+CRITICAL ='FFD10D0D'
+FINAL = 'FF666666'
+FREE = 'FF43CD80'
+
+
+
+#Images
+ICON = ROOTDIR+"/icon.png"
+FANART = ROOTDIR+"/fanart.jpg"
+PREV_ICON = ROOTDIR+"/icon.png"
+NEXT_ICON = ROOTDIR+"/icon.png"
+
+if SINGLE_TEAM == 'true':
+ MASTER_FILE_TYPE = 'master_wired.m3u8'
+ PLAYBACK_SCENARIO = 'HTTP_CLOUD_WIRED'
+else:
+ MASTER_FILE_TYPE = 'master_wired60.m3u8'
+ PLAYBACK_SCENARIO = 'HTTP_CLOUD_WIRED_60'
+
+
+#User Agents
+UA_IPHONE = 'AppleCoreMedia/1.0.0.13D15 (iPhone; U; CPU OS 9_2_1 like Mac OS X; en_us)'
+UA_IPAD = 'AppleCoreMedia/1.0 ( iPad; compatible; 3ivx HLS Engine/2.0.0.382; Win8; x64; 264P AACP AC3P AESD CLCP HTPC HTPI HTSI MP3P MTKA)'
+UA_PC = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.97 Safari/537.36'
+UA_PS4 = 'PS4Application libhttp/1.000 (PS4) libhttp/3.15 (PlayStation 4)'
+UA_ATBAT = 'At Bat/13268 CFNetwork/758.2.8 Darwin/15.0.0'
+
+#Playlists
+RECAP_PLAYLIST = xbmc.PlayList(0)
+EXTENDED_PLAYLIST = xbmc.PlayList(1)
+
+
+
+def find(source,start_str,end_str):
+ start = source.find(start_str)
+ end = source.find(end_str,start+len(start_str))
+
+ if start != -1:
+ return source[start+len(start_str):end]
+ else:
+ return ''
+
+def getGameIcon(home,away):
+ #Check if game image already exists
+ image_path = ROOTDIR+'/resources/images/'+away+'vs'+home+'.png'
+ file_name = os.path.join(image_path)
+ if not os.path.isfile(file_name):
+ try:
+ createGameIcon(home,away,image_path)
+ except:
+ pass
+
+ return image_path
+
+
+def createGameIcon(home,away,image_path):
+ #bg = Image.new('RGB', (400,225), (0,0,0))
+ bg = Image.new('RGB', (500,250), (0,0,0))
+ #http://mlb.mlb.com/mlb/images/devices/240x240/110.png
+ #img_file = urllib.urlopen('http://mlb.mlb.com/mlb/images/devices/76x76/'+home+'.png ')
+ img_file = urllib.urlopen('http://mlb.mlb.com/mlb/images/devices/240x240/'+home+'.png ')
+ im = StringIO(img_file.read())
+ home_image = Image.open(im)
+ #bg.paste(home_image, (267,74), home_image)
+ bg.paste(home_image, (255,5), home_image)
+
+ #img_file = urllib.urlopen('http://mlb.mlb.com/mlb/images/devices/76x76/'+away+'.png ')
+ img_file = urllib.urlopen('http://mlb.mlb.com/mlb/images/devices/240x240/'+away+'.png ')
+ im = StringIO(img_file.read())
+ away_image = Image.open(im)
+ #bg.paste(away_image, (57,74), away_image)
+ bg.paste(away_image, (5,5), away_image)
+
+ bg.save(image_path)
+
+
+def colorString(string, color):
+ return '[COLOR='+color+']'+string+'[/COLOR]'
+
+
+def stringToDate(string, date_format):
+ try:
+ date = datetime.strptime(str(string), date_format)
+ except TypeError:
+ date = datetime(*(time.strptime(str(string), date_format)[0:6]))
+
+ return date
+
+
+def easternToLocal(eastern_time):
+ utc = pytz.utc
+ eastern = pytz.timezone('US/Eastern')
+ eastern_time = eastern.localize(eastern_time)
+ # Convert it from Eastern to UTC
+ utc_time = eastern_time.astimezone(utc)
+ timestamp = calendar.timegm(utc_time.timetuple())
+ local_dt = datetime.fromtimestamp(timestamp)
+ # Convert it from UTC to local time
+ assert utc_time.resolution >= timedelta(microseconds=1)
+ return local_dt.replace(microsecond=utc_time.microsecond)
+
+def UTCToLocal(utc_dt):
+ # get integer timestamp to avoid precision lost
+ timestamp = calendar.timegm(utc_dt.timetuple())
+ local_dt = datetime.fromtimestamp(timestamp)
+ assert utc_dt.resolution >= timedelta(microseconds=1)
+ return local_dt.replace(microsecond=utc_dt.microsecond)
+
+
+def localToEastern():
+ eastern = pytz.timezone('US/Eastern')
+ local_to_utc = datetime.now(pytz.timezone('UTC'))
+
+ eastern_hour = local_to_utc.astimezone(eastern).strftime('%H')
+ eastern_date = local_to_utc.astimezone(eastern)
+ #Don't switch to the current day until 4:01 AM est
+ if int(eastern_hour) < 3:
+ eastern_date = eastern_date - timedelta(days=1)
+
+ local_to_eastern = eastern_date.strftime('%Y-%m-%d')
+ return local_to_eastern
+
+def easternToUTC(eastern_time):
+ utc = pytz.utc
+ eastern = pytz.timezone('US/Eastern')
+ eastern_time = eastern.localize(eastern_time)
+ # Convert it from Eastern to UTC
+ utc_time = eastern_time.astimezone(utc)
+ return utc_time
+
+
+
+def get_params():
+ param=[]
+ paramstring=sys.argv[2]
+ if len(paramstring)>=2:
+ params=sys.argv[2]
+ cleanedparams=params.replace('?','')
+ if (params[len(params)-1]=='/'):
+ params=params[0:len(params)-2]
+ pairsofparams=cleanedparams.split('&')
+ param={}
+ for i in range(len(pairsofparams)):
+ splitparams={}
+ splitparams=pairsofparams[i].split('=')
+ if (len(splitparams))==2:
+ param[splitparams[0]]=splitparams[1]
+
+ return param
+
+
+
+def addStream(name,title,event_id,gid,icon=None,fanart=None,info=None,video_info=None,audio_info=None,teams_stream=None,stream_date=None):
+ ok=True
+ u=sys.argv[0]+"?mode="+str(104)+"&name="+urllib.quote_plus(name)+"&event_id="+urllib.quote_plus(str(event_id))+"&gid="+urllib.quote_plus(str(gid))+"&teams_stream="+urllib.quote_plus(str(teams_stream))+"&stream_date="+urllib.quote_plus(str(stream_date))
+
+ #if icon != None:
+ liz=xbmcgui.ListItem(name, iconImage=ICON, thumbnailImage=icon)
+ #else:
+ #liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=ICON)
+
+ if fanart != None:
+ liz.setProperty('fanart_image', fanart)
+ else:
+ liz.setProperty('fanart_image', FANART)
+
+ liz.setProperty("IsPlayable", "true")
+ liz.setInfo( type="Video", infoLabels={ "Title": title } )
+ if info != None:
+ liz.setInfo( type="Video", infoLabels=info)
+ if video_info != None:
+ liz.addStreamInfo('video', video_info)
+ if audio_info != None:
+ liz.addStreamInfo('audio', audio_info)
+
+ ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
+ xbmcplugin.setContent(addon_handle, 'episodes')
+
+ return ok
+
+
+def addLink(name,url,title,iconimage,info=None,video_info=None,audio_info=None,fanart=None):
+ ok=True
+ liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
+ liz.setProperty("IsPlayable", "true")
+ liz.setInfo( type="Video", infoLabels={ "Title": title } )
+ liz.setProperty('fanart_image', FANART)
+ #if iconimage != None:
+ liz=xbmcgui.ListItem(name, iconImage=ICON, thumbnailImage=iconimage)
+ #else:
+ #liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=ICON)
+
+ if info != None:
+ liz.setInfo( type="Video", infoLabels=info)
+ if video_info != None:
+ liz.addStreamInfo('video', video_info)
+ if audio_info != None:
+ liz.addStreamInfo('audio', audio_info)
+
+ if fanart != None:
+ liz.setProperty('fanart_image', fanart)
+ else:
+ liz.setProperty('fanart_image', FANART)
+
+ ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
+ xbmcplugin.setContent(addon_handle, 'episodes')
+ return ok
+
+
+
+
+def addDir(name,mode,iconimage,fanart=None,game_day=None):
+ ok=True
+
+ #Set day to today if none given
+ #game_day = time.strftime("%Y-%m-%d")
+ #game_day = localToEastern()
+ #game_day = '2016-01-27'
+
+ u=sys.argv[0]+"?mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&icon="+urllib.quote_plus(iconimage)
+ if game_day != None:
+ u = u+"&game_day="+urllib.quote_plus(game_day)
+
+ if iconimage != None:
+ liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
+ else:
+ liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=ICON)
+
+ liz.setInfo( type="Video", infoLabels={ "Title": name } )
+
+ if fanart != None:
+ liz.setProperty('fanart_image', fanart)
+ else:
+ liz.setProperty('fanart_image', FANART)
+
+
+ ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
+ xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
+ return ok
+
+
+def addPlaylist(name,game_day,mode,iconimage,fanart=None):
+ ok=True
+ u=sys.argv[0]+"?mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&icon="+urllib.quote_plus(iconimage)+"&stream_date="+urllib.quote_plus(str(game_day))
+
+ if iconimage != None:
+ liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
+ else:
+ liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=ICON)
+
+ liz.setInfo( type="Video", infoLabels={ "Title": name } )
+
+ if fanart != None:
+ liz.setProperty('fanart_image', fanart)
+ else:
+ liz.setProperty('fanart_image', FANART)
+
+
+ info = {'plot':'Watch all the days highlights for '+game_day,'tvshowtitle':'MLB','title':name,'originaltitle':name,'aired':game_day,'genre':LOCAL_STRING(700),'mediatype':'video'}
+ audio_info, video_info = getAudioVideoInfo()
+
+ if info != None:
+ liz.setInfo( type="Video", infoLabels=info)
+ if video_info != None:
+ liz.addStreamInfo('video', video_info)
+ if audio_info != None:
+ liz.addStreamInfo('audio', audio_info)
+
+
+ ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
+ #xbmcplugin.setContent(int(sys.argv[1]), 'episodes')
+ return ok
+
+
+def scoreUpdates():
+ #http://gdx.mlb.com/components/game/mlb/year_2016/month_03/day_08/miniscoreboard.json
+ #grid.poll=15
+ #s = ScoreThread()
+ t = threading.Thread(target = scoringUpdates)
+ t.start()
+
+def getFavTeamColor():
+ #Hex code taken from http://teamcolors.arc90.com/
+ team_colors = {'Arizona Diamondbacks':'FFA71930',
+ 'Atlanta Braves':'FFCE1141',
+ 'Baltimore Orioles':'FFDF4601',
+ 'Boston Red Sox':'FFBD3039',
+ 'Chicago Cubs':'FFCC3433',
+ 'Chicago White Sox':'FFC4CED4',
+ 'Cincinnati Reds':'FFC6011F',
+ 'Cleveland Indians':'FFE31937',
+ 'Colorado Rockies':'FFC4CED4',
+ 'Detroit Tigers':'FF0C2C56',
+ 'Houston Astros':'FFEB6E1F',
+ 'Kansas City Royals':'FFC09A5B',
+ 'Los Angeles Angels':'FFBA0021',
+ 'Los Angeles Dodgers':'FFEF3E42',
+ 'Miami Marlins':'FFFF6600',
+ 'Milwaukee Brewers':'FFB6922E',
+ 'Minnesota Twins':'FFD31145',
+ 'New York Mets':'FFFF5910',
+ 'New York Yankees':'FFE4002B',
+ 'Oakland Athletics':'FFEFB21E',
+ 'Philadelphia Phillies':'FFE81828',
+ 'Pittsburgh Pirates':'FFFDB827',
+ 'St. Louis Cardinals':'FFC41E3A',
+ 'San Diego Padres':'FF05143F',
+ 'San Francisco Giants':'FFFD5A1E',
+ 'Seattle Mariners':'FFC4CED4',
+ 'Tampa Bay Rays':'FF8FBCE6',
+ 'Texas Rangers':'FFC0111F',
+ 'Toronto Blue Jays':'FFE8291C',
+ 'Washington Nationals':'FFAB0003'}
+
+
+ fav_team_color = team_colors[FAV_TEAM]
+
+ return fav_team_color
+
+
+def getFavTeamId():
+ #possibly use the xml file in the future
+ #http://mlb.mlb.com/shared/properties/mlb_properties.xml
+ team_ids = {'Arizona Diamondbacks':'109',
+ 'Atlanta Braves':'144',
+ 'Baltimore Orioles':'110',
+ 'Boston Red Sox':'111',
+ 'Chicago Cubs':'112',
+ 'Chicago White Sox':'145',
+ 'Cincinnati Reds':'113',
+ 'Cleveland Indians':'114',
+ 'Colorado Rockies':'115',
+ 'Detroit Tigers':'116',
+ 'Houston Astros':'117',
+ 'Kansas City Royals':'118',
+ 'Los Angeles Angels':'108',
+ 'Los Angeles Dodgers':'119',
+ 'Miami Marlins':'146',
+ 'Milwaukee Brewers':'158',
+ 'Minnesota Twins':'142',
+ 'New York Mets':'121',
+ 'New York Yankees':'147',
+ 'Oakland Athletics':'133',
+ 'Philadelphia Phillies':'143',
+ 'Pittsburgh Pirates':'134',
+ 'St. Louis Cardinals':'138',
+ 'San Diego Padres':'135',
+ 'San Francisco Giants':'137',
+ 'Seattle Mariners':'136',
+ 'Tampa Bay Rays':'139',
+ 'Texas Rangers':'140',
+ 'Toronto Blue Jays':'141',
+ 'Washington Nationals':'120'}
+
+ fav_team_id = team_ids[FAV_TEAM]
+
+ return fav_team_id
+
+def getAudioVideoInfo():
+ #SD (800 kbps)|SD (1600 kbps)|HD (3000 kbps)|HD (5000 kbps)
+ if QUALITY == 'SD (800 kbps)':
+ video_info = { 'codec': 'h264', 'width' : 512, 'height' : 288, 'aspect' : 1.78 }
+ elif QUALITY == 'SD (1200 kbps)':
+ video_info = { 'codec': 'h264', 'width' : 640, 'height' : 360, 'aspect' : 1.78 }
+ else:
+ #elif QUALITY == 'HD (2500 kbps)' or QUALITY == 'HD (3500 kbps)' or QUALITY == 'HD (5000 kbps)':
+ video_info = { 'codec': 'h264', 'width' : 1280, 'height' : 720, 'aspect' : 1.78 }
+
+ audio_info = { 'codec': 'aac', 'language': 'en', 'channels': 2 }
+ return audio_info, video_info
+
+def getConfigFile():
+ '''
+ GET http://lwsa.mlb.com/partner-config/config?company=sony-tri&type=nhl&productYear=2015&model=PS4&firmware=default&app_version=1_0 HTTP/1.0
+ Host: lwsa.mlb.com
+ User-Agent: PS4Application libhttp/1.000 (PS4) libhttp/3.15 (PlayStation 4)
+ Connection: close
+ '''
+ url = 'http://lwsa.mlb.com/partner-config/config?company=sony-tri&type=nhl&productYear=2015&model=PS4&firmware=default&app_version=1_0'
+ req = urllib2.Request(url)
+ req.add_header("Connection", "close")
+ req.add_header("User-Agent", UA_PS4)
+
+ response = urllib2.urlopen(req, '')
+ json_source = json.load(response)
+ response.close()
+
+
+def convertSubtitles(suburl):
+ #suburl = subtitles url
+ #xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, xbmcgui.ListItem(path = url))
+
+ #if ((addon.getSetting('sub_enable') == "true"):
+ subfile = xbmc.translatePath(os.path.join(ADDON_PATH_PROFILE, 'game_subtitles.srt'))
+ prodir = xbmc.translatePath(os.path.join(ADDON_PATH_PROFILE))
+ if not os.path.isdir(prodir):
+ os.makedirs(prodir)
+
+ #pg = getRequest(suburl)
+ response = urllib.urlopen(suburl)
+ pg = response.read()
+ response.close()
+ if pg != "":
+ ofile = open(subfile, 'w+')
+ #need to adjust for subtitles not starting until 18 hours into the stream
+ #<p begin='18:00:08;29' end='18:00:35;23'>&gt;&gt;&gt;</p>
+ captions = re.compile("<p begin='(.+?)' end='(.+?)'>(.+?)</p>").findall(pg)
+ idx = 1
+ for cstart, cend, caption in captions:
+ cstart = cstart.replace('.',',')
+ cend = cend.replace('.',',').split('"',1)[0]
+ caption = caption.replace('<br/>','\n').replace('&gt;','>')
+ ofile.write( '%s\n%s --> %s\n%s\n\n' % (idx, cstart, cend, caption))
+ idx += 1
+ ofile.close()
+
+ return subfile
+
+
+def getStreamQuality(stream_url):
+ stream_title = []
+ req = urllib2.Request(stream_url)
+ response = urllib2.urlopen(req)
+ master = response.read()
+ response.close()
+
+ line = re.compile("(.+?)\n").findall(master)
+
+ for temp_url in line:
+ if '.m3u8' in temp_url:
+ temp_url = temp_url
+ match = re.search(r'(\d.+?)K', temp_url)
+ if match:
+ bandwidth = match.group()
+ if 0 < len(bandwidth) < 6:
+ bandwidth = bandwidth.replace('K',' kbps')
+ stream_title.append(bandwidth)
+
+
+ stream_title.sort(key=natural_sort_key,reverse=True)
+ dialog = xbmcgui.Dialog()
+ ret = dialog.select('Choose Stream Quality', stream_title)
+ if ret >=0:
+ bandwidth = find(stream_title[ret],'',' kbps')
+ else:
+ sys.exit()
+
+ return bandwidth
+
+def natural_sort_key(s):
+ _nsre = re.compile('([0-9]+)')
+ return [int(text) if text.isdigit() else text.lower()
+ for text in re.split(_nsre, s)]
+
+def getBlackoutLiftTime(url):
+ #"http://mediadownloads.mlb.com/ttml/2016/04/14/584182283.ttml"
+ #url = 'http://mediadownloads.mlb.com/ttml/2016/04/14/584182283.ttml'
+ req = urllib2.Request(url)
+ req.add_header('Connection', 'close')
+ req.add_header('User-Agent', UA_IPAD)
+ try:
+ response = urllib2.urlopen(req)
+ xml_data = response.read()
+ response.close()
+ except HTTPError as e:
+ xbmc.log('The server couldn\'t fulfill the request.')
+ xbmc.log('Error code: ', e.code)
+ sys.exit()
+
+
+ #<p begin="19:59:16;28" end="19:59:20;06">PRESENTED BY THE ALLEGHENY HEALTH NETWORK.</p>
+ #match = re.compile("<p begin='(.+?)' end='(.+?)'>",re.DOTALL).findall(xml_data)
+ match = re.compile('<inningTime type="SCAST" start="(.+?)" end="(.+?)"/>',re.DOTALL).findall(xml_data)
+
+ last_end_time = ''
+ for begin_time, end_time in match:
+ last_end_time = end_time
+
+
+ #ex 19:59:20;06
+ game_end_time = datetime.strptime(last_end_time,'%H:%M:%S')
+ blackout_lift_time = game_end_time + timedelta(minutes = 90)
+ now = datetime.strptime(datetime.utcnow().strftime('%H:%M:%S'),'%H:%M:%S')
+
+ minutes_until_lift = int(math.ceil((blackout_lift_time - now).total_seconds() / 60))
+ lift_time = datetime.utcnow() + timedelta(minutes = minutes_until_lift)
+ local_lift_time = UTCToLocal(lift_time)
+
+ if TIME_FORMAT == '0':
+ local_lift_time = local_lift_time.strftime('%I:%M %p').lstrip('0')
+ else:
+ local_lift_time = local_lift_time.strftime('%H:%M')
+
+ return minutes_until_lift, local_lift_time
+ \ No newline at end of file
diff --git a/plugin.video.mlbtv/resources/settings.xml b/plugin.video.mlbtv/resources/settings.xml
new file mode 100644
index 0000000..2b6512b
--- /dev/null
+++ b/plugin.video.mlbtv/resources/settings.xml
@@ -0,0 +1,27 @@
+<?xml version="1.0" encoding="utf-8" standalone="yes"?>
+<settings>
+ <!--Login-->
+ <category label="100">
+ <setting id="username" type="text" label="140" default=""/>
+ <setting id="password" type="text" label="150" option="hidden" default=""/>
+ <setting id="single_team" type="bool" label="151" default="false"/>
+ <setting label="156" type="action" action="RunPlugin(plugin://plugin.video.mlbtv/?url=junk&mode=400)" option="close" />
+ <!-- <setting label="156" type="action" action="RunScript(special://home/addons/plugin.video.nhlgcl/resources/lib/logout.py)" option="close" /> -->
+ </category>
+ <category label="159">
+ <setting id="quality" type="labelenum" label="160" values="SD (450 kbps)|SD (800 kbps)|SD (1200 kbps)|SD (1800 kbps)|HD (2500 kbps)|HD (3500 kbps)|HD (5000 kbps)|Best Available|Always Ask" default="HD (5000 kbps)" />
+ <setting id="no_spoilers" type="enum" label="170" lvalues="1700|1701|1702|1703|1704" />
+ <setting id="fav_team" type="labelenum" label="180" default="None" values="None|Washington Nationals|Toronto Blue Jays|Texas Rangers|Tampa Bay Rays|St. Louis Cardinals|Seattle Mariners|San Francisco Giants|San Diego Padres|Pittsburgh Pirates|Philadelphia Phillies|Oakland Athletics|New York Yankees|New York Mets|Minnesota Twins|Milwaukee Brewers|Los Angeles Dodgers|Los Angeles Angels|Kansas City Royals|Miami Marlins|Houston Astros|Detroit Tigers|Colorado Rockies|Cleveland Indians|Cincinnati Reds|Chicago White Sox|Chicago Cubs|Boston Red Sox|Baltimore Orioles|Atlanta Braves|Arizona Diamondbacks" />
+
+ <setting id="team_names" type="select" label="1901" lvalues="1901|1903" default="0" />
+ <setting id="time_format" type="select" label="200" lvalues="2000|2001" default="0" />
+
+ <setting id="stream_date" type="text" label="900" default="" visible="false"/>
+ <setting id="session_key" type="text" label="902" default="" visible="false"/>
+ <setting id="media_auth" type="text" label="903" default="" visible="false"/>
+
+ <setting id="old_username" type="text" label="" default="" visible="false"/>
+ <setting id="old_password" type="text" label="" default="" visible="false"/>
+ </category>
+</settings>
+