divingmule

LiveStreams Addon Mod.

Jul 26th, 2012
134
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 18.06 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. # *  This Program is free software; you can redistribute it and/or modify
  4. # *  it under the terms of the GNU General Public License as published by
  5. # *  the Free Software Foundation; either version 2, or (at your option)
  6. # *  any later version.
  7. # *
  8. # *  This Program is distributed in the hope that it will be useful,
  9. # *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # *  GNU General Public License for more details.
  12. # *
  13. # *  You should have received a copy of the GNU General Public License.
  14. # *  If not, write to the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  15. # *  http://www.gnu.org/copyleft/gpl.html
  16. # *
  17. # *  7/26/2012
  18. # *  This is a modified version of LiveStreams-1.0.5 addon default.py - http://forum.xbmc.org/showthread.php?tid=97116
  19. # *  You can use this to make your own add-on using a single xml file. See lines 37, 467-470.
  20. # *     Have fun, divingmule.
  21.  
  22. import urllib
  23. import urllib2
  24. import datetime
  25. import re
  26. import os
  27. import xbmcplugin
  28. import xbmcgui
  29. import xbmcaddon
  30. import xbmcvfs
  31. from BeautifulSoup import BeautifulStoneSoup, BeautifulSoup, BeautifulSOAP
  32. try:
  33.     import json
  34. except:
  35.     import simplejson as json
  36.  
  37. # change the addon id in the next line to match the addon.xml and the addon directory/folder
  38. addon = xbmcaddon.Addon(id='plugin.CHANGE.ME')
  39. profile = addon.getAddonInfo('profile').decode('utf-8')
  40. home = addon.getAddonInfo('path').decode('utf-8')
  41. favorites = xbmc.translatePath(os.path.join(profile, 'favorites' )).decode('utf-8')
  42. icon = xbmc.translatePath(os.path.join(home, 'icon.png'))
  43. fanart = xbmc.translatePath(os.path.join(home, 'fanart.jpg'))
  44. if os.path.exists(favorites)==True:
  45.     FAV = open(favorites).read()
  46.  
  47. def makeRequest(url):
  48.         try:
  49.             req = urllib2.Request(url)
  50.             response = urllib2.urlopen(req)
  51.             data = response.read()
  52.             response.close()
  53.             return data
  54.         except urllib2.URLError, e:
  55.             if hasattr(e, 'code'):
  56.                 print 'We failed with error code - %s.' % e.code
  57.                 xbmc.executebuiltin("XBMC.Notification(LiveStreams,We failed with error code - "+str(e.code)+",10000,"+icon+")")
  58.             elif hasattr(e, 'reason'):
  59.                 print 'We failed to reach a server.'
  60.                 print 'Reason: ', e.reason
  61.                 xbmc.executebuiltin("XBMC.Notification(LiveStreams,We failed to reach a server. - "+str(e.reason)+",10000,"+icon+")")
  62.  
  63.  
  64. def getSoup(url):
  65.         if url.startswith('http://'):
  66.             data = makeRequest(url)
  67.         else:
  68.             if xbmcvfs.exists(url):
  69.                 if url.startswith("smb://"):
  70.                     copy = xbmcvfs.copy( url, xbmc.translatePath(os.path.join(profile, 'temp', 'sorce_temp.txt')))
  71.                     if copy:
  72.                         data = open( xbmc.translatePath(os.path.join(profile, 'temp', 'sorce_temp.txt')), "r").read()
  73.                         xbmcvfs.delete( xbmc.translatePath(os.path.join(profile, 'temp', 'sorce_temp.txt')) )
  74.                     else:
  75.                         print "--- failed to copy from smb: ----"
  76.                 else:
  77.                     data = open(url, 'r').read()
  78.             else:
  79.                 print "---- Soup Data not found! ----"
  80.                 return
  81.         soup = BeautifulSOAP(data, convertEntities=BeautifulStoneSoup.XML_ENTITIES)
  82.         return soup
  83.  
  84.  
  85. def getData(url,fanart):
  86.         soup = getSoup(url)
  87.         if len(soup('channels')) > 0:
  88.             channels = soup('channel')
  89.             for channel in channels:
  90.                 name = channel('name')[0].string
  91.                 thumbnail = channel('thumbnail')[0].string
  92.                 if thumbnail == None:
  93.                     thumbnail = ''
  94.  
  95.                 try:
  96.                     if not channel('fanart'):
  97.                         if addon.getSetting('use_thumb') == "true":
  98.                             fanArt = thumbnail
  99.                         else:
  100.                             fanArt = fanart
  101.                     else:
  102.                         fanArt = channel('fanart')[0].string
  103.                     if fanArt == None:
  104.                         raise
  105.                 except:
  106.                     fanArt = fanart
  107.  
  108.                 try:
  109.                     desc = channel('info')[0].string
  110.                     if desc == None:
  111.                         raise
  112.                 except:
  113.                     desc = ''
  114.  
  115.                 try:
  116.                     genre = channel('genre')[0].string
  117.                     if genre == None:
  118.                         raise
  119.                 except:
  120.                     genre = ''
  121.  
  122.                 try:
  123.                     date = channel('date')[0].string
  124.                     if date == None:
  125.                         raise
  126.                 except:
  127.                     date = ''
  128.                 try:
  129.                     addDir(name.encode('utf-8', 'ignore'),url.encode('utf-8'),2,thumbnail,fanArt,desc,genre,date)
  130.                 except:
  131.                     print 'There was a problem adding directory from getData(): '+name.encode('utf-8', 'ignore')
  132.         else:
  133.             getItems(soup('item'),fanart)
  134.  
  135.  
  136. def getChannelItems(name,url,fanart):
  137.         soup = getSoup(url)
  138.         channel_list = soup.find('channel', attrs={'name' : name})
  139.         items = channel_list('item')
  140.         try:
  141.             fanArt = channel_list('fanart')[0].string
  142.             if fanArt == None:
  143.                 raise
  144.         except:
  145.             fanArt = fanart
  146.         for channel in channel_list('subchannel'):
  147.             name = channel('name')[0].string
  148.             try:
  149.                 thumbnail = channel('thumbnail')[0].string
  150.                 if thumbnail == None:
  151.                     raise
  152.             except:
  153.                 thumbnail = ''
  154.             try:
  155.                 if not channel('fanart'):
  156.                     if addon.getSetting('use_thumb') == "true":
  157.                         fanArt = thumbnail
  158.                 else:
  159.                     fanArt = channel('fanart')[0].string
  160.                 if fanArt == None:
  161.                     raise
  162.             except:
  163.                 pass
  164.             try:
  165.                 desc = channel('info')[0].string
  166.                 if desc == None:
  167.                     raise
  168.             except:
  169.                 desc = ''
  170.  
  171.             try:
  172.                 genre = channel('genre')[0].string
  173.                 if genre == None:
  174.                     raise
  175.             except:
  176.                 genre = ''
  177.  
  178.             try:
  179.                 date = channel('date')[0].string
  180.                 if date == None:
  181.                     raise
  182.             except:
  183.                 date = ''
  184.             try:
  185.                 addDir(name.encode('utf-8', 'ignore'),url.encode('utf-8'),3,thumbnail,fanArt,desc,genre,date)
  186.             except:
  187.                 print 'There was a problem adding directory - '+name.encode('utf-8', 'ignore')
  188.         getItems(items,fanArt)
  189.  
  190.  
  191. def getSubChannelItems(name,url,fanart):
  192.         soup = getSoup(url)
  193.         channel_list = soup.find('subchannel', attrs={'name' : name})
  194.         items = channel_list('subitem')
  195.         getItems(items,fanart)
  196.  
  197.  
  198. def getItems(items,fanart):
  199.         for item in items:
  200.             try:
  201.                 name = item('title')[0].string
  202.             except:
  203.                 print '-----Name Error----'
  204.                 name = ''
  205.             try:
  206.                 if item('epg'):
  207.                     if item('epg')[0].string > 1:
  208.                         name += getepg(item('epg')[0].string)
  209.                 else:
  210.                     pass
  211.             except:
  212.                 print '----- EPG Error ----'
  213.  
  214.             try:
  215.                 url = []
  216.                 for i in item('link'):
  217.                     url.append(i.string)
  218.             except:
  219.                 print '---- URL Error Passing ----'+name
  220.                 continue
  221.  
  222.             try:
  223.                 thumbnail = item('thumbnail')[0].string
  224.                 if thumbnail == None:
  225.                     raise
  226.             except:
  227.                 thumbnail = ''
  228.             try:
  229.                 if not item('fanart'):
  230.                     if addon.getSetting('use_thumb') == "true":
  231.                         fanArt = thumbnail
  232.                     else:
  233.                         fanArt = fanart
  234.                 else:
  235.                     fanArt = item('fanart')[0].string
  236.                 if fanArt == None:
  237.                     raise
  238.             except:
  239.                 fanArt = fanart
  240.             try:
  241.                 desc = item('info')[0].string
  242.                 if desc == None:
  243.                     raise
  244.             except:
  245.                 desc = ''
  246.  
  247.             try:
  248.                 genre = item('genre')[0].string
  249.                 if genre == None:
  250.                     raise
  251.             except:
  252.                 genre = ''
  253.  
  254.             try:
  255.                 date = item('date')[0].string
  256.                 if date == None:
  257.                     raise
  258.             except:
  259.                 date = ''
  260.             try:
  261.                 if len(url) > 1:
  262.                     alt = 0
  263.                     playlist = []
  264.                     for i in url:
  265.                         playlist.append(i)
  266.                     for i in url:
  267.                         alt += 1
  268.                         addLink(i,'%s) %s' %(str(alt), name.encode('utf-8', 'ignore')),thumbnail,fanArt,desc,genre,date,True,playlist)
  269.                 else:
  270.                     addLink(url[0],name.encode('utf-8', 'ignore'),thumbnail,fanArt,desc,genre,date,True)
  271.             except:
  272.                 print 'There was a problem adding link - '+name.encode('utf-8', 'ignore')
  273.  
  274.  
  275. def get_params():
  276.         param=[]
  277.         paramstring=sys.argv[2]
  278.         if len(paramstring)>=2:
  279.             params=sys.argv[2]
  280.             cleanedparams=params.replace('?','')
  281.             if (params[len(params)-1]=='/'):
  282.                 params=params[0:len(params)-2]
  283.             pairsofparams=cleanedparams.split('&')
  284.             param={}
  285.             for i in range(len(pairsofparams)):
  286.                 splitparams={}
  287.                 splitparams=pairsofparams[i].split('=')
  288.                 if (len(splitparams))==2:
  289.                     param[splitparams[0]]=splitparams[1]
  290.         return param
  291.  
  292.  
  293. def getFavorites():
  294.         for i in json.loads(open(favorites).read()):
  295.             name = i[0]
  296.             url = i[1]
  297.             iconimage = i[2]
  298.             try:
  299.                 fanArt = i[3]
  300.                 if fanArt == None:
  301.                     raise
  302.             except:
  303.                 if addon.getSetting('use_thumb') == "true":
  304.                     fanArt = iconimage
  305.                 else:
  306.                     fanArt = fanart
  307.             addLink(url,name,iconimage,fanArt,'','','')
  308.  
  309.  
  310. def addFavorite(name,url,iconimage,fanart):
  311.         favList = []
  312.         if os.path.exists(favorites)==False:
  313.             print 'Making Favorites File'
  314.             favList.append((name,url,iconimage,fanart))
  315.             a = open(favorites, "w")
  316.             a.write(json.dumps(favList))
  317.             a.close()
  318.         else:
  319.             print 'Appending Favorites'
  320.             a = open(favorites).read()
  321.             data = json.loads(a)
  322.             data.append((name,url,iconimage,fanart))
  323.             b = open(favorites, "w")
  324.             b.write(json.dumps(data))
  325.             b.close()
  326.  
  327.  
  328. def rmFavorite(name):
  329.         a = open(favorites).read()
  330.         data = json.loads(a)
  331.         for index in range(len(data)):
  332.             if data[index][0]==name:
  333.                 del data[index]
  334.                 b = open(favorites, "w")
  335.                 b.write(json.dumps(data))
  336.                 b.close()
  337.                 return
  338.  
  339.  
  340. def play_playlist(name, list):
  341.         playlist = xbmc.PlayList(1)
  342.         playlist.clear()
  343.         item = 0
  344.         for i in list:
  345.             item += 1
  346.             info = xbmcgui.ListItem('%s) %s' %(str(item),name))
  347.             playlist.add(i, info)
  348.         xbmc.executebuiltin('playlist.playoffset(video,0)')
  349.  
  350.  
  351. def addDir(name,url,mode,iconimage,fanart,description,genre,date,showcontext=True):
  352.         u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&fanart="+urllib.quote_plus(fanart)
  353.         ok=True
  354.         liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
  355.         liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot": description, "Genre": genre, "Date": date } )
  356.         liz.setProperty( "Fanart_Image", fanart )
  357.         # if showcontext == True:
  358.             # try:
  359.                 # if name in str(SOURCES):
  360.                     # contextMenu = [('Remove from Sources','XBMC.Container.Update(%s?mode=8&name=%s)' %(sys.argv[0], urllib.quote_plus(name)))]
  361.                     # liz.addContextMenuItems(contextMenu, True)
  362.             # except:
  363.                 # pass
  364.         ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
  365.         return ok
  366.  
  367.  
  368. def addLink(url,name,iconimage,fanart,description,genre,date,showcontext=True,playlist=None):
  369.         u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode=12"
  370.         ok=True
  371.         liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
  372.         liz.setInfo( type="Video", infoLabels={ "Title": name, "Plot": description, "Genre": genre, "Date": date } )
  373.         liz.setProperty( "Fanart_Image", fanart )
  374.         liz.setProperty('IsPlayable', 'true')
  375.         if showcontext:
  376.             try:
  377.                 if name in FAV:
  378.                     contextMenu = [('Remove from LiveStreams Favorites','XBMC.Container.Update(%s?mode=6&name=%s)' %(sys.argv[0], urllib.quote_plus(name)))]
  379.                 else:
  380.                     contextMenu = [('Add to LiveStreams Favorites','XBMC.Container.Update(%s?mode=5&name=%s&url=%s&iconimage=%s&fanart=%s)' %(sys.argv[0], urllib.quote_plus(name), urllib.quote_plus(url), urllib.quote_plus(iconimage), urllib.quote_plus(fanart)))]
  381.             except:
  382.                 contextMenu = [('Add to LiveStreams Favorites','XBMC.Container.Update(%s?mode=5&name=%s&url=%s&iconimage=%s&fanart=%s)' %(sys.argv[0], urllib.quote_plus(name), urllib.quote_plus(url), urllib.quote_plus(iconimage), urllib.quote_plus(fanart)))]
  383.             liz.addContextMenuItems(contextMenu)
  384.         if not playlist is None:
  385.             playlist_name = name.split(') ')[1]
  386.             contextMenu_ = [('Play '+playlist_name+' PlayList','XBMC.RunPlugin(%s?mode=13&name=%s&playlist=%s)' %(sys.argv[0], urllib.quote_plus(playlist_name), urllib.quote_plus(str(playlist).replace(',','|'))))]
  387.             liz.addContextMenuItems(contextMenu_)
  388.         ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz)
  389.         return ok
  390.  
  391.  
  392.   # Thanks to daschacka, an epg scraper for http://i.teleboy.ch/programm/station_select.php - http://forum.xbmc.org/showpost.php?p=936228&postcount=1076
  393. def getepg(link):
  394.         url=urllib.urlopen(link)
  395.         source=url.read()
  396.         url.close()
  397.         source2 = source.split("Jetzt")
  398.         source3 = source2[1].split('programm/detail.php?const_id=')
  399.         sourceuhrzeit = source3[1].split('<br /><a href="/')
  400.         nowtime = sourceuhrzeit[0][40:len(sourceuhrzeit[0])]
  401.         sourcetitle = source3[2].split("</a></p></div>")
  402.         nowtitle = sourcetitle[0][17:len(sourcetitle[0])]
  403.         nowtitle = nowtitle.replace("ö","oe")
  404.         nowtitle = nowtitle.replace("ä","ae")
  405.         nowtitle = nowtitle.replace("ü","ue")
  406.         return "  - "+nowtitle+" - "+nowtime
  407.  
  408.  
  409. xbmcplugin.setContent(int(sys.argv[1]), 'movies')
  410. try:
  411.     xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_UNSORTED)
  412. except:
  413.     pass
  414. try:
  415.     xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)
  416. except:
  417.     pass
  418. try:
  419.     xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_DATE)
  420. except:
  421.     pass
  422. try:
  423.     xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_GENRE)
  424. except:
  425.     pass
  426.  
  427. params=get_params()
  428.  
  429. url=None
  430. name=None
  431. mode=None
  432. playlist=None
  433.  
  434. try:
  435.     url=urllib.unquote_plus(params["url"]).decode('utf-8')
  436. except:
  437.     pass
  438. try:
  439.     name=urllib.unquote_plus(params["name"])
  440. except:
  441.     pass
  442. try:
  443.     iconimage=urllib.unquote_plus(params["iconimage"])
  444. except:
  445.     pass
  446. try:
  447.     fanart=urllib.unquote_plus(params["fanart"])
  448. except:
  449.     pass
  450. try:
  451.     mode=int(params["mode"])
  452. except:
  453.     pass
  454. try:
  455.     playlist=eval(urllib.unquote_plus(params["playlist"]).replace('|',','))
  456. except:
  457.     pass
  458.  
  459. print "Mode: "+str(mode)
  460. if not url is None:
  461.     print "URL: "+str(url.encode('utf-8'))
  462. print "Name: "+str(name)
  463.  
  464.  
  465. if mode==None:
  466.     print "getData"
  467.     # if using a remote file uncomment the following line
  468.     # data = 'http://path/to/file.xml'
  469.     # if using a local file uncomment the following line
  470.     # data = os.path.join(home, 'my.xml')
  471.     getData(data, fanart)
  472.  
  473. elif mode==2:
  474.     print "getChannelItems"
  475.     getChannelItems(name,url,fanart)
  476.  
  477. elif mode==3:
  478.     print ""
  479.     getSubChannelItems(name,url,fanart)
  480.  
  481. elif mode==4:
  482.     print ""
  483.     getFavorites()
  484.  
  485. elif mode==5:
  486.     print ""
  487.     try:
  488.         name = name.split('\\ ')[1]
  489.     except:
  490.         pass
  491.     try:
  492.         name = name.split('  - ')[0]
  493.     except:
  494.         pass
  495.     addFavorite(name,url,iconimage,fanart)
  496.  
  497. elif mode==6:
  498.     print "rmFavorite"
  499.     try:
  500.         name = name.split('\\ ')[1]
  501.     except:
  502.         pass
  503.     try:
  504.         name = name.split('  - ')[0]
  505.     except:
  506.         pass
  507.     rmFavorite(name)
  508.  
  509. elif mode==7:
  510.     print "addSource"
  511.     addSource(url)
  512.  
  513. elif mode==8:
  514.     print "rmSource"
  515.     rmSource(name)
  516.  
  517. elif mode==9:
  518.     print "getUpdate"
  519.     getUpdate()
  520.  
  521. elif mode==10:
  522.     print "getCommunitySources"
  523.     getCommunitySources()
  524.  
  525. elif mode==11:
  526.     print "addSource"
  527.     addSource(url)
  528.  
  529. elif mode==12:
  530.     print "setResolvedUrl"
  531.     item = xbmcgui.ListItem(path=url)
  532.     xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, item)
  533.  
  534. elif mode==13:
  535.     print "play_playlist"
  536.     play_playlist(name, playlist)
  537.  
  538. xbmcplugin.endOfDirectory(int(sys.argv[1]))
Advertisement
Add Comment
Please, Sign In to add comment