Advertisement
Guest User

default.py

a guest
Aug 17th, 2015
424
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 15.57 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. import xbmc, xbmcgui, xbmcplugin, xbmcaddon, xbmcvfs
  3. import sys, os, random, json, zlib
  4. import urllib, urllib2, cookielib
  5. import re, base64
  6. from watched import *
  7. from array import *
  8. from htmlentitydefs import name2codepoint as n2cp
  9. import htmlentitydefs
  10. # new since v0.95
  11. import urlresolver
  12. # new since 1.3.0
  13. from player import bsPlayer
  14.  
  15. thisPlugin = int(sys.argv[1])
  16. dialog = xbmcgui.Dialog()
  17. addonInfo = xbmcaddon.Addon()
  18. hosterList = xbmcplugin.getSetting(thisPlugin,"hosterlist").lower()
  19. serienOrdner = xbmcplugin.getSetting(thisPlugin, 'seriespath')
  20. thumbUrl = addonInfo.getAddonInfo('path')+"/resources/img/"
  21.  
  22. urlHost = "http://bs.to/api/"
  23. urlPics = "http://s.bs.to/img/cover/"
  24.  
  25. # --------------
  26. # main functions
  27. # --------------
  28.  
  29. def showContent(sortType):
  30.     global thisPlugin
  31.     print "[bs][showContent] started"
  32.     seriesList = {}
  33.     serie =[]
  34.     picture = ""
  35.     try:
  36.         if sortType[0] == "A":
  37.             data = getUrl(urlHost+"series")
  38.         if sortType[0] == "G":
  39.             data = getUrl(urlHost+"series:genre")
  40.     except Exception:
  41.         addDirectoryItem("! a problem with website or network !", {"kindOf":0, "sortType": "A"})
  42.         return
  43.     print "[bs][showContent] -- some init data"
  44.     print "[bs][showContent] len(data): "+str(len(data))
  45.     print "[bs][showContent] sortType: "+sortType
  46.     if sortType[0] == "A":
  47.         # -- alphabetical order --
  48.         jsonContent = json.loads(data)
  49.         for d in jsonContent:
  50.             serie = ["[B]"+d['series'].strip()+"[/B]",d['series'],d['id']]
  51.             helper = ord(d['series'][0])
  52.             if helper>90:
  53.                 helper = helper-32
  54.             if (helper>64) and (helper<91):
  55.                 lKey = chr(helper).upper()
  56.             else:
  57.                 lKey = "0"
  58.             if lKey in seriesList:
  59.                 seriesList[lKey].append(serie)
  60.             else:
  61.                 seriesList[lKey] = []
  62.                 seriesList[lKey].append(serie)
  63.            
  64.     if sortType[0] == "G":
  65.         # -- sort by genre --
  66.         jsonContent = json.loads(data)
  67.         for d,dv in jsonContent.iteritems():
  68.             if sortType[0] == "G":
  69.                 for ks in dv['series']:
  70.                     #print ks['name'].encode('utf-8')
  71.                     serie = [d+" : [B]"+ks['name'].strip()+"[/B]",ks['name'],ks['id']]
  72.                     lKey = d
  73.                     if lKey in seriesList:
  74.                         seriesList[lKey].append(serie)
  75.                     else:
  76.                         seriesList[lKey] = []
  77.                         seriesList[lKey].append(serie)
  78.    
  79.     if len(sortType)==1:
  80.         # -- if only A or G show list of series --
  81.         addDirectoryItem(".sort by Alphabet", {"kindOf":0, "sortType": "A"})
  82.         addDirectoryItem(".sort by Genre", {"kindOf":0, "sortType": "G"})
  83.         addDirectoryItem("", {"kindOf":0, "sortType": "A"})
  84.         for key in sorted(seriesList):
  85.             picture = thumbUrl+key+".jpg"
  86.             skey = key
  87.             if key =="0":
  88.                 skey = "0-9 etc"
  89.             addDirectoryItem("[B]"+skey.encode('utf-8')+"[/B] (%d)" % len(seriesList[key]), {"kindOf":0, "sortType": sortType+key.encode('utf-8')},picture)
  90.     else:
  91.         # -- show subset for A or G --
  92.         # -- example AD shows all series with D
  93.         # -- example GAnimation shows all Series in Animation
  94.         sortType = sortType.decode('utf-8')    
  95.         sKey = sortType[1:]
  96.         for s in sorted(seriesList[sKey], key=lambda f:f[0]):
  97.             seriesName = s[0]
  98.             picture = urlPics+str(s[2])+'.jpg|encoding=gzip'
  99.             print picture
  100.             # check if watched
  101.             if readWatchedData(s[1].encode('utf-8')):
  102.                 seriesName = changeToWatched(seriesName)
  103.             addDirectoryItem(seriesName, {"kindOf":1, "name": s[1].encode('utf-8'), "id":s[2],"doFav":"0"},picture)
  104.     print "[bs][showContent] --- ok"   
  105.     xbmcplugin.endOfDirectory(thisPlugin)
  106.  
  107. # changed
  108. def showSeasons(n, id):
  109.     global thisPlugin
  110.     cover = urlPics+str(id)+'.jpg|encoding=gzip'
  111.     name = n.decode('utf-8')
  112.     print "[bs][showSeasons] started"
  113.     addDirectoryItem("[B]. "+name.encode('utf-8')+"[/B]", {},cover)
  114.     addDirectoryItem("[B]* add to Library[/B]", {"kindOf":"add2lib",'name': name.encode('utf-8'), 'id': str(id)},cover)
  115.     season = 0
  116.     seasonWatched = 0
  117.     while True:
  118.         data = json.loads(getUrl(urlHost+"series/"+str(id)+"/"+str(season)))
  119.         print "[bs][showSeasons] reading seasons"
  120.         if data.has_key('error'):
  121.             if season == 0:
  122.                     season = 1
  123.                     continue
  124.             else:
  125.                     break
  126.         if season == 0:
  127.                 seasonName = "[B] Film(e) [/B]"
  128.         else:
  129.                 seasonName = "[B] Staffel"+str(season)+"[/B]"
  130.         if readWatchedData((name+"/"+str(season)).encode('utf-8')):
  131.             seasonWatched += 1
  132.             seasonName = changeToWatched(seasonName.encode('utf-8'))
  133.         if data.has_key('series'):
  134.             addDirectoryItem(seasonName, {"kindOf":2, "name":data['series']['series'].encode('utf-8'), "id":id, "season":season},cover)
  135.         season+=1
  136.     if seasonWatched == season:
  137.         markParentEntry(name.encode('utf-8'))
  138.     print "[bs][showSeasons] --- ok"    
  139.     xbmcplugin.endOfDirectory(thisPlugin)
  140.  
  141. # changed
  142. def showEpisodes(n,id,season):
  143.     global thisPlugin
  144.     name = n.decode('utf-8')   
  145.     episodesWatched = 0
  146.     cover = urlPics+str(id)+'.jpg|encoding=gzip'
  147.     if season == 0:
  148.             # FIXME: directory name is "Staffel 0"
  149.         addDirectoryItem("[B]. "+name.encode('utf-8')+" Film(e) [/B]", {},cover)
  150.     else:
  151.         addDirectoryItem("[B]. "+name.encode('utf-8')+" Staffel "+str(season)+"[/B]", {},cover)
  152.     print "[bs][showEpisodes] started with "+name.encode('utf-8')
  153.     data = json.loads(getUrl(urlHost+"series/"+str(id)+"/"+str(season)))
  154.     for d in data['epi']:
  155.         episodeName = "#"+str(d['epi'])
  156.         if 'german' in d:
  157.             episodeName += " "+d['german']
  158.         if 'english' in d:
  159.             if not d['english']=='':
  160.                 episodeName += " ("+d['english']+")"
  161.         print episodeName.encode('utf-8')
  162.         episodeName_watched = episodeName
  163.         if readWatchedData((name+"/"+str(season)+"/"+str(d['epi'])).encode('utf-8')):
  164.             episodesWatched += 1
  165.             episodeName_watched = changeToWatched(episodeName)
  166.         addDirectoryItem(episodeName_watched, {"kindOf": 3, "name":data['series']['series'].encode('utf-8'), "id":id, "season":season, "episode":d['epi'],"episodename":episodeName.encode('utf-8')},cover)
  167.     # if watched all episodes, mark Season
  168.     if episodesWatched == len(data['epi']):
  169.         markParentEntry(name.encode('utf-8')+"/"+str(season))
  170.     print "[bs][showEpisodes] ok"  
  171.     xbmcplugin.endOfDirectory(thisPlugin)
  172.  
  173. def showHosts(n, id, season,episode,episodeName):
  174.     global thisPlugin
  175.     n = name.decode('utf-8')
  176.     matchCover = ""
  177.     cover = urlPics+str(id)+'.jpg|encoding=gzip'
  178.     addDirectoryItem("[B]."+name+" Staffel "+str(season)+" "+str(episode)+"[/B]", {},cover)
  179.     addDirectoryItem("[B]."+episodeName+"[/B]", {},cover)
  180.     data = json.loads(getUrl(urlHost+"series/"+str(id)+"/"+str(season)+"/"+str(episode)))
  181.     for d in data['links']:
  182.         if d['hoster'].lower() in hosterList:
  183.             showVideo(d['id'],data['series'].encode('utf8'),season,episode)
  184.             break
  185.         addDirectoryItem("Host: "+d['hoster'], {"kindOf":4, "vid":d['id'], "name": data['series'].encode("utf-8"),"season": season, "episode":episode},matchCover)
  186.     print "[bs][showHosts] ok" 
  187.     xbmcplugin.endOfDirectory(thisPlugin)
  188.    
  189. def showVideo(vid, n,season,episode):
  190.     global thisPlugin
  191.     name = n.decode('utf-8')
  192.     print "[bs][showVideo] started on "+name.encode('utf8')+"/"+season+"/"+episode+" - "+str(vid)
  193.     data = json.loads(getUrl(urlHost+"watch/"+str(vid)))
  194.     videoLink = urlresolver.resolve(data['fullurl']);
  195.     print "[bs][showVideo] urlResolver returns - "
  196.     print videoLink
  197.     if videoLink:
  198.         item = xbmcgui.ListItem(path=videoLink)
  199.         bsPlayer().playStream(videoLink, name.encode('utf-8'),season,episode)
  200.     else:
  201.         addDirectoryItem("ERROR. Video deleted or urlResolver cant handle Host", {"urlV": "/"})
  202.         xbmcplugin.endOfDirectory(thisPlugin)
  203.  
  204. def straightPlay(id,season,episode):
  205.     global thisPlugin
  206.     thisUrl = urlHost+"series/"+str(id)+"/"+str(season)+"/"+str(episode)
  207.     print "[bs][straightPlay] thisUrl: "+thisUrl
  208.     episodeData = getUrl(thisUrl)
  209.     print episodeData
  210.     episodeJSON = json.loads(episodeData)
  211.     series = episodeJSON['series']
  212.     allHoster = []
  213.     for d in episodeJSON['links']:
  214.         hoster = d['hoster']
  215.         hEntry = {"hoster":hoster,"id":str(d['id'])}
  216.         if hoster.lower() in hosterList:
  217.             hEntry['hoster'] = "-"+hEntry['hoster']
  218.             allHoster.append(hEntry)
  219.         else:
  220.             allHoster.append(hEntry)
  221.     sortedHoster = sorted(allHoster,key=lambda k: k['hoster'])
  222.    
  223.     print "[bs][straightPlay] sortedHoster: ",sortedHoster
  224.     for sortedH in sortedHoster:   
  225.         streamData = getUrl(urlHost+"watch/"+str(sortedH['id']))
  226.         streamJSON = json.loads(streamData)
  227.         fullurl = streamJSON['fullurl']
  228.         print "[bs][straightPlay] fullurl: "+fullurl
  229.         videoLink = urlresolver.resolve(fullurl)
  230.         if videoLink:
  231.             print "[bs][straightPlay] playing: "+videoLink
  232.             li = xbmcgui.ListItem (series.encode('utf-8'), path=videoLink)
  233.             xbmcplugin.setResolvedUrl(thisPlugin, True, li)
  234.             break
  235.         else:
  236.             print "[bs][straightPlay] escaping: "+sortedH['hoster']+" - video url null"
  237.  
  238. # --------------------
  239. # -- add to library -- hints from movieserver.addon - jin - thx
  240. # --------------------
  241. def add2Library(n,id):
  242.     global thisPlugin
  243.     print "[bs][add2Lib] creating Data for "+n
  244.     newName = simplifyName(n)
  245.     print type(newName),newName
  246.     print serienOrdner
  247.     folder = os.path.join(serienOrdner,newName)
  248.     print "[bs][add2Lib] Folder "+folder
  249.     season = 0
  250.     while True:
  251.         season += 1
  252.         seasonData = getUrl(urlHost+"series/"+str(id)+"/"+str(season))
  253.         seasonJSON = json.loads(seasonData)
  254.         if 'error' in seasonJSON:
  255.             break
  256.         seasonName = "[B]Staffel"+str(season)+"[/B]"
  257.         if seasonJSON.has_key('series'):
  258.             episodeUrl = urlHost+"series/"+str(id)+"/"+str(season)
  259.             episodeData = getUrl(episodeUrl)
  260.             episodeJSON = json.loads(episodeData)
  261.             for d in episodeJSON['epi']:
  262.                 episode = d['epi']
  263.                 newFile = newName+"_s"+str(season)+"e"+str(episode)+".strm"
  264.                 print "[bs][add2Lib] creating: "+newFile
  265.                 try:
  266.                     parameters = {"kindOf": "straightPlay", "id":id, "season":season, "episode":episode}
  267.                     pluginCall = sys.argv[0] + '?' + urllib.urlencode(parameters)
  268.                     strmFile = os.path.join(serienOrdner,newName,newFile)
  269.                     create_strm_file(strmFile,str(pluginCall))
  270.                 except Exception:
  271.                     continue
  272.     print "[bs][add2Lib] ended"
  273.    
  274. def create_strm_file(strm,strmentry):
  275.     if not xbmcvfs.exists(os.path.dirname(strm)):
  276.         try:
  277.             xbmcvfs.mkdirs(os.path.dirname(strm))
  278.         except:
  279.             xbmc.executebuiltin('[bs][libEntry] Notification(Info: Konnte keinen Ordner erstellen!,)')
  280.             return
  281.     old_strmentry = ''
  282.     try:
  283.         f = xbmcvfs.File(strm, 'r')
  284.         old_strmentry = f.read()
  285.         f.close()
  286.     except:
  287.         pass
  288.     if strmentry != old_strmentry:
  289.         try:
  290.             file_desc = xbmcvfs.File(strm, 'w')
  291.             file_desc.write(strmentry)
  292.             file_desc.close()
  293.         except:
  294.             xbmc.executebuiltin('[bs][libENtry] Notification(Info: Konnte keine Datei erstellen!,)')       
  295.  
  296. def simplifyName(s):
  297.     # because mostly used by german rewrite umlaut
  298.     s = s.replace("ä","ae")
  299.     s = s.replace("ö","oe")
  300.     s = s.replace("ü","ue")
  301.     s = s.replace("ß","ss")
  302.     s = s.replace(" ","_")
  303.     astr = s.decode('utf-8').encode("ascii",'ignore')
  304.     astr = astr.replace("/","_")
  305.     astr = astr.replace("\\","_")
  306.     astr = astr.replace(".","_")
  307.     astr = astr.replace("*","_")
  308.     astr = astr.replace("?","_")
  309.     astr = astr.replace(":","_")
  310.     return astr
  311.  
  312. # --------------
  313. # --- helper ---
  314. # --------------
  315.  
  316. def is_number(s):
  317.     try:
  318.         float(s)
  319.         return True
  320.     except ValueError:
  321.         return False
  322.  
  323. def baseN(num,b,numerals="0123456789abcdefghijklmnopqrstuvwxyz"):
  324.     return ((num == 0) and numerals[0]) or (baseN(num // b, b, numerals).lstrip(numerals[0]) + numerals[num % b])
  325.  
  326. def getUrl(url):
  327.     try:
  328.         req = urllib2.Request(url)
  329.         req.add_header('User-Agent', 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3')
  330.         req.add_header('Accept-encoding', 'gzip')
  331.         response = urllib2.urlopen(req)
  332.         if response.info().get('Content-Encoding') == 'gzip':
  333.             d = zlib.decompressobj(16+zlib.MAX_WBITS)
  334.             return d.decompress(response.read())
  335.         else:
  336.             return response.read()
  337.         response.close()
  338.     except:
  339.         return False
  340.  
  341. def addDirectoryItem(name, parameters={},pic=""):
  342.     iconpic = pic
  343.     if pic == "":
  344.         iconpic = "DefaultFolder.png"
  345.     li = xbmcgui.ListItem(name,iconImage=iconpic, thumbnailImage=pic)
  346.     u = sys.argv[0] + '?' + urllib.urlencode(parameters)
  347.     return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=li, isFolder=True)
  348.  
  349. def addPlayableItem(name, parameters={},pic=""):
  350.     iconpic = pic
  351.     if pic == "":
  352.         iconpic = "DefaultFolder.png"
  353.     li = xbmcgui.ListItem(name,iconImage=iconpic, thumbnailImage=pic)
  354.     li.setProperty("IsPlayable","true")
  355.     u = sys.argv[0] + '?' + urllib.urlencode(parameters)
  356.     return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=li, isFolder=False)
  357.  
  358.    
  359. def parameters_string_to_dict(parameters):
  360.     ''' Convert parameters encoded in a URL to a dict. '''
  361.     paramDict = {}
  362.     if parameters:
  363.         paramPairs = parameters[1:].split("&")
  364.         for paramsPair in paramPairs:
  365.             paramSplits = paramsPair.split('=')
  366.             if (len(paramSplits)) == 2:
  367.                 paramDict[paramSplits[0]] = paramSplits[1]
  368.     return paramDict
  369.  
  370. def unescape(text):
  371.     def fixup(m):
  372.         text = m.group(0)
  373.         if text[:2] == "&#":
  374.             # character reference
  375.             try:
  376.                 if text[:3] == "&#x":
  377.                     return unichr(int(text[3:-1], 16))
  378.                 else:
  379.                     return unichr(int(text[2:-1]))
  380.             except ValueError:
  381.                 pass
  382.         else:
  383.             # named entity
  384.             try:
  385.                 text = unichr(htmlentitydefs.name2codepoint[text[1:-1]])
  386.             except KeyError:
  387.                 pass
  388.         return text # leave as is
  389.     return re.sub("&#?\w+;", fixup, unicode(text, "UTF-8"), re.UNICODE)
  390.    
  391.  
  392. # ----------------
  393. # ----- main -----
  394. # ----------------
  395.  
  396. params = parameters_string_to_dict(sys.argv[2])
  397.  
  398. #showFavs = str(params.get("showFavs",""))
  399. kindOf = str(params.get("kindOf",""))
  400. sortType = str(params.get("sortType", ""))
  401. name = str(params.get("name", ""))
  402. id = str(params.get("id", ""))
  403. season = str(params.get("season", ""))
  404. episode = str(params.get("episode", ""))
  405. episodename = str(params.get("episodename", ""))
  406. vid = str(params.get("vid", ""))
  407.  
  408. print "[bs][init] show params"
  409. print params
  410.  
  411. if not params.has_key('kindOf'):    # -- init start --
  412.     kindOf = "0"
  413.     sortType = "A"
  414.  
  415. if kindOf=="0":                     # -- show Series --
  416.     sortType = urllib.unquote(sortType)
  417.     ok = showContent(sortType)
  418. if kindOf=="1":                     # -- showSeasons --
  419.     name = urllib.unquote(name)
  420.     id = urllib.unquote(id)
  421.     ok = showSeasons(name, id)
  422. if kindOf=="2":                     # -- showEpisodes --
  423.     name = urllib.unquote(name)
  424.     id = urllib.unquote(id)
  425.     season = urllib.unquote(season)
  426.     ok = showEpisodes(name, id, season)
  427. if kindOf=="3":                     # -- showHosts --
  428.     name = urllib.unquote(name)
  429.     id = urllib.unquote(id)
  430.     season = urllib.unquote(season)
  431.     episode = urllib.unquote(episode)
  432.     episodename = urllib.unquote(episodename)
  433.     ok = showHosts(name, id, season, episode, episodename)
  434. if kindOf=="4":                     # -- showVideo --
  435.     vid = urllib.unquote(vid)
  436.     name = urllib.unquote(name)
  437.     season = urllib.unquote(season)
  438.     episode = urllib.unquote(episode)
  439.     ok = showVideo(vid,name,season,episode)
  440. if kindOf == "add2lib":
  441.     name = urllib.unquote(name)
  442.     id = urllib.unquote(id)
  443.     ok = add2Library(name, id)
  444.     ok = dialog.notification("add 2 Library", name+" finished.", xbmcgui.NOTIFICATION_INFO,4000)
  445.     ok = showSeasons(name,id)
  446. if kindOf == "straightPlay":
  447.     id = urllib.unquote(id)
  448.     season = urllib.unquote(season)
  449.     episode = urllib.unquote(episode)
  450.     ok = straightPlay(id,season,episode)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement