Advertisement
Guest User

Untitled

a guest
Mar 26th, 2012
608
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.54 KB | None | 0 0
  1. #!/usr/bin/python
  2. #
  3. #
  4. # Written by Ksosez, with massive help from Bluecop
  5. # Released under GPL(v2)
  6.  
  7. import urllib, urllib2, xbmcplugin, xbmcaddon, xbmcgui, string, htmllib, os, platform, random, calendar, re
  8. from datetime import date, timedelta
  9. from BeautifulSoup import BeautifulStoneSoup as Soup
  10.  
  11.  
  12. ## Get the settings
  13.  
  14. selfAddon = xbmcaddon.Addon(id='plugin.video.espn3')
  15. cbrowser=selfAddon.getSetting('browser')
  16. if cbrowser is '' or cbrowser is None:
  17. # Default to Firefox
  18. cbrowser = "Firefox"
  19. usexbmc = selfAddon.getSetting('watchinxbmc')
  20. defaultimage = 'special://home/addons/plugin.video.espn3/icon.png'
  21. if usexbmc is '' or usexbmc is None:
  22. usexbmc = True
  23.  
  24. def CATEGORIES():
  25. mode = 1
  26. addDir('Live', 'http://espn.go.com/espn3/feeds/live', mode, defaultimage)
  27. addDir('Replay - By Sport', 'http://espn3.passportproject.org/', 2,
  28. defaultimage)
  29. addDir('Replay - Previous 10 Days', 'http://espn3.passportproject.org/10_days.xml', mode,
  30. defaultimage)
  31. addDir('Upcoming', 'http://sports-ak.espn.go.com/espn3/feeds/upcoming', mode,
  32. defaultimage)
  33.  
  34. # print pluginhandle
  35. xbmcplugin.endOfDirectory(int(sys.argv[1]))
  36.  
  37. def INDEX(url):
  38. if "upcoming" in url or "replay" in url:
  39. addDir("Today", "", 1, defaultimage)
  40. html = get_html(url)
  41. soup = Soup(html)
  42. tomadded = 0 # set for headers in indexing later
  43. nextdayadded = 0
  44. savedate = date.today()
  45. for event in soup.findAll('event'):
  46. msg_attrs = dict(event.attrs)
  47. eventname = str(event.find('name'))
  48. if len(eventname) < 5: # Ignore the first instance which is broken
  49. pass
  50. else:
  51. if "upcoming" in url or "live" in url:
  52. reventname = string.split(string.split(eventname, "[")[2], "]]")[0]
  53. else:
  54. reventname = string.split(string.split(eventname, ">")[1], "<")[0]
  55. eventid = str(msg_attrs[u'id'])
  56. league = string.split(string.split(str(event.find('league')), ">")[1], "<")[0]
  57. sport = event.find('sport')
  58. eventedt =string.split(string.split(str(event.find('starttime')),">")[1], "<")[0]
  59. eyear = eventedt[0:4]
  60. emonth = eventedt[4:6]
  61. eday = eventedt[6:8]
  62. etime = eventedt[8:12]
  63. if "upcoming" in url:
  64. today = date.today()
  65. edate = date(int(eyear),int(emonth),int(eday))
  66. tom = today.replace(day=today.day+1)
  67. nextday = today.replace(day=today.day+2)
  68. diffdate = date(int(eyear),int(emonth),int(eday)) - date.today()
  69.  
  70. if edate == today:
  71. pass
  72. elif edate == tom and tomadded != 1:
  73. addDir("Tomorrow", "special://home/addons/plugin.video.espn3/icon.png", 1, defaultimage)
  74. tomadded = 1
  75. elif edate == nextday and nextdayadded != 1:
  76. addDir(nextday.strftime("%A - %B %d, %Y"), "special://home/addons/plugin.video.espn3/icon.png", 1, defaultimage)
  77. nextdayadded = 1
  78. else:
  79. pass
  80.  
  81. if diffdate < timedelta(days=3):
  82. # Only print the next 2 days
  83. sport = string.split(string.split(str(sport), ">")[1], "<")[0]
  84. etime = ampm(etime)
  85. name = etime + " EDT" + ":" + reventname + ":" + sport + ":" + league
  86. rurl = "http://espn.go.com/espn3/player?id=%s&league=%s" % (eventid, urllib.quote(league))
  87. print rurl
  88. mode = 4
  89. rthumbnail = event.find('thumbnail')
  90. sthumbnail = string.split(string.split(str(rthumbnail), "<small>")[1], "</small>")[0]
  91. sthumbnail = string.split(string.split(sthumbnail, "[")[2], "]]")[0]
  92. if sthumbnail < 5:
  93. thumbnail = "special://home/addons/plugin.video.espn3/icon.png"
  94. else:
  95. thumbnail = sthumbnail
  96. addLink(name, rurl, mode, thumbnail)
  97. else:
  98. pass
  99. elif "live" in url:
  100. ## Live
  101. sport = string.split(string.split(str(sport), ">")[1], "<")[0]
  102. etime = ampm(etime)
  103. name = etime + " EDT:" + reventname + ":" + sport + ":" + league
  104. rurl = "http://espn.go.com/espn3/player?id=%s&league=%s" % (eventid, urllib.quote(league))
  105. print rurl
  106. mode = 4
  107. rthumbnail = event.find('thumbnail')
  108. sthumbnail = string.split(string.split(str(rthumbnail), "<small>")[1], "</small>")[0]
  109. sthumbnail = string.split(string.split(sthumbnail, "[")[2], "]]")[0]
  110. if sthumbnail < 5:
  111. thumbnail = "special://home/addons/plugin.video.espn3/icon.png"
  112. else:
  113. thumbnail = sthumbnail
  114. addLink(name, rurl, mode, thumbnail)
  115. else:
  116. # Everything else to Index
  117. edate = date(int(eyear),int(emonth),int(eday))
  118. #diffdate = date.today() - date(int(eyear),int(emonth),int(eday))
  119. if "10_days" in url:
  120. if edate == savedate:
  121. pass
  122. elif edate != savedate:
  123. try:
  124. savedate = savedate.replace(day=savedate.day-1)
  125. except ValueError:
  126. try:
  127. savedate = savedate.replace(month=savedate.month-1)
  128. savedate = savedate.replace(day=calendar.monthrange(savedate.year,savedate.month)[1])
  129. except ValueError:
  130. savedate = savedate.replace(year=savedate.year-1)
  131. savedate = savedate.replace(month=12)
  132. savedate = savedate.replace(day=31)
  133.  
  134. addDir(savedate.strftime("%A - %B %d, %Y"), "special://home/addons/plugin.video.espn3/icon.png", 1, defaultimage)
  135.  
  136. else:
  137. pass
  138. else:
  139. if savedate != edate:
  140. addDir(edate.strftime("%A - %B %d, %Y"), "special://home/addons/plugin.video.espn3/icon.png", 1, defaultimage)
  141. else:
  142. pass
  143. savedate = edate
  144. sport = string.split(string.split(str(sport), ">")[1], "<")[0]
  145. etime = ampm(etime)
  146. name = etime + " EDT" + ":" + reventname + ":" + sport + ":" + league
  147. rurl = "http://espn.go.com/espn3/player?id=%s&league=%s" % (eventid, urllib.quote(league))
  148. print rurl
  149. mode = 4
  150. rthumbnail = event.find('thumbnail')
  151. sthumbnail = string.split(string.split(str(rthumbnail), "<small>")[1], "</small>")[0]
  152. #sthumbnail = string.split(string.split(sthumbnail, "[")[2], "]]")[0]
  153. if sthumbnail < 5:
  154. thumbnail = "special://home/addons/plugin.video.espn3/icon.png"
  155. else:
  156. thumbnail = sthumbnail
  157. addLink(name, rurl, mode, thumbnail)
  158.  
  159.  
  160. def REPLAYBYSPORT(url):
  161. html = get_html(url)
  162. match = re.compile('<img src="/icons/text.gif" alt="\[TXT\]"> <a href="(.+?)">(.+?)</a>').findall(html)
  163. for gurl,name in match:
  164. if gurl == '10_days.xml':
  165. pass
  166. else:
  167. realurl = "http://espn3.passportproject.org/%s" % gurl
  168. name = string.split(unescape(name), ".")[0]
  169. name = name.replace("_", " ")
  170. name = name.title()
  171. mode = 1
  172. addDir(name,realurl, mode, defaultimage)
  173.  
  174.  
  175.  
  176.  
  177. def PLAY(url):
  178. #Make startupevent url from page url
  179. print url
  180. startUrl = 'http://espn.go.com/espn3/feeds/startupEvent?'+url.split('?')[1]+'&gameId=null&sportCode=null'
  181. #Get eventid, bamContentId, and bamEventId from starturl data
  182. html = get_html(startUrl)
  183. if html == False:
  184. dialog = xbmcgui.Dialog()
  185. dialog.ok("Failure to Launch URL", "Unable to launch video feed most likely", "because you already requested this feed.", "Please wait a while and try again.")
  186. else:
  187. event = Soup(html)('event')[1]
  188. eventid = event['id']
  189. bamContentId = event['bamcontentid']
  190. bamEventId = event['bameventid']
  191.  
  192.  
  193. #Make identityPointId from userdata
  194. userdata = 'http://broadband.espn.go.com/espn3/auth/userData'
  195. html = get_html(userdata)
  196. soup = Soup(html)
  197. affiliateid = '"Put your <name> from userdata.xml here"'
  198. swid = '"Put your <swid> from userdata.xml here"'
  199. identityPointId = affiliateid+':'+swid
  200. req.add_header('Cookie',
  201. 'SWID="Put your <swid> from userdata.xml here"')
  202.  
  203. #Use eventid, bamContentId, bamEventId, and identityPointId to get smil url and auth data
  204. authurl = 'https://espn-ws.bamnetworks.com/pubajaxws/bamrest/MediaService2_0/op-findUserVerifiedEvent/v-2.1'
  205. authurl += '?platform=WEB_MEDIAPLAYER'
  206. authurl += '&playbackScenario=FMS_CLOUD'
  207. authurl += '&eventId='+bamEventId
  208. authurl += '&contentId='+bamContentId
  209. authurl += '&rand='+str(random.random())+'0000'
  210. authurl += '&cdnName=PRIMARY_AKAMAI'
  211. authurl += '&partnerContentId='+eventid
  212. authurl += '&identityPointId='+identityPointId
  213. authurl += '&playerId=domestic'
  214. html = get_html(authurl)
  215. smilurl = Soup(html).findAll('url')[0].string
  216. auth = smilurl.split('?')[1]
  217.  
  218. #Grab smil url to get rtmp url and playpath
  219. html = get_html(smilurl)
  220. soup = Soup(html)
  221. print soup.prettify()
  222. rtmp = soup.findAll('meta')[0]['base']
  223. #live selects stream quality
  224. #200000,400000,800000,1200000,1800000
  225. # 0, 1, 2, 3, 4
  226. # Lowest, Low, Medium, High, Highest
  227. #Change the [4] to 0-4 to change the bitrate
  228. if 'ondemand' in rtmp:
  229. replayquality = selfAddon.getSetting('replayquality')
  230. playpath = soup.findAll('video')[3]['src']
  231. finalurl = rtmp+'/?'+auth+' playpath='+playpath
  232. elif 'live' in rtmp:
  233. livequality = selfAddon.getSetting('livequality')
  234. playpath = soup.findAll('video')[4]['src']
  235. finalurl = rtmp+' live=1 playlist=1 subscribe='+playpath+' playpath='+playpath+'?'+auth
  236. item = xbmcgui.ListItem(path=finalurl)
  237. return xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
  238.  
  239. def PLAYBROWSER(url):
  240. print "Play URL:%s" % url
  241. psystem = platform.system()
  242. if cbrowser == "Chrome":
  243. if psystem == "Darwin":
  244. cmd = 'open -a /Applications/Chrome.app %s' % url
  245. elif psystem == "Linux":
  246. cmd = "/usr/bin/google-chrome %s" % url
  247. elif psystem == "Windows":
  248. cmd = "chrome.exe %s" % url
  249. else:
  250. print "Aint no browser here"
  251. else:
  252. if psystem == "Darwin":
  253. cmd = 'open -a /Applications/Firefox.app %s' % url
  254. elif psystem == "Linux":
  255. cmd = "/usr/bin/firefox %s" % url
  256. elif psystem == "Windows":
  257. cmd = '"C:\Program Files\Mozilla Firefox\firefox.exe" %s' % url
  258. else:
  259. print "Aint no browser here"
  260.  
  261. os.system(cmd)
  262.  
  263. # subprocess.call(['open -a /Applications/Firefox.app'])
  264.  
  265.  
  266. def get_html(url):
  267. req = urllib2.Request(url)
  268. req.add_header('User-Agent',
  269. 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
  270. req.add_header('Cookie',
  271. 'SWID=XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX')
  272. try:
  273. response = urllib2.urlopen(req)
  274. html = response.read()
  275. response.close()
  276. except urllib2.HTTPError:
  277. response = False
  278. html = False
  279. return html
  280.  
  281. def get_params():
  282. param = []
  283. paramstring = sys.argv[2]
  284. if len(paramstring) >= 2:
  285. params = sys.argv[2]
  286. cleanedparams = params.replace('?', '')
  287. if (params[len(params) - 1] == '/'):
  288. params = params[0:len(params) - 2]
  289. pairsofparams = cleanedparams.split('&')
  290. param = {}
  291. for i in range(len(pairsofparams)):
  292. splitparams = {}
  293. splitparams = pairsofparams[i].split('=')
  294. if (len(splitparams)) == 2:
  295. param[splitparams[0]] = splitparams[1]
  296.  
  297. return param
  298.  
  299.  
  300. def addLink(name, url, mode, iconimage):
  301. u = sys.argv[0] + "?url=" + urllib.quote_plus(url) + "&mode=" + str(mode) + "&name=" + urllib.quote_plus(name)
  302. ok = True
  303. liz = xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
  304. liz.setInfo(type="Video", infoLabels={"Title": name})
  305. liz.setProperty('IsPlayable', 'true')
  306. ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz)
  307. return ok
  308.  
  309.  
  310. def addDir(name, url, mode, iconimage):
  311. u = sys.argv[0] + "?url=" + urllib.quote_plus(url) + "&mode=" + str(mode) + "&name=" + urllib.quote_plus(name)
  312. ok = True
  313. liz = xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
  314. liz.setInfo(type="Video", infoLabels={"Title": name})
  315. ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True)
  316. return ok
  317.  
  318. def unescape(s):
  319. p = htmllib.HTMLParser(None)
  320. p.save_bgn()
  321. p.feed(s)
  322. return p.save_end()
  323.  
  324. def ampm(etime):
  325. if int(etime) >= 1300:
  326. etime = int(etime) - 1200
  327. etime = str(etime) + "PM"
  328. elif 1200 <= int(etime) < 1300:
  329. etime = str(etime) + "PM"
  330. else:
  331. etime = etime + "AM"
  332. return etime
  333.  
  334. params = get_params()
  335. url = None
  336. name = None
  337. mode = None
  338. cookie = None
  339.  
  340. try:
  341. url = urllib.unquote_plus(params["url"])
  342. except:
  343. pass
  344. try:
  345. name = urllib.unquote_plus(params["name"])
  346. except:
  347. pass
  348. try:
  349. mode = int(params["mode"])
  350. except:
  351. pass
  352.  
  353. print "Mode: " + str(mode)
  354. print "URL: " + str(url)
  355. print "Name: " + str(name)
  356.  
  357. if mode == None or url == None or len(url) < 1:
  358. print "Generate Main Menu"
  359. CATEGORIES()
  360. elif mode == 1:
  361. print "Indexing Videos"
  362. INDEX(url)
  363. elif mode == 2:
  364. print "Indexing Replay by Sport"
  365. REPLAYBYSPORT(url)
  366.  
  367. elif mode == 4:
  368. print "Play Video"
  369. if usexbmc == True or usexbmc == "true":
  370. PLAY(url)
  371. else:
  372. PLAYBROWSER(url)
  373.  
  374. #elif mode =="categories":
  375. # print "Category: Categories"
  376. # CATEGORIES(url)
  377. ##elif mode =="search":
  378. ## print "Category: Search"
  379. # SEARCH(url, mode)
  380. #else:
  381. # print ""+url
  382. # INDEX(url)
  383.  
  384.  
  385.  
  386. xbmcplugin.endOfDirectory(int(sys.argv[1]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement