Guest User

Untitled

a guest
May 28th, 2018
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 41.70 KB | None | 0 0
  1. #!/usr/bin/python
  2. #IceLibrary v0.9.6 - Batch 2011-9-15
  3. #With some code borrowed from Icefilms.info v1.0.10 - anarchintosh / daledude / westcoast13 2011-07-02
  4.  
  5. import urllib2, urllib, sys, os, re, random, copy, shutil
  6. import xbmc,xbmcplugin,xbmcgui,xbmcaddon
  7. import threading
  8. import trace
  9. from mega import megaroutines
  10. from BeautifulSoup import BeautifulSoup, Tag, NavigableString
  11.  
  12. ADDON = xbmcaddon.Addon(id='plugin.video.icelibrary')
  13. USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
  14. DATA_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.icelibrary'), '')
  15.  
  16. if ADDON.getSetting('movie_custom_directory') == "true":
  17.     MOVIES_PATH = ADDON.getSetting('movie_directory')
  18. else:
  19.     MOVIES_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.icelibrary/movies'), '')
  20.  
  21. if ADDON.getSetting('tv_show_custom_directory') == "true":
  22.     TV_SHOWS_PATH = ADDON.getSetting('tv_show_directory')
  23. else:
  24.     TV_SHOWS_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.icelibrary/tvshows'), '')
  25.     TV_SHOWS_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.icelibrary/tvshows'), '')
  26.  
  27. MOVIES_DATA_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.icelibrary/movies_data'), '')
  28. TV_SHOWS_DATA_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.icelibrary/tvshows_data'), '')
  29. DOWNLOAD_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.icelibrary/download'), '')
  30. ICEFILMS_URL = ADDON.getSetting('icefilms-url')
  31. ICEFILMS_AJAX = ICEFILMS_URL + '/membersonly/components/com_iceplayer/video.phpAjaxResp.php'
  32. EXCLUDE_PROBLEM_EPISODES = True
  33. AZ_DIRECTORIES = ['1', 'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y', 'Z']
  34. MOVIE_YEAR = int(ADDON.getSetting('movie_minimum_year'))
  35. TV_SHOW_YEAR = int(ADDON.getSetting('tv_show_minimum_year'))
  36. AUTO_BEST_QUALITY = True
  37. AUTO_DVDRIP_QUALITY = True
  38. AUTO_PLAY_MIRRORS = True
  39. AUTO_PLAY_PARTS = False #Not yet implemented
  40.  
  41. if ADDON.getSetting('movie_hd_only') == "true":
  42.     MOVIES_HD_ONLY = True
  43. else:
  44.     MOVIES_HD_ONLY = False
  45.  
  46. if ADDON.getSetting('auto_best_quality') == "true":
  47.     AUTO_BEST_QUALITY = True
  48. else:
  49.     AUTO_BEST_QUALITY = False
  50.  
  51. if ADDON.getSetting('auto_dvdrip_quality') == "true":
  52.     AUTO_DVDRIP_QUALITY = True
  53. else:
  54.     AUTO_DVDRIP_QUALITY = False
  55.  
  56. if ADDON.getSetting('auto_mirror') == "true":
  57.     AUTO_PLAY_MIRRORS = True
  58. else:
  59.     AUTO_PLAY_MIRRORS = False
  60.    
  61. #########################
  62. ### General functions ###
  63. #########################
  64.  
  65. def Notification(title, message):
  66.     xbmc.executebuiltin("XBMC.Notification("+title+","+message+")")
  67.  
  68. def RemoveDirectory(dir):
  69.     dialog = xbmcgui.Dialog()
  70.     if dialog.yesno("Remove directory", "Do you want to remove directory?", dir):
  71.         if os.path.exists(dir):
  72.             pDialog = xbmcgui.DialogProgress()
  73.             pDialog.create(' Removing directory...')
  74.             pDialog.update(0, dir) 
  75.             shutil.rmtree(dir)
  76.             pDialog.close()
  77.             Notification("Directory removed", dir)
  78.         else:
  79.             Notification("Directory not found", "Can't delete what does not exist.")   
  80.    
  81. def GetURL(url, params = None, referrer = ICEFILMS_URL, cookie = None, save_cookie = False, silent = False):
  82.     if params:
  83.         req = urllib2.Request(url, params)
  84.         # req.add_header('Content-type', 'application/x-www-form-urlencoded')
  85.     else:
  86.         req = urllib2.Request(url)
  87.  
  88.     req.add_header('User-Agent', USER_AGENT)
  89.     if referrer:
  90.         req.add_header('Referer', referrer)
  91.     if cookie:
  92.         req.add_header('Cookie', cookie)
  93.  
  94.     print url
  95.    
  96.     try:
  97.         response = urllib2.urlopen(req)
  98.         body = response.read()
  99.     except:
  100.         if not silent:
  101.             dialog = xbmcgui.Dialog()
  102.             dialog.ok("Connection failed", "Failed to connect to Icefilms.info", url)
  103.             print "Failed to connect to Icefilms.info"
  104.             return ''
  105.  
  106.     if save_cookie:
  107.         setcookie = response.info().get('Set-Cookie', None)
  108.         #print "Set-Cookie: %s" % repr(setcookie)
  109.         if setcookie:
  110.             setcookie = re.search('([^=]+=[^=;]+)', setcookie).group(1)
  111.             body = body + '<cookie>' + setcookie + '</cookie>'
  112.  
  113.     response.close()
  114.     return body
  115.    
  116. def PassMovieFilter(year, hd_test):
  117.     if MOVIES_HD_ONLY:
  118.         if hd_test != "HD":
  119.             return False
  120.     if MOVIE_YEAR > year:      
  121.         return False
  122.     return True
  123.    
  124. def PassTVShowFilter(year):
  125.     if TV_SHOW_YEAR > 1900:
  126.         try:
  127.             year = int(show_name[len(show_name)-5:len(show_name)-1])
  128.         except:
  129.             year = 0
  130.         if year < TV_SHOW_YEAR:
  131.             return False
  132.     return True
  133.    
  134. def CreateStreamFile(name, href, dir, remove_year, show_name=''):
  135.     try:
  136.        
  137.         if len(show_name) > 0:
  138.             show_name = show_name + ' '
  139.         strm_string = "plugin://plugin.video.icelibrary/?href=" + urllib.quote(href) + "&mode=10&name=" + urllib.quote(show_name + name)
  140.         filename = CleanFileName(name, remove_year) + ".strm"
  141.         path = os.path.join(dir, filename)
  142.         file = open(path,'w')
  143.         file.write(strm_string)
  144.         file.close()
  145.     except:
  146.         print "Error while creating strm file for : " + name
  147.    
  148. def DeleteFavorites():
  149.     dialog = xbmcgui.Dialog()
  150.     if dialog.yesno("Remove", "Do you want to remove favorites.dat?"):
  151.         print "Removing favorites.dat"
  152.         try:
  153.             os.remove(os.path.join(TV_SHOWS_DATA_PATH, "favorites.dat"))
  154.             Notification("File deleted", "favorites.dat was deleted.")
  155.         except:
  156.             Notification("File not found", "No favorites.dat to delete.")
  157.  
  158.  
  159. def AddToFavorites(name):
  160.     #Needed to use X:N format to not alter the names of the TV shows
  161.     print "Adding " + name + " to favorites."
  162.     split = name.split(":")
  163.     tv_show_data = LoadData("TV shows", split[0] + ".dat")
  164.     to_add = tv_show_data[int(split[1])]
  165.    
  166.     favorites_data = LoadData("TV shows", "favorites.dat")
  167.     for data in favorites_data:
  168.         if len(data) > 1:
  169.             if data[1] == to_add[1]:
  170.                 print to_add[0] + " already exists in favorites."
  171.                 Notification("Already exists in favorites", to_add[0] + " already exist in favorites.")
  172.                 return
  173.     favorites_data.append(to_add)
  174.  
  175.     SaveData("TV shows", "favorites.dat", favorites_data)
  176.     print "Successfully added "+ to_add[0] + " to favorites."
  177.     xbmc.executebuiltin("Container.Refresh")
  178.     Notification("Favorite added", to_add[0] + " was added to favorites.")
  179.  
  180. def RemoveFromFavorites(name):
  181.     print "Removing " + name + " from favorites."
  182.     favorites_data = LoadData("TV shows", "favorites.dat")
  183.     split = name.split(":")
  184.     to_remove = favorites_data[int(split[1])]
  185.     favorites_data.remove(to_remove)
  186.     SaveData("TV shows", "favorites.dat", favorites_data)
  187.     Notification("Favorite removed", to_remove[0] + " was removed from favorites.")
  188.     print "Successfully removed "+ to_remove[0] + " from favorites."
  189.     xbmc.executebuiltin("Container.Refresh")
  190.    
  191. def CreateDirectory(dir_path):
  192.     dir_path = dir_path.strip()
  193.     if not os.path.exists(dir_path):
  194.         os.makedirs(dir_path)
  195.            
  196. def CleanFileName(s, remove_year, use_encoding = False, use_blanks = True):
  197.     if remove_year:
  198.         s = s[0:len(s)-7]
  199.     s = s.replace(' (Eng subs)', '')
  200.     s = s.replace(' (eng subs)', '')
  201.     s = s.replace(' (English subs)', '')
  202.     s = s.replace(' (english subs)', '')
  203.     s = s.replace(' (Eng Subs)', '')
  204.     s = s.replace(' (English Subs)', '')
  205.     s = s.replace('&', '&')
  206.     s = s.replace('&#x27;', '\'')
  207.     s = s.replace('&#xC6;', 'AE')
  208.     s = s.replace('&#xC7;', 'C')
  209.     s = s.replace('&#xF4;', 'o')
  210.     s = s.replace('&#xE9;', 'e')
  211.     s = s.replace('&#xEB;', 'e')
  212.     s = s.replace('&#xED;', 'i')
  213.     s = s.replace('&#xEE;', 'i')
  214.     s = s.replace('&#xA2;', 'c')
  215.     s = s.replace('&#xE2;', 'a')
  216.     s = s.replace('&#xEF;', 'i')
  217.     s = s.replace('&#xE1;', 'a')
  218.     s = s.replace('&#xE8;', 'e')
  219.     s = s.replace('%2E', '.')
  220.     if use_encoding:
  221.         s = s.replace('"', '%22')
  222.         s = s.replace('*', '%2A')
  223.         s = s.replace('/', '%2F')
  224.         s = s.replace(':', ',')
  225.         s = s.replace('<', '%3C')
  226.         s = s.replace('>', '%3E')
  227.         s = s.replace('?', '%3F')
  228.         s = s.replace('\\', '%5C')
  229.         s = s.replace('|', '%7C')
  230.         s = s.replace('&frac12;', '%BD')
  231.         s = s.replace('&#xBD;', '%BD') #half character
  232.         s = s.replace('&#xB3;', '%B3')
  233.         s = s.replace('&#xB0;', '%B0') #degree character       
  234.     if use_blanks:
  235.         s = s.replace('"', ' ')
  236.         s = s.replace('*', ' ')
  237.         s = s.replace('/', ' ')
  238.         s = s.replace(':', ' ')
  239.         s = s.replace('<', ' ')
  240.         s = s.replace('>', ' ')
  241.         s = s.replace('?', ' ')
  242.         s = s.replace('\\', ' ')
  243.         s = s.replace('|', ' ')
  244.         s = s.replace('&frac12;', ' ')
  245.         s = s.replace('&#xBD;', ' ') #half character
  246.         s = s.replace('&#xB3;', ' ')
  247.         s = s.replace('&#xB0;', ' ') #degree character
  248.     s = s.strip()
  249.     return s
  250.  
  251. def FileAlreadyExist(filename, files):
  252.     for file in files:
  253.         if filename == file:
  254.             return True        
  255.     return False
  256.  
  257. def SetupAutoUpdate():
  258.     source_path = os.path.join(xbmc.translatePath('special://profile/'), 'autoexec.py')
  259.     try:
  260.         file = open(source_path, 'r')
  261.         content=file.read()
  262.         file.close()
  263.         index = content.find("xbmc.executebuiltin('RunScript(plugin.video.icelibrary,\"?mode=100\")')")
  264.         if index > 0:
  265.             Notification("Already set up", "Auto update is already set up in autoexec.py")
  266.             return
  267.     except:
  268.         content = "import xbmc\n"
  269.     content += "\nxbmc.executebuiltin('RunScript(plugin.video.icelibrary,\"?mode=100\")')"
  270.    
  271.     file = open(source_path, 'w')
  272.     file.write(content)
  273.     file.close()
  274.     print "autoexec.py updated to include IceFilms auto update"
  275.     dialog = xbmcgui.Dialog()  
  276.     dialog.ok("Auto update added to autoexec.py", "To complete the setup:", " 1) Activate auto update in IceLibrary configs.", " 2) Restart XBMC.")
  277.    
  278. def SetupIceLibrary(type):
  279.     print "Trying to add IceLibrary source paths..."
  280.     source_path = os.path.join(xbmc.translatePath('special://profile/'), 'sources.xml')
  281.    
  282.     try:
  283.         file = open(source_path, 'r')
  284.         content=file.read()
  285.         file.close()
  286.         soup = BeautifulSoup(content)
  287.     except:
  288.         soup = BeautifulSoup()
  289.         sources_tag = Tag(soup, "sources")
  290.         soup.insert(0, sources_tag)
  291.        
  292.     if soup.find("video") == None:
  293.         sources = soup.find("sources")
  294.         video_tag = Tag(soup, "video")
  295.         sources.insert(0, video_tag)
  296.        
  297.     video = soup.find("video")
  298.  
  299.     if type=="movies":
  300.         CreateDirectory(MOVIES_PATH)
  301.         if len(soup.findAll(text="Movies (Icefilms)")) < 1:
  302.             movie_source_tag = Tag(soup, "source")
  303.             movie_name_tag = Tag(soup, "name")
  304.             movie_name_tag.insert(0, "Movies (Icefilms)")
  305.             MOVIES_PATH_tag = Tag(soup, "path")
  306.             MOVIES_PATH_tag['pathversion'] = 1
  307.             MOVIES_PATH_tag.insert(0, MOVIES_PATH)
  308.             movie_source_tag.insert(0, movie_name_tag)
  309.             movie_source_tag.insert(1, MOVIES_PATH_tag)
  310.             video.insert(2, movie_source_tag)
  311.  
  312.     if type=="TV shows":
  313.         CreateDirectory(TV_SHOWS_PATH)
  314.         if len(soup.findAll(text="TV Shows (Icefilms)")) < 1:  
  315.             tvshow_source_tag = Tag(soup, "source")
  316.             tvshow_name_tag = Tag(soup, "name")
  317.             tvshow_name_tag.insert(0, "TV Shows (Icefilms)")
  318.             tvshow_path_tag = Tag(soup, "path")
  319.             tvshow_path_tag['pathversion'] = 1
  320.             tvshow_path_tag.insert(0, TV_SHOWS_PATH)
  321.             tvshow_source_tag.insert(0, tvshow_name_tag)
  322.             tvshow_source_tag.insert(1, tvshow_path_tag)
  323.             video.insert(2, tvshow_source_tag)
  324.    
  325.     print soup.prettify()
  326.     string = ""
  327.     for i in soup:
  328.         string = string + str(i)
  329.    
  330.     file = open(source_path, 'w')
  331.     file.write(str(soup))
  332.     file.close()
  333.     print "Source paths added!"
  334.    
  335.     dialog = xbmcgui.Dialog()
  336.     dialog.ok("Source folders added", "To complete the setup:", " 1) Restart XBMC.", " 2) Set the content type of added folders.")
  337.     #Appearently this restarted everything and not just XBMC... :(
  338.     #if dialog.yesno("Restart now?", "Do you want to restart XBMC now?"):
  339.     #   xbmc.restart()
  340.    
  341. ##################
  342. ### Megaupload ###
  343. ##################
  344.  
  345. def LoginMegaupload():
  346.     #Get whether user has set an account to use.
  347.     Account = ADDON.getSetting('megaupload-account')
  348.  
  349.     mu=megaroutines.megaupload(DATA_PATH)
  350.  
  351.     #delete old logins
  352.     mu.delete_login()
  353.  
  354.     if Account == 'false':
  355.         print 'Account: '+'no account set'
  356.  
  357.     elif Account == 'true':
  358.         #check for megaupload login and do it
  359.         megauser = ADDON.getSetting('megaupload-username')
  360.         megapass = ADDON.getSetting('megaupload-password')
  361.         login=mu.set_login(megauser,megapass)
  362.        
  363.         if megapass != '' and megauser != '':
  364.             if login is False:
  365.                 print 'Account: '+'login failed'
  366.                 Notification("Megaupload", "Login failed. Megaupload will load with no account.")
  367.             elif login is True:
  368.                 print 'Account: '+'login succeeded'
  369.                 HideSuccessfulLogin = ADDON.getSetting('hide-successful-login-messages')
  370.                 if HideSuccessfulLogin == 'false':
  371.                     Notification("Megaupload", "Account login successful.")  
  372.         if megapass == '' or megauser == '':
  373.             print 'no login details specified, using no account'
  374.             Notification("Megaupload", "Login failed. Megaupload will load with no account.")  
  375.    
  376. ################
  377. ### Icefilms ###
  378. ################
  379.    
  380. def GetAllAZ(type, create_strm_files, path, sub_path, silent = False):
  381.     print 'Trying to scrape all ' + type + ' from A-Z categories'
  382.     CreateDirectory(path)
  383.     pDialog = xbmcgui.DialogProgress()
  384.     if not silent:
  385.         pDialog.create(' Scraping ' + type + ', A-Z')
  386.  
  387.     for character in AZ_DIRECTORIES:
  388.         percent = int((100 * AZ_DIRECTORIES.index(character))/len(AZ_DIRECTORIES))
  389.        
  390.         if not GetItem(type, ICEFILMS_URL + sub_path + character, character, create_strm_files, pDialog, 0, silent):
  391.             break
  392.         if not silent:
  393.             if (pDialog.iscanceled()):
  394.                 print 'Canceled scraping'
  395.                 return
  396.  
  397.     pDialog.close()
  398.     print 'Scraping complete!' 
  399.        
  400. def GetFromPath(type, create_strm_files, path, sub_path, page_name, silent = False):
  401.     print 'Scraping ' + type + ' from ' + page_name
  402.     pDialog = xbmcgui.DialogProgress()
  403.     if not silent:
  404.         pDialog.create(' Scraping newly added ' + type)
  405.  
  406.     CreateDirectory(path)
  407.     GetItem(type, ICEFILMS_URL + sub_path, page_name, create_strm_files, pDialog, 0, silent)
  408.    
  409.     if not silent:
  410.         if (pDialog.iscanceled()):
  411.             print 'Canceled scraping'
  412.         else:
  413.             pDialog.close()
  414.     print 'Scraping complete!' 
  415.    
  416. def GetItem(type, page, page_name, create_strm_files, pDialog, percent, silent = False):
  417.     print "Scanning " + page
  418.     if not silent:
  419.         pDialog.update(percent, page_name, '')
  420.    
  421.     pagedata = GetURL(page, silent = silent)
  422.     if pagedata=='':
  423.         return False
  424.    
  425.     soup = BeautifulSoup(pagedata)
  426.     list = soup.find("span", { "class" : "list" })
  427.     stars = list.findAll("img", { "class" : "star" })
  428.     data = []
  429.    
  430.     for star in stars:
  431.         a = star.findNextSibling('a')
  432.         name = str(a.string)
  433.         if not silent:
  434.             if (pDialog.iscanceled()):
  435.                 return False
  436.             pDialog.update(percent, "Scraping " + type + " " + page_name, name)
  437.         try:
  438.             year = int(name[len(name)-5:len(name)-1])
  439.         except:
  440.             year = 0
  441.         href = a['href']
  442.         data.append([name,href])
  443.        
  444.         if type=="movies":
  445.             hd_test = a.nextSibling.string
  446.             passed_filter = PassMovieFilter(year, hd_test)
  447.             if passed_filter and create_strm_files:
  448.                 CreateStreamFile(name, href, MOVIES_PATH, False)
  449.  
  450.         if type=="TV shows":
  451.             passed_filter = PassTVShowFilter(year)
  452.             if passed_filter and create_strm_files:
  453.                 if not GetEpisodes(name, href, silent):
  454.                     return False
  455.                
  456.     SaveData(type, page_name + ".dat", data)
  457.     return True
  458.    
  459. def GetFavorites(file_name, silent = False):
  460.     print "Fetching favorites"
  461.     pDialog = xbmcgui.DialogProgress()
  462.     if not silent:
  463.         pDialog.create(' Scraping favorites')
  464.    
  465.     tv_show_data = LoadData("TV shows", file_name)
  466.  
  467.     for data in tv_show_data:
  468.         percent = int((100 * tv_show_data.index(data))/len(tv_show_data))
  469.         if not silent:
  470.             if (pDialog.iscanceled()):
  471.                 return
  472.             pDialog.update(percent, "Scraping TV show", data[0])
  473.         GetEpisodes(data[0], data[1], silent)
  474.    
  475. def AddMovie(name):
  476.     #Needed to use X:N format to not alter the names of movie
  477.     print "Adding movie " + name
  478.     CreateDirectory(MOVIES_PATH)
  479.     split = name.split(":")
  480.     movies_data = LoadData("movies", split[0] + ".dat")
  481.     to_add = movies_data[int(split[1])]
  482.     CreateStreamFile(to_add[0], to_add[1], MOVIES_PATH, False)
  483.     Notification("Movie added", to_add[0])
  484.    
  485. def SaveData(type, file_name, data):
  486.     s = ''
  487.     for d in data:
  488.         try:
  489.             s = s + d[0] + "\t" + d[1] + "\n"
  490.         except:
  491.             print "Got a problem when saving data."
  492.     if type=="movies":
  493.         CreateDirectory(MOVIES_DATA_PATH)
  494.         path = os.path.join(MOVIES_DATA_PATH, file_name.lower())
  495.     if type=="TV shows":
  496.         CreateDirectory(TV_SHOWS_DATA_PATH)
  497.         path = os.path.join(TV_SHOWS_DATA_PATH, file_name.lower())
  498.  
  499.     file = open(path,'w')
  500.     file.write(s)
  501.     file.close()   
  502.  
  503. def LoadData(type, file_name):
  504.     if type=="movies":
  505.         directory =  MOVIES_DATA_PATH
  506.     if type=="TV shows":
  507.         directory = TV_SHOWS_DATA_PATH
  508.     CreateDirectory(directory)
  509.     try:
  510.         path = os.path.join(directory, file_name.lower())
  511.         fh = open(path, 'r')
  512.         contents=fh.read()
  513.         fh.close()
  514.     except:
  515.         return []
  516.  
  517.     file_data = []
  518.     file_strings = contents.split("\n")
  519.     for data_text in file_strings:
  520.         data = data_text.split("\t")
  521.         if len(data) > 1:
  522.             file_data.append([data[0],data[1]])
  523.     return file_data
  524.  
  525. def GetEpisodes(show_name, href, silent = False):
  526.     page = ICEFILMS_URL + href
  527.     pagedata = GetURL(page, silent = silent)
  528.     if pagedata=='':
  529.         return False
  530.     month = [' ','Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  531.     month_nr = [' ','01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
  532.     soup = BeautifulSoup(pagedata)
  533.     list = soup.find("span", { "class" : "list" })
  534.     stars = list.findAll("img", { "class" : "star" })
  535.     year_loc = soup.findAll( "a", {"name" : re.compile(r"[0-9]{4}")})
  536.     print year_loc
  537.     for y in year_loc:
  538.         print y
  539.         season = y['name']
  540.         print season
  541.         b = y.parent.nextSibling
  542.         while getattr(b, 'name', None) != 'h3':
  543.             try:
  544.                 if getattr(b, 'name', None) == 'img':
  545.                     a = b.findNextSibling('a')
  546.                     name_split = re.split(r'[^a-zA-Z0-9_]',str(a.string))
  547.                     try:
  548.                         name = season+'.'+month_nr[month.index(name_split[0])]+'.'+name_split[1]
  549.                     except ValueError:
  550.                         name = name_split[1]
  551.                     href = a['href']
  552.                     show_path = os.path.join(TV_SHOWS_PATH, CleanFileName(show_name, True, use_encoding = True))
  553.                     CreateDirectory(show_path)     
  554.                     season_path = os.path.join(show_path, season)
  555.                     CreateDirectory(season_path)
  556.                     sname = CleanFileName(show_name, True, False, False)
  557.                     CreateStreamFile(name, href, season_path, False, show_name=sname)  
  558.                 b = b.nextSibling
  559.             except AttributeError:
  560.                 break
  561.  
  562.     for star in stars:
  563.         a = star.findNextSibling('a')
  564.         name = str(a.string)
  565.         href = a['href']
  566.         save_episode = True
  567.        
  568.         #Get the season number
  569.         season = name.split("x")[0]
  570.         try:
  571.             int(season)
  572.         except:
  573.             if EXCLUDE_PROBLEM_EPISODES:
  574.                 #print show_name, season
  575.                 save_episode = False
  576.             else:
  577.                 season = "0"
  578.         if save_episode:
  579.             show_path = os.path.join(TV_SHOWS_PATH, CleanFileName(show_name, True, use_encoding = True))
  580.             CreateDirectory(show_path)
  581.             season_path = os.path.join(show_path, season)
  582.             CreateDirectory(season_path)
  583.             sname = CleanFileName(show_name, True, False, False)
  584.             CreateStreamFile(name, href, season_path, False, show_name=sname)  
  585.     return True
  586.            
  587. def LaunchSTRM(name, href):
  588.     print 'Running .strm'
  589.     print name
  590.  
  591.     name = CleanFileName(name, False, use_encoding = False)
  592.    
  593.    
  594.     url = ICEFILMS_URL + urllib2.unquote(href)
  595.  
  596.     pagedata = GetURL(url)
  597.     if pagedata=='':
  598.         return
  599.      
  600.     match=re.compile('/membersonly/components/com_iceplayer/(.+?)" width=').findall(pagedata)
  601.     match[0]=re.sub('%29',')',match[0])
  602.     match[0]=re.sub('%28','(',match[0])
  603.     for url in match:
  604.         mirrorpageurl = ICEFILMS_URL + '/membersonly/components/com_iceplayer/' + url
  605.     print mirrorpageurl
  606.  
  607.     mirrorpage=GetURL(mirrorpageurl, save_cookie = True)
  608.     if pagedata=='':
  609.         return
  610.  
  611.     # check for recaptcha
  612.     has_recaptcha = CheckForCaptcha(mirrorpage)
  613.     if has_recaptcha is False:
  614.         HandleOptions(name, mirrorpage)
  615.     elif has_recaptcha is True:
  616.         return #TODO: Handle captchas
  617.        
  618. def CheckForCaptcha(url):
  619.     print "Looking for a captcha..."
  620.     return False
  621.  
  622. def HandleOptions(name, mirrorpage):
  623.     dialog = xbmcgui.Dialog()
  624.     soup = BeautifulSoup(mirrorpage)
  625.    
  626.     #Wanted to replace this with BautifulSoup ... but I'm to lazy :D
  627.     try:
  628.         sec = re.search("f\.lastChild\.value=\"([^']+)\",a", mirrorpage).group(1)
  629.         t   = re.search('"&t=([^"]+)",', mirrorpage).group(1)
  630.         args = {'iqs': '', 'url': '', 'cap': ''}
  631.         args['sec'] = sec
  632.         args['t'] = t
  633.         cookie = soup.find("cookie").string
  634.     except:
  635.         dialog = xbmcgui.Dialog()
  636.         dialog.ok("Unexpected page content", "Unexpected page content returned from Icefilms.info")
  637.         return
  638.    
  639.     quality_list = soup.findAll("div", { "class" : "ripdiv" })
  640.    
  641.     quality_options = []
  642.     for quality in quality_list:
  643.         quality_options.append(quality.b.string)
  644.    
  645.     print quality_options
  646.    
  647.     if AUTO_BEST_QUALITY:
  648.         quality_select = 0
  649.     elif AUTO_DVDRIP_QUALITY:
  650.         if u'DVDRip / Standard Def' in quality_options:
  651.             quality_select=quality_options.index(u'DVDRip / Standard Def')
  652.         else:
  653.             quality_select = dialog.select('Unable to understand quality options, pelase select quality', quality_options)
  654.             print quality_select
  655.             if quality_select < 0:
  656.                 return
  657.     else:
  658.         quality_select = dialog.select('Select quality', quality_options)
  659.         print quality_select
  660.         if quality_select < 0:
  661.             return
  662.    
  663.     for quality in quality_list:
  664.         if quality_options[quality_select] == quality.b.string:
  665.             quality_choice = quality
  666.             break
  667.    
  668.     mirror_list = quality_choice.findAll("p")
  669.  
  670.     mirror_options = []        
  671.     mirror_id = []
  672.     multiple_parts = False
  673.    
  674.     for mirror in mirror_list:
  675.         if len(mirror.contents) > 0:
  676.             if len(mirror.contents[0]) > 2: #Multi part
  677.                 links = mirror.findAll("a")
  678.                 if AUTO_PLAY_MIRRORS and AUTO_PLAY_PARTS:
  679.                     part_urls = []
  680.                     failed = False
  681.                     for link in links:
  682.                         part_id = link['onclick'][3:len(link['onclick'])-1]
  683.                         part_url = GetSource(int(part_id), args, cookie)
  684.                         if part_url == None:
  685.                             failed = True
  686.                             break
  687.                         part_urls.append(part_url)
  688.                     if not failed:
  689.                         url1 = HandleVidlink(part_urls[0])[0]
  690.                         if len(part_urls) > 1:
  691.                             url2 = HandleVidlink(part_urls[1])[0]
  692.                         else:
  693.                             url2 = ''
  694.                         if len(part_urls) > 2:
  695.                             url3 = HandleVidlink(part_urls[2])[0]
  696.                         else:
  697.                             url3 = ''
  698.                         if len(part_urls) > 3:
  699.                             url4 = HandleVidlink(part_urls[3])[0]
  700.                         else:
  701.                             url4 = ''
  702.                         StreamSource(name, url1, url2, url3, url4)
  703.                         return
  704.                 else:
  705.                     multiple_parts = True
  706.                     for link in links:
  707.                         print mirror.next
  708.                         mirror_options.append(mirror.next + link.next)
  709.                         mirror_id.append(link['onclick'][3:len(link['onclick'])-1])
  710.             else: #Single part 
  711.                 link = mirror.find("a")
  712.                 if AUTO_PLAY_MIRRORS:
  713.                     mega_upload_url = GetSource(int(link['onclick'][3:len(link['onclick'])-1]), args, cookie)
  714.                     page=HandleVidlink(mega_upload_url)
  715.                     if page != None:
  716.                         resolved_url= page[0]
  717.                         StreamSource(name, resolved_url)
  718.                         return
  719.                 else:
  720.                     mirror_options.append(link.next[0:len(link.next)-2])
  721.                     mirror_id.append(link['onclick'][3:len(link['onclick'])-1])
  722.  
  723.     if AUTO_PLAY_MIRRORS and not multiple_parts: #Failed to play any mirror.
  724.         dialog.ok("Streaming failed", "No working mirror found")
  725.         return
  726.                    
  727.     print mirror_options;
  728.     print mirror_id;
  729.     mirror_select = dialog.select('Select mirror', mirror_options)
  730.     print mirror_select
  731.     if mirror_select < 0:
  732.         return
  733.     #AUTO_PLAY_PARTS
  734.     mega_upload_url = GetSource(int(mirror_id[mirror_select]), args, cookie)
  735.     page=HandleVidlink(mega_upload_url)
  736.     if page == None:
  737.         return
  738.     resolved_url= page[0]
  739.    
  740.     StreamSource(name, resolved_url)
  741.  
  742. def GetSource(id, args, cookie):
  743.     m = random.randrange(100, 300) * -1
  744.     s = random.randrange(5, 50)
  745.     params = copy.copy(args)
  746.     params['id'] = id
  747.     params['m'] = m
  748.     params['s'] = s
  749.     paramsenc = urllib.urlencode(params)
  750.     body = GetURL(ICEFILMS_AJAX, params = paramsenc, cookie = cookie)
  751.     print 'response: %s' % body
  752.     source = re.search('url=(http[^&]+)', body).group(1)
  753.     url = urllib.unquote(source)
  754.     print 'url: %s' % url
  755.     return url
  756.    
  757. def StreamSource(name,url1, url2 = '', url3 = '', url4 = ''):
  758.     print 'attempting to stream file'
  759.     WaitIf()
  760.    
  761.     #print url1
  762.     #print url2
  763.     #print url3
  764.     #print url4
  765.    
  766.     download = False #Can't get it to work :\
  767.     if not download:
  768.         #pl=xbmc.PlayList(1)
  769.         #pl.clear()
  770.         list_item = xbmcgui.ListItem(name, iconImage="DefaultVideoBig.png", thumbnailImage='', path=url1)
  771.         #xbmc.PlayList(1).add(url1, list_item)
  772.         #print 'thread1 started'
  773.         #if not url2=='':
  774.         #   xbmc.PlayList(1).add(url2, list_item)
  775.         #   print 'thread2 started'
  776.         #if not url3=='':
  777.         #   xbmc.PlayList(1).add(url3, list_item)
  778.         #   print 'thread3 started'
  779.         #if not url4=='':
  780.         #   xbmc.PlayList(1).add(url4, list_item)
  781.         #   print 'thread4 started'
  782.            
  783.         try:
  784.             #xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),True,pl)
  785.             #xbmc.Player().play(pl)
  786.             list_item.setProperty( "IsPlayable", "true" )
  787.             xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),True,list_item)
  788.         except:
  789.             print 'file streaming failed'
  790.             Notification("Streaming failed", "Streaming failed")
  791.     else:
  792.         print 'starting threads'
  793.         CreateDirectory(DOWNLOAD_PATH)
  794.        
  795.         pl=xbmc.PlayList(1)
  796.         pl.clear()
  797.         list_item = xbmcgui.ListItem('', iconImage="DefaultVideoBig.png", thumbnailImage='')
  798.        
  799.         d_path1 = os.path.join(DOWNLOAD_PATH, 'part1.avi')
  800.         d_thread1 = KThread(target=urllib.urlretrieve, args=(url1, d_path1))
  801.         d_thread1.start()
  802.         xbmc.PlayList(1).add(d_path1, list_item)
  803.         print 'thread1 started'
  804.         if not url2=='':
  805.             d_path2 = os.path.join(DOWNLOAD_PATH, 'part2.avi')
  806.             d_thread2 = KThread(target=urllib.urlretrieve, args=(url2, d_path2))
  807.             d_thread2.start()
  808.             xbmc.PlayList(1).add(d_path2, list_item)
  809.             print 'thread2 started'
  810.         if not url3=='':
  811.             d_path3 = os.path.join(DOWNLOAD_PATH, 'part3.avi')
  812.             d_thread3 = KThread(target=urllib.urlretrieve, args=(url3, d_path3))
  813.             d_thread3.start()
  814.             xbmc.PlayList(1).add(d_path3, list_item)
  815.             print 'thread3 started'
  816.         if not url4=='':
  817.             d_path4 = os.path.join(DOWNLOAD_PATH, 'part4.avi')
  818.             d_thread4 = KThread(target=urllib.urlretrieve, args=(url4, d_path4))
  819.             d_thread4.start()
  820.             xbmc.PlayList(1).add(d_path4, list_item)
  821.             print 'thread4 started'
  822.        
  823.         #xbmc.Player().play(pl)
  824.        
  825.         xbmc.sleep(10000) # Set a 10 second delay to allow the file start downloading a bit.
  826.         print 'wait completed'
  827.        
  828.         #list_item = xbmcgui.ListItem('', iconImage="DefaultVideoBig.png", thumbnailImage='', path=d_path1)
  829.         #list_item.setProperty( "IsPlayable", "true" )
  830.        
  831.         #xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),True,pl)
  832.         xbmc.Player().play(pl)
  833.        
  834.         #thread2 = threading.Thread(target=xbmcplugin.setResolvedUrl, args=(int(sys.argv[ 1 ]),True,list_item))
  835.         #thread2 = threading.Thread(target=xbmc.Player( xbmc.PLAYER_CORE_DVDPLAYER ).play, args=(d_path, list_item))
  836.        
  837.        
  838.         while xbmc.Player().isPlayingVideo():
  839.             pass
  840.         while os.path.exists(d_path1):
  841.             try:
  842.                 os.remove(d_path1)
  843.                 break
  844.             except:
  845.                 pass
  846.  
  847. class KThread(threading.Thread):
  848.   def __init__(self, *args, **keywords):
  849.     threading.Thread.__init__(self, *args, **keywords)
  850.     self.killed = False
  851.  
  852.   def start(self):
  853.     self.__run_backup = self.run
  854.     self.run = self.__run
  855.     threading.Thread.start(self)
  856.  
  857.   def __run(self):
  858.     sys.settrace(self.globaltrace)
  859.     self.__run_backup()
  860.     self.run = self.__run_backup
  861.  
  862.   def globaltrace(self, frame, why, arg):
  863.     if why == 'call':
  864.       return self.localtrace
  865.     else:
  866.       return None
  867.  
  868.   def localtrace(self, frame, why, arg):
  869.     if self.killed:
  870.       if why == 'line':
  871.         raise SystemExit()
  872.     return self.localtrace
  873.  
  874.   def kill(self):
  875.     self.killed = True
  876.  
  877. def HandleVidlink(url):
  878.     #video link preflight, pays attention to settings / checks if url is mega or 2shared
  879.     ismega = re.search('\.megaupload\.com/', url)
  880.     is2shared = re.search('\.2shared\.com/', url)
  881.  
  882.     if ismega is not None:
  883.         WaitIf()
  884.  
  885.         mu=megaroutines.megaupload(DATA_PATH)
  886.         link=mu.resolve_megaup(url)
  887.  
  888.         finished = DoWait(link[3], link[4])
  889.  
  890.         if finished == True:
  891.             return link
  892.         else:
  893.             return None
  894.  
  895.     elif is2shared is not None:
  896.         Notify('big','2Shared','2Shared is not supported by this addon. (Yet)','')
  897.         return False
  898.         #shared2url=SHARED2_HANDLER(url)
  899.         #return shared2url
  900.  
  901. def WaitIf():
  902.     #killing playback is necessary if switching playing of one megaup/2share stream to another
  903.     if xbmc.Player().isPlayingVideo() == True:
  904.         xbmc.Player().stop()
  905.  
  906. def DoWait(account, wait_time):
  907.     # do the necessary wait, with  a nice notice and pre-set waiting time. I have found the below waiting times to never fail.
  908.     if account == 'platinum':    
  909.         return HandleWait(int(wait_time),'Megaupload','Loading video with your *Platinum* account.')
  910.     elif account == 'premium':    
  911.         return HandleWait(int(wait_time),'Megaupload','Loading video with your *Premium* account.')
  912.     elif account == 'free':
  913.         return HandleWait(int(wait_time),'Megaupload Free User','Loading video with your free account.')
  914.     else:
  915.         return HandleWait(int(wait_time),'Megaupload','Loading video.')
  916.  
  917. def HandleWait(time_to_wait,title,text):
  918.     print 'waiting '+str(time_to_wait)+' secs'    
  919.  
  920.     pDialog = xbmcgui.DialogProgress()
  921.     ret = pDialog.create(' '+title)
  922.  
  923.     secs=0
  924.     percent=0
  925.    
  926.     cancelled = False
  927.     while secs < time_to_wait:
  928.         secs = secs + 1
  929.         percent = int((100 * secs)/time_to_wait)
  930.         secs_left = str((time_to_wait - secs))
  931.         remaining_display = ' Wait '+secs_left+' seconds for the video stream to activate...'
  932.         pDialog.update(percent,' '+text,remaining_display)
  933.         xbmc.sleep(1000)
  934.         if (pDialog.iscanceled()):
  935.             cancelled = True
  936.             break
  937.     if cancelled == True:    
  938.         print 'wait cancelled'
  939.         return False
  940.     else:
  941.         print 'done waiting'
  942.         return True
  943.  
  944. ###################
  945. ### Auto-update ###
  946. ###################
  947.  
  948. def AutoUpdateLibrary():
  949.     if ADDON.getSetting('auto_update') == "false":
  950.         return
  951.    
  952.     print "IceLibrary running an automatic update"
  953.    
  954.     xbmc.executebuiltin('CancelAlarm(updatelibrary)')
  955.    
  956.     timer_amounts = {}
  957.     timer_amounts['0'] = '120'
  958.     timer_amounts['1'] = '300'
  959.     timer_amounts['2'] = '600'
  960.     timer_amounts['3'] = '900'
  961.     timer_amounts['4'] = '1440'
  962.  
  963.     #only do this if we are not playing anything
  964.     if xbmc.Player().isPlaying() == False:
  965.         if ADDON.getSetting('update_tvshows') == "true":
  966.             UpdateFavorites(True)
  967.             #xbmc.executebuiltin('UpdateLibrary(video,' + TV_SHOWS_PATH + ')')
  968.         if ADDON.getSetting('update_movies') == "true":
  969.             UpdateMovies(True)
  970.             #xbmc.executebuiltin('UpdateLibrary(video,' + MOVIES_PATH + ')')
  971.         xbmc.executebuiltin('UpdateLibrary(video)')
  972.        
  973.     #reset the timer
  974.     xbmc.executebuiltin('AlarmClock(updatelibrary,XBMC.RunScript(plugin.video.icelibrary,"?mode=100"),' +
  975.                         timer_amounts[ADDON.getSetting('update_timer')] +  ',true)')
  976.  
  977.     print "IceLibrary update complete"
  978.        
  979. ##################
  980. ### Addon menu ###
  981. ##################
  982.  
  983. def AddonMenu():  #homescreen
  984.     print 'IceLibrary menu'
  985.     AddOption('Movies',True, 1000)
  986.     AddOption('TV shows',True, 2000)
  987.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  988.  
  989. def MoviesMenu(): #1000
  990.     print 'Movie menu'
  991.     AddOption('Update movies',False, 1100)
  992.     AddOption('Pick movies',True, 1200)
  993.     AddOption('Setup movies',True, 1300)
  994.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  995.  
  996. def UpdateMovies(silent = False): #1100
  997.     GetFromPath("movies", True, MOVIES_PATH, "/movies/added/1", 'added', silent)
  998.    
  999. def MoviesListMenu(): #1200
  1000.     AddOption('A-Z',True, 1210)
  1001.     AddOption('Genres',True, 1220) 
  1002.     AddOption('Popular',True, 1230)
  1003.     AddOption('Highly rated',True, 1240)   
  1004.     AddOption('Newly released',True, 1250) 
  1005.     AddOption('Newly added',True, 1260)
  1006.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1007.  
  1008. def MoviesAlphabetMenu(): #1210
  1009.     print 'Movies alphabet screen'
  1010.     for character in AZ_DIRECTORIES:
  1011.         AddOption(character,True,1211,character)
  1012.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1013.  
  1014. def MoviesLetterScreen(name): #1211
  1015.     print 'Movies letter ' + str(name) + ' screen'
  1016.     GetFromPath("movies", False, MOVIES_DATA_PATH, "/movies/a-z/" + str(name), str(name))
  1017.     AddOptionsFromFile("movies", str(name), 20, False)
  1018.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1019.  
  1020. def MovieGenresMenu(): #1220
  1021.     print 'Movies genres screen'
  1022.     AddOption("Action",True,1221,"action")
  1023.     AddOption("Animation",True,1221,"animation")
  1024.     AddOption("Comedy",True,1221,"comedy")
  1025.     AddOption("Documentary",True,1221,"documentary")
  1026.     AddOption("Drama",True,1221,"drama")
  1027.     AddOption("Family",True,1221,"family")
  1028.     AddOption("Horror",True,1221,"horror")
  1029.     AddOption("Romance",True,1221,"romance")
  1030.     AddOption("Sci-Fi",True,1221,"sci-fi")
  1031.     AddOption("Thriller",True,1221,"thriller")
  1032.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1033.    
  1034. def MovieGenreScreen(name): #1221
  1035.     print 'Movies genre ' + str(name) + ' screen'
  1036.     GetFromPath("movies", False, MOVIES_DATA_PATH, "/movies/added/" + str(name), str(name))
  1037.     AddOptionsFromFile("movies", str(name),20, False)
  1038.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1039.  
  1040. def MoviePopularScreen(): #1230
  1041.     print 'Movies popular screen'
  1042.     GetFromPath("movies", False, MOVIES_DATA_PATH, "/movies/popular/1", "popular")
  1043.     AddOptionsFromFile("movies", "popular",20, False)
  1044.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1045.    
  1046. def MovieRating(): #1240
  1047.     print 'Movies rating screen'
  1048.     GetFromPath("movies", False, MOVIES_DATA_PATH, "/movies/rating/1", "rating")
  1049.     AddOptionsFromFile("movies", "rating",20, False)
  1050.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1051.  
  1052. def MovieReleased(): #1250
  1053.     print 'Movies release screen'
  1054.     GetFromPath("movies", False, MOVIES_DATA_PATH, "/movies/release/1", "release")
  1055.     AddOptionsFromFile("movies", "release",20, False)
  1056.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1057.  
  1058. def MovieAdded(): #1260
  1059.     print 'Movies added screen'
  1060.     GetFromPath("movies", False, MOVIES_DATA_PATH, "/movies/added/1", "added")
  1061.     AddOptionsFromFile("movies", "added",20, False)
  1062.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1063.    
  1064. def MoviesSetupMenu(): #1300
  1065.     print 'Movies setup screen'
  1066.     AddOption("Scrape all movies",False,1310)
  1067.     AddOption("Add IceLibrary movie directory to XBMC sources",False,1320)
  1068.     AddOption("Remove the movie directory and all (Icefilms) movie files",False,1330)
  1069.     AddOption("Install auto update code in autoexec.py",False,1340)
  1070.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1071.  
  1072. def GetAllMovies(): #1310
  1073.     GetAllAZ("movies", True, MOVIES_PATH, "/movies/a-z/")
  1074.    
  1075. def AddMovieDirectory(): #1320
  1076.     SetupIceLibrary("movies")
  1077.    
  1078. def RemoveMovieDirectory(): #1330
  1079.     RemoveDirectory(MOVIES_PATH)
  1080.    
  1081. def TVShowsMenu(): #2000
  1082.     print 'TV shows menu'
  1083.     AddOption('Update favorites',True, 2100)
  1084.     AddOption('View favorites',True, 2200)
  1085.     AddOption('Add favorites',True, 2300)
  1086.     AddOption('Setup TV shows',True, 2400)
  1087.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1088.    
  1089. def UpdateFavorites(silent = False): #2100
  1090.     GetFavorites("favorites.dat", silent)
  1091.    
  1092. def FavoritesListScreen(): #2200
  1093.     AddOptionsFromFile("TV shows", "favorites",40, False)
  1094.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1095.  
  1096. def TVShowListMenu(): #2300
  1097.     AddOption('A-Z',True, 2310)
  1098.     AddOption('Genres',True, 2320) 
  1099.     AddOption('Popular',True, 2330)
  1100.     AddOption('Highly rated',True, 2340)   
  1101.     AddOption('Newly released',True, 2350) 
  1102.     AddOption('Newly added',True, 2360)
  1103.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1104.    
  1105. def TVShowAlphabetMenu(): #2310
  1106.     print 'TV shows alphabet screen'
  1107.     for character in AZ_DIRECTORIES:
  1108.         AddOption(character,True,2311,character)
  1109.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1110.  
  1111. def TVShowLetterScreen(name): #2311
  1112.     print 'TV shows letter ' + str(name) + '  screen'
  1113.     GetFromPath("TV shows", False, TV_SHOWS_DATA_PATH, "/tv/a-z/" + str(name), str(name))
  1114.     AddOptionsFromFile("TV shows", str(name),30, True)
  1115.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1116.  
  1117. def TVShowGenresMenu(): #2320
  1118.     print 'TV shows genres screen'
  1119.     AddOption("Action",True,2321,"action")
  1120.     AddOption("Animation",True,2321,"animation")
  1121.     AddOption("Comedy",True,2321,"comedy")
  1122.     AddOption("Documentary",True,2321,"documentary")
  1123.     AddOption("Drama",True,2321,"drama")
  1124.     AddOption("Family",True,2321,"family")
  1125.     AddOption("Horror",True,2321,"horror")
  1126.     AddOption("Romance",True,2321,"romance")
  1127.     AddOption("Sci-Fi",True,2321,"sci-fi")
  1128.     AddOption("Thriller",True,2321,"thriller")
  1129.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1130.    
  1131. def TVShowGenreScreen(name): #2321
  1132.     print 'TV shows genre ' + str(name) + ' screen'
  1133.     GetFromPath("TV shows", False, TV_SHOWS_DATA_PATH, "/tv/added/" + str(name), str(name))
  1134.     AddOptionsFromFile("TV shows", str(name),30, True)
  1135.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1136.  
  1137. def TVShowPopularScreen(): #2330
  1138.     print 'TV shows popular screen'
  1139.     GetFromPath("TV shows", False, TV_SHOWS_DATA_PATH, "/tv/popular/1", "popular")
  1140.     AddOptionsFromFile("TV shows", "popular",30, True)
  1141.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1142.    
  1143. def TVShowRating(): #2340
  1144.     print 'TV shows rating screen'
  1145.     GetFromPath("TV shows", False, TV_SHOWS_DATA_PATH, "/tv/rating/1", "rating")
  1146.     AddOptionsFromFile("TV shows", "rating",30, True)
  1147.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1148.  
  1149. def TVShowReleased(): #2350
  1150.     print 'TV shows release screen'
  1151.     GetFromPath("TV shows", False, TV_SHOWS_DATA_PATH, "/tv/release/1", "release")
  1152.     AddOptionsFromFile("TV shows", "release",30, True)
  1153.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1154.  
  1155. def TVShowAdded(): #2360
  1156.     print 'TV shows added screen'
  1157.     GetFromPath("TV shows", False, TV_SHOWS_DATA_PATH, "/tv/added/1", "added")
  1158.     AddOptionsFromFile("TV shows", "added",30, True)
  1159.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1160.    
  1161. def TVShowSetupMenu(): #2400
  1162.     print 'TV shows setup screen'
  1163.     AddOption("Add IceLibrary TV shows directory to XBMC sources",False,2410)
  1164.     AddOption("Remove the TV shows directory and all (Icefilms) TV shows",False,2420)
  1165.     AddOption("Delete favorites file",False,2430)
  1166.     AddOption("Install auto update code in autoexec.py",False,2440)
  1167.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1168.    
  1169. def AddTVShowDirectory(): #2410
  1170.     SetupIceLibrary("TV shows")
  1171.    
  1172. def RemoveTVShowDirectory(): #2420
  1173.     RemoveDirectory(TV_SHOWS_PATH)
  1174.    
  1175. def DeleteFavoritesFile(): #2430
  1176.     DeleteFavorites()
  1177.    
  1178. def AddOption(text, isFolder, mode, name=''):
  1179.     li = xbmcgui.ListItem(text)
  1180.     url = sys.argv[0]+'?mode=' + str(mode) + '&name='+  name
  1181.     return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
  1182.    
  1183. def AddOptionsFromFile(type, name, mode, remove_favorites):
  1184.     file_data = LoadData(type, str(name) + ".dat")
  1185.    
  1186.     if remove_favorites:
  1187.         favorites_data = LoadData(type, "favorites.dat")
  1188.         for data in file_data:
  1189.             exclude = False
  1190.             for favorite in favorites_data:
  1191.                 if len(data) > 0 and len(favorite) > 0:
  1192.                     if data[1]==favorite[1]:
  1193.                         exclude = True
  1194.             if not exclude:
  1195.                 if len(data) > 0:
  1196.                     index = file_data.index(data)
  1197.                     text = CleanFileName(data[0], True, use_blanks = False)
  1198.                     AddOption(text,False,str(mode),str(name)+':'+str(index))
  1199.     else:
  1200.         for data in file_data:
  1201.             if len(data) > 0:
  1202.                 index = file_data.index(data)
  1203.                 AddOption(data[0],False,str(mode),str(name)+':'+str(index))
  1204.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1205.        
  1206. ########################
  1207. ### Params and stuff ###
  1208. ########################
  1209.  
  1210. def GetParams():
  1211.     param=[]
  1212.     paramstring=sys.argv[len(sys.argv)-1]
  1213.     if len(paramstring)>=2:
  1214.         cleanedparams=paramstring.replace('?','')
  1215.         if (paramstring[len(paramstring)-1]=='/'):
  1216.                 paramstring=paramstring[0:len(paramstring)-2]
  1217.         pairsofparams=cleanedparams.split('&')
  1218.         param={}
  1219.         for i in range(len(pairsofparams)):
  1220.             splitparams={}
  1221.             splitparams=pairsofparams[i].split('=')
  1222.             if (len(splitparams))==2:
  1223.                 param[splitparams[0]]=splitparams[1]           
  1224.     return param
  1225.  
  1226. params=GetParams()
  1227. url=None
  1228. name=None
  1229. mode=None
  1230. href=None
  1231.  
  1232. try:
  1233.         url=urllib.unquote_plus(params["url"])
  1234. except:
  1235.         pass
  1236. try:
  1237.         name=urllib.unquote_plus(params["name"])
  1238. except:
  1239.         pass
  1240. try:
  1241.         mode=int(params["mode"])
  1242. except:
  1243.         pass
  1244. try:
  1245.         href=urllib.unquote_plus(params["href"])
  1246. except:
  1247.         pass       
  1248. print '==========================PARAMS:\nHREF: %s\nNAME: %s\nMODE: %s\nURL: %s\nMYHANDLE: %s\nPARAMS: %s' % ( href, name, mode, url, sys.argv[1], params )
  1249.  
  1250. if mode==None: #Main menu
  1251.     AddonMenu()
  1252. elif mode==10: #Run stream
  1253.     LoginMegaupload()
  1254.     LaunchSTRM(name, href)
  1255. elif mode==20: #Add movie
  1256.     AddMovie(name)
  1257. elif mode==30: #Add TV show to favorites
  1258.     AddToFavorites(name)
  1259. elif mode==40: #Remove TV show from favorites
  1260.     RemoveFromFavorites(name)
  1261. elif mode==100: #Update the library and set a timer for the next update
  1262.     AutoUpdateLibrary()
  1263. elif mode==1000: #Movies menu
  1264.     MoviesMenu()
  1265. elif mode==1100: #Update movies
  1266.     UpdateMovies()
  1267. elif mode==1200: #Pick movies
  1268.     MoviesListMenu()
  1269. elif mode==1210: #Alphabet list
  1270.     MoviesAlphabetMenu()
  1271. elif mode==1211: #A
  1272.     MoviesLetterScreen(name)
  1273. elif mode==1220: #Genres
  1274.     MovieGenresMenu()
  1275. elif mode==1221: #Action
  1276.     MovieGenreScreen(name)
  1277. elif mode==1230: #Popular
  1278.     MoviePopularScreen()
  1279. elif mode==1240: #Rating
  1280.     MovieRating()
  1281. elif mode==1250: #Release
  1282.     MovieReleased()
  1283. elif mode==1260: #Added
  1284.     MovieAdded()
  1285. elif mode==1300: #Setup movies
  1286.     MoviesSetupMenu()
  1287. elif mode==1310: #Get all movies
  1288.     GetAllMovies()
  1289. elif mode==1320: #Add movie folder to XBMC sources
  1290.     AddMovieDirectory()
  1291. elif mode==1330: #Remove movie folder
  1292.     RemoveMovieDirectory()
  1293. elif mode==1340: #Setup auto update
  1294.     SetupAutoUpdate()
  1295. elif mode==2000: #TV Shows menu
  1296.     TVShowsMenu()
  1297. elif mode==2100: #Update TV Shows
  1298.     UpdateFavorites()
  1299. elif mode==2200: #View favorites
  1300.     FavoritesListScreen()
  1301. elif mode==2300: #Add favorite menu
  1302.     TVShowListMenu()
  1303. elif mode==2310: #Alphabet list
  1304.     TVShowAlphabetMenu()
  1305. elif mode==2311: #A
  1306.     TVShowLetterScreen(name)
  1307. elif mode==2320: #Genres
  1308.     TVShowGenresMenu()
  1309. elif mode==2321: #Action
  1310.     TVShowGenreScreen(name)
  1311. elif mode==2330: #Popular
  1312.     TVShowPopularScreen()
  1313. elif mode==2340: #Rating
  1314.     TVShowRating()
  1315. elif mode==2350: #Release
  1316.     TVShowReleased()
  1317. elif mode==2360: #Added
  1318.     TVShowAdded()
  1319. elif mode==2400: #Setup TV Shows
  1320.     TVShowSetupMenu()
  1321. elif mode==2410: #Add TV shows folder to XBMC sources
  1322.     AddTVShowDirectory()
  1323. elif mode==2420: #Remove TV shows folder
  1324.     RemoveTVShowDirectory()
  1325. elif mode==2430: #Remove favorites file
  1326.     DeleteFavoritesFile()
  1327. elif mode==2440: #Setup auto update
  1328.     SetupAutoUpdate()
Add Comment
Please, Sign In to add comment