Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- #IceLibrary v0.9.6 - Batch 2011-9-15
- #With some code borrowed from Icefilms.info v1.0.10 - anarchintosh / daledude / westcoast13 2011-07-02
- import urllib2, urllib, sys, os, re, random, copy, shutil
- import xbmc,xbmcplugin,xbmcgui,xbmcaddon
- import threading
- import trace
- from mega import megaroutines
- from BeautifulSoup import BeautifulSoup, Tag, NavigableString
- ADDON = xbmcaddon.Addon(id='plugin.video.icelibrary')
- USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
- DATA_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.icelibrary'), '')
- if ADDON.getSetting('movie_custom_directory') == "true":
- MOVIES_PATH = ADDON.getSetting('movie_directory')
- else:
- MOVIES_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.icelibrary/movies'), '')
- if ADDON.getSetting('tv_show_custom_directory') == "true":
- TV_SHOWS_PATH = ADDON.getSetting('tv_show_directory')
- else:
- TV_SHOWS_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.icelibrary/tvshows'), '')
- TV_SHOWS_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.icelibrary/tvshows'), '')
- MOVIES_DATA_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.icelibrary/movies_data'), '')
- TV_SHOWS_DATA_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.icelibrary/tvshows_data'), '')
- DOWNLOAD_PATH = os.path.join(xbmc.translatePath('special://profile/addon_data/plugin.video.icelibrary/download'), '')
- ICEFILMS_URL = ADDON.getSetting('icefilms-url')
- ICEFILMS_AJAX = ICEFILMS_URL + '/membersonly/components/com_iceplayer/video.phpAjaxResp.php'
- EXCLUDE_PROBLEM_EPISODES = True
- 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']
- MOVIE_YEAR = int(ADDON.getSetting('movie_minimum_year'))
- TV_SHOW_YEAR = int(ADDON.getSetting('tv_show_minimum_year'))
- AUTO_BEST_QUALITY = True
- AUTO_DVDRIP_QUALITY = True
- AUTO_PLAY_MIRRORS = True
- AUTO_PLAY_PARTS = False #Not yet implemented
- if ADDON.getSetting('movie_hd_only') == "true":
- MOVIES_HD_ONLY = True
- else:
- MOVIES_HD_ONLY = False
- if ADDON.getSetting('auto_best_quality') == "true":
- AUTO_BEST_QUALITY = True
- else:
- AUTO_BEST_QUALITY = False
- if ADDON.getSetting('auto_dvdrip_quality') == "true":
- AUTO_DVDRIP_QUALITY = True
- else:
- AUTO_DVDRIP_QUALITY = False
- if ADDON.getSetting('auto_mirror') == "true":
- AUTO_PLAY_MIRRORS = True
- else:
- AUTO_PLAY_MIRRORS = False
- #########################
- ### General functions ###
- #########################
- def Notification(title, message):
- xbmc.executebuiltin("XBMC.Notification("+title+","+message+")")
- def RemoveDirectory(dir):
- dialog = xbmcgui.Dialog()
- if dialog.yesno("Remove directory", "Do you want to remove directory?", dir):
- if os.path.exists(dir):
- pDialog = xbmcgui.DialogProgress()
- pDialog.create(' Removing directory...')
- pDialog.update(0, dir)
- shutil.rmtree(dir)
- pDialog.close()
- Notification("Directory removed", dir)
- else:
- Notification("Directory not found", "Can't delete what does not exist.")
- def GetURL(url, params = None, referrer = ICEFILMS_URL, cookie = None, save_cookie = False, silent = False):
- if params:
- req = urllib2.Request(url, params)
- # req.add_header('Content-type', 'application/x-www-form-urlencoded')
- else:
- req = urllib2.Request(url)
- req.add_header('User-Agent', USER_AGENT)
- if referrer:
- req.add_header('Referer', referrer)
- if cookie:
- req.add_header('Cookie', cookie)
- print url
- try:
- response = urllib2.urlopen(req)
- body = response.read()
- except:
- if not silent:
- dialog = xbmcgui.Dialog()
- dialog.ok("Connection failed", "Failed to connect to Icefilms.info", url)
- print "Failed to connect to Icefilms.info"
- return ''
- if save_cookie:
- setcookie = response.info().get('Set-Cookie', None)
- #print "Set-Cookie: %s" % repr(setcookie)
- if setcookie:
- setcookie = re.search('([^=]+=[^=;]+)', setcookie).group(1)
- body = body + '<cookie>' + setcookie + '</cookie>'
- response.close()
- return body
- def PassMovieFilter(year, hd_test):
- if MOVIES_HD_ONLY:
- if hd_test != "HD":
- return False
- if MOVIE_YEAR > year:
- return False
- return True
- def PassTVShowFilter(year):
- if TV_SHOW_YEAR > 1900:
- try:
- year = int(show_name[len(show_name)-5:len(show_name)-1])
- except:
- year = 0
- if year < TV_SHOW_YEAR:
- return False
- return True
- def CreateStreamFile(name, href, dir, remove_year, show_name=''):
- try:
- if len(show_name) > 0:
- show_name = show_name + ' '
- strm_string = "plugin://plugin.video.icelibrary/?href=" + urllib.quote(href) + "&mode=10&name=" + urllib.quote(show_name + name)
- filename = CleanFileName(name, remove_year) + ".strm"
- path = os.path.join(dir, filename)
- file = open(path,'w')
- file.write(strm_string)
- file.close()
- except:
- print "Error while creating strm file for : " + name
- def DeleteFavorites():
- dialog = xbmcgui.Dialog()
- if dialog.yesno("Remove", "Do you want to remove favorites.dat?"):
- print "Removing favorites.dat"
- try:
- os.remove(os.path.join(TV_SHOWS_DATA_PATH, "favorites.dat"))
- Notification("File deleted", "favorites.dat was deleted.")
- except:
- Notification("File not found", "No favorites.dat to delete.")
- def AddToFavorites(name):
- #Needed to use X:N format to not alter the names of the TV shows
- print "Adding " + name + " to favorites."
- split = name.split(":")
- tv_show_data = LoadData("TV shows", split[0] + ".dat")
- to_add = tv_show_data[int(split[1])]
- favorites_data = LoadData("TV shows", "favorites.dat")
- for data in favorites_data:
- if len(data) > 1:
- if data[1] == to_add[1]:
- print to_add[0] + " already exists in favorites."
- Notification("Already exists in favorites", to_add[0] + " already exist in favorites.")
- return
- favorites_data.append(to_add)
- SaveData("TV shows", "favorites.dat", favorites_data)
- print "Successfully added "+ to_add[0] + " to favorites."
- xbmc.executebuiltin("Container.Refresh")
- Notification("Favorite added", to_add[0] + " was added to favorites.")
- def RemoveFromFavorites(name):
- print "Removing " + name + " from favorites."
- favorites_data = LoadData("TV shows", "favorites.dat")
- split = name.split(":")
- to_remove = favorites_data[int(split[1])]
- favorites_data.remove(to_remove)
- SaveData("TV shows", "favorites.dat", favorites_data)
- Notification("Favorite removed", to_remove[0] + " was removed from favorites.")
- print "Successfully removed "+ to_remove[0] + " from favorites."
- xbmc.executebuiltin("Container.Refresh")
- def CreateDirectory(dir_path):
- dir_path = dir_path.strip()
- if not os.path.exists(dir_path):
- os.makedirs(dir_path)
- def CleanFileName(s, remove_year, use_encoding = False, use_blanks = True):
- if remove_year:
- s = s[0:len(s)-7]
- s = s.replace(' (Eng subs)', '')
- s = s.replace(' (eng subs)', '')
- s = s.replace(' (English subs)', '')
- s = s.replace(' (english subs)', '')
- s = s.replace(' (Eng Subs)', '')
- s = s.replace(' (English Subs)', '')
- s = s.replace('&', '&')
- s = s.replace(''', '\'')
- s = s.replace('Æ', 'AE')
- s = s.replace('Ç', 'C')
- s = s.replace('ô', 'o')
- s = s.replace('é', 'e')
- s = s.replace('ë', 'e')
- s = s.replace('í', 'i')
- s = s.replace('î', 'i')
- s = s.replace('¢', 'c')
- s = s.replace('â', 'a')
- s = s.replace('ï', 'i')
- s = s.replace('á', 'a')
- s = s.replace('è', 'e')
- s = s.replace('%2E', '.')
- if use_encoding:
- s = s.replace('"', '%22')
- s = s.replace('*', '%2A')
- s = s.replace('/', '%2F')
- s = s.replace(':', ',')
- s = s.replace('<', '%3C')
- s = s.replace('>', '%3E')
- s = s.replace('?', '%3F')
- s = s.replace('\\', '%5C')
- s = s.replace('|', '%7C')
- s = s.replace('½', '%BD')
- s = s.replace('½', '%BD') #half character
- s = s.replace('³', '%B3')
- s = s.replace('°', '%B0') #degree character
- if use_blanks:
- s = s.replace('"', ' ')
- s = s.replace('*', ' ')
- s = s.replace('/', ' ')
- s = s.replace(':', ' ')
- s = s.replace('<', ' ')
- s = s.replace('>', ' ')
- s = s.replace('?', ' ')
- s = s.replace('\\', ' ')
- s = s.replace('|', ' ')
- s = s.replace('½', ' ')
- s = s.replace('½', ' ') #half character
- s = s.replace('³', ' ')
- s = s.replace('°', ' ') #degree character
- s = s.strip()
- return s
- def FileAlreadyExist(filename, files):
- for file in files:
- if filename == file:
- return True
- return False
- def SetupAutoUpdate():
- source_path = os.path.join(xbmc.translatePath('special://profile/'), 'autoexec.py')
- try:
- file = open(source_path, 'r')
- content=file.read()
- file.close()
- index = content.find("xbmc.executebuiltin('RunScript(plugin.video.icelibrary,\"?mode=100\")')")
- if index > 0:
- Notification("Already set up", "Auto update is already set up in autoexec.py")
- return
- except:
- content = "import xbmc\n"
- content += "\nxbmc.executebuiltin('RunScript(plugin.video.icelibrary,\"?mode=100\")')"
- file = open(source_path, 'w')
- file.write(content)
- file.close()
- print "autoexec.py updated to include IceFilms auto update"
- dialog = xbmcgui.Dialog()
- dialog.ok("Auto update added to autoexec.py", "To complete the setup:", " 1) Activate auto update in IceLibrary configs.", " 2) Restart XBMC.")
- def SetupIceLibrary(type):
- print "Trying to add IceLibrary source paths..."
- source_path = os.path.join(xbmc.translatePath('special://profile/'), 'sources.xml')
- try:
- file = open(source_path, 'r')
- content=file.read()
- file.close()
- soup = BeautifulSoup(content)
- except:
- soup = BeautifulSoup()
- sources_tag = Tag(soup, "sources")
- soup.insert(0, sources_tag)
- if soup.find("video") == None:
- sources = soup.find("sources")
- video_tag = Tag(soup, "video")
- sources.insert(0, video_tag)
- video = soup.find("video")
- if type=="movies":
- CreateDirectory(MOVIES_PATH)
- if len(soup.findAll(text="Movies (Icefilms)")) < 1:
- movie_source_tag = Tag(soup, "source")
- movie_name_tag = Tag(soup, "name")
- movie_name_tag.insert(0, "Movies (Icefilms)")
- MOVIES_PATH_tag = Tag(soup, "path")
- MOVIES_PATH_tag['pathversion'] = 1
- MOVIES_PATH_tag.insert(0, MOVIES_PATH)
- movie_source_tag.insert(0, movie_name_tag)
- movie_source_tag.insert(1, MOVIES_PATH_tag)
- video.insert(2, movie_source_tag)
- if type=="TV shows":
- CreateDirectory(TV_SHOWS_PATH)
- if len(soup.findAll(text="TV Shows (Icefilms)")) < 1:
- tvshow_source_tag = Tag(soup, "source")
- tvshow_name_tag = Tag(soup, "name")
- tvshow_name_tag.insert(0, "TV Shows (Icefilms)")
- tvshow_path_tag = Tag(soup, "path")
- tvshow_path_tag['pathversion'] = 1
- tvshow_path_tag.insert(0, TV_SHOWS_PATH)
- tvshow_source_tag.insert(0, tvshow_name_tag)
- tvshow_source_tag.insert(1, tvshow_path_tag)
- video.insert(2, tvshow_source_tag)
- print soup.prettify()
- string = ""
- for i in soup:
- string = string + str(i)
- file = open(source_path, 'w')
- file.write(str(soup))
- file.close()
- print "Source paths added!"
- dialog = xbmcgui.Dialog()
- dialog.ok("Source folders added", "To complete the setup:", " 1) Restart XBMC.", " 2) Set the content type of added folders.")
- #Appearently this restarted everything and not just XBMC... :(
- #if dialog.yesno("Restart now?", "Do you want to restart XBMC now?"):
- # xbmc.restart()
- ##################
- ### Megaupload ###
- ##################
- def LoginMegaupload():
- #Get whether user has set an account to use.
- Account = ADDON.getSetting('megaupload-account')
- mu=megaroutines.megaupload(DATA_PATH)
- #delete old logins
- mu.delete_login()
- if Account == 'false':
- print 'Account: '+'no account set'
- elif Account == 'true':
- #check for megaupload login and do it
- megauser = ADDON.getSetting('megaupload-username')
- megapass = ADDON.getSetting('megaupload-password')
- login=mu.set_login(megauser,megapass)
- if megapass != '' and megauser != '':
- if login is False:
- print 'Account: '+'login failed'
- Notification("Megaupload", "Login failed. Megaupload will load with no account.")
- elif login is True:
- print 'Account: '+'login succeeded'
- HideSuccessfulLogin = ADDON.getSetting('hide-successful-login-messages')
- if HideSuccessfulLogin == 'false':
- Notification("Megaupload", "Account login successful.")
- if megapass == '' or megauser == '':
- print 'no login details specified, using no account'
- Notification("Megaupload", "Login failed. Megaupload will load with no account.")
- ################
- ### Icefilms ###
- ################
- def GetAllAZ(type, create_strm_files, path, sub_path, silent = False):
- print 'Trying to scrape all ' + type + ' from A-Z categories'
- CreateDirectory(path)
- pDialog = xbmcgui.DialogProgress()
- if not silent:
- pDialog.create(' Scraping ' + type + ', A-Z')
- for character in AZ_DIRECTORIES:
- percent = int((100 * AZ_DIRECTORIES.index(character))/len(AZ_DIRECTORIES))
- if not GetItem(type, ICEFILMS_URL + sub_path + character, character, create_strm_files, pDialog, 0, silent):
- break
- if not silent:
- if (pDialog.iscanceled()):
- print 'Canceled scraping'
- return
- pDialog.close()
- print 'Scraping complete!'
- def GetFromPath(type, create_strm_files, path, sub_path, page_name, silent = False):
- print 'Scraping ' + type + ' from ' + page_name
- pDialog = xbmcgui.DialogProgress()
- if not silent:
- pDialog.create(' Scraping newly added ' + type)
- CreateDirectory(path)
- GetItem(type, ICEFILMS_URL + sub_path, page_name, create_strm_files, pDialog, 0, silent)
- if not silent:
- if (pDialog.iscanceled()):
- print 'Canceled scraping'
- else:
- pDialog.close()
- print 'Scraping complete!'
- def GetItem(type, page, page_name, create_strm_files, pDialog, percent, silent = False):
- print "Scanning " + page
- if not silent:
- pDialog.update(percent, page_name, '')
- pagedata = GetURL(page, silent = silent)
- if pagedata=='':
- return False
- soup = BeautifulSoup(pagedata)
- list = soup.find("span", { "class" : "list" })
- stars = list.findAll("img", { "class" : "star" })
- data = []
- for star in stars:
- a = star.findNextSibling('a')
- name = str(a.string)
- if not silent:
- if (pDialog.iscanceled()):
- return False
- pDialog.update(percent, "Scraping " + type + " " + page_name, name)
- try:
- year = int(name[len(name)-5:len(name)-1])
- except:
- year = 0
- href = a['href']
- data.append([name,href])
- if type=="movies":
- hd_test = a.nextSibling.string
- passed_filter = PassMovieFilter(year, hd_test)
- if passed_filter and create_strm_files:
- CreateStreamFile(name, href, MOVIES_PATH, False)
- if type=="TV shows":
- passed_filter = PassTVShowFilter(year)
- if passed_filter and create_strm_files:
- if not GetEpisodes(name, href, silent):
- return False
- SaveData(type, page_name + ".dat", data)
- return True
- def GetFavorites(file_name, silent = False):
- print "Fetching favorites"
- pDialog = xbmcgui.DialogProgress()
- if not silent:
- pDialog.create(' Scraping favorites')
- tv_show_data = LoadData("TV shows", file_name)
- for data in tv_show_data:
- percent = int((100 * tv_show_data.index(data))/len(tv_show_data))
- if not silent:
- if (pDialog.iscanceled()):
- return
- pDialog.update(percent, "Scraping TV show", data[0])
- GetEpisodes(data[0], data[1], silent)
- def AddMovie(name):
- #Needed to use X:N format to not alter the names of movie
- print "Adding movie " + name
- CreateDirectory(MOVIES_PATH)
- split = name.split(":")
- movies_data = LoadData("movies", split[0] + ".dat")
- to_add = movies_data[int(split[1])]
- CreateStreamFile(to_add[0], to_add[1], MOVIES_PATH, False)
- Notification("Movie added", to_add[0])
- def SaveData(type, file_name, data):
- s = ''
- for d in data:
- try:
- s = s + d[0] + "\t" + d[1] + "\n"
- except:
- print "Got a problem when saving data."
- if type=="movies":
- CreateDirectory(MOVIES_DATA_PATH)
- path = os.path.join(MOVIES_DATA_PATH, file_name.lower())
- if type=="TV shows":
- CreateDirectory(TV_SHOWS_DATA_PATH)
- path = os.path.join(TV_SHOWS_DATA_PATH, file_name.lower())
- file = open(path,'w')
- file.write(s)
- file.close()
- def LoadData(type, file_name):
- if type=="movies":
- directory = MOVIES_DATA_PATH
- if type=="TV shows":
- directory = TV_SHOWS_DATA_PATH
- CreateDirectory(directory)
- try:
- path = os.path.join(directory, file_name.lower())
- fh = open(path, 'r')
- contents=fh.read()
- fh.close()
- except:
- return []
- file_data = []
- file_strings = contents.split("\n")
- for data_text in file_strings:
- data = data_text.split("\t")
- if len(data) > 1:
- file_data.append([data[0],data[1]])
- return file_data
- def GetEpisodes(show_name, href, silent = False):
- page = ICEFILMS_URL + href
- pagedata = GetURL(page, silent = silent)
- if pagedata=='':
- return False
- month = [' ','Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
- month_nr = [' ','01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12']
- soup = BeautifulSoup(pagedata)
- list = soup.find("span", { "class" : "list" })
- stars = list.findAll("img", { "class" : "star" })
- year_loc = soup.findAll( "a", {"name" : re.compile(r"[0-9]{4}")})
- print year_loc
- for y in year_loc:
- print y
- season = y['name']
- print season
- b = y.parent.nextSibling
- while getattr(b, 'name', None) != 'h3':
- try:
- if getattr(b, 'name', None) == 'img':
- a = b.findNextSibling('a')
- name_split = re.split(r'[^a-zA-Z0-9_]',str(a.string))
- try:
- name = season+'.'+month_nr[month.index(name_split[0])]+'.'+name_split[1]
- except ValueError:
- name = name_split[1]
- href = a['href']
- show_path = os.path.join(TV_SHOWS_PATH, CleanFileName(show_name, True, use_encoding = True))
- CreateDirectory(show_path)
- season_path = os.path.join(show_path, season)
- CreateDirectory(season_path)
- sname = CleanFileName(show_name, True, False, False)
- CreateStreamFile(name, href, season_path, False, show_name=sname)
- b = b.nextSibling
- except AttributeError:
- break
- for star in stars:
- a = star.findNextSibling('a')
- name = str(a.string)
- href = a['href']
- save_episode = True
- #Get the season number
- season = name.split("x")[0]
- try:
- int(season)
- except:
- if EXCLUDE_PROBLEM_EPISODES:
- #print show_name, season
- save_episode = False
- else:
- season = "0"
- if save_episode:
- show_path = os.path.join(TV_SHOWS_PATH, CleanFileName(show_name, True, use_encoding = True))
- CreateDirectory(show_path)
- season_path = os.path.join(show_path, season)
- CreateDirectory(season_path)
- sname = CleanFileName(show_name, True, False, False)
- CreateStreamFile(name, href, season_path, False, show_name=sname)
- return True
- def LaunchSTRM(name, href):
- print 'Running .strm'
- print name
- name = CleanFileName(name, False, use_encoding = False)
- url = ICEFILMS_URL + urllib2.unquote(href)
- pagedata = GetURL(url)
- if pagedata=='':
- return
- match=re.compile('/membersonly/components/com_iceplayer/(.+?)" width=').findall(pagedata)
- match[0]=re.sub('%29',')',match[0])
- match[0]=re.sub('%28','(',match[0])
- for url in match:
- mirrorpageurl = ICEFILMS_URL + '/membersonly/components/com_iceplayer/' + url
- print mirrorpageurl
- mirrorpage=GetURL(mirrorpageurl, save_cookie = True)
- if pagedata=='':
- return
- # check for recaptcha
- has_recaptcha = CheckForCaptcha(mirrorpage)
- if has_recaptcha is False:
- HandleOptions(name, mirrorpage)
- elif has_recaptcha is True:
- return #TODO: Handle captchas
- def CheckForCaptcha(url):
- print "Looking for a captcha..."
- return False
- def HandleOptions(name, mirrorpage):
- dialog = xbmcgui.Dialog()
- soup = BeautifulSoup(mirrorpage)
- #Wanted to replace this with BautifulSoup ... but I'm to lazy :D
- try:
- sec = re.search("f\.lastChild\.value=\"([^']+)\",a", mirrorpage).group(1)
- t = re.search('"&t=([^"]+)",', mirrorpage).group(1)
- args = {'iqs': '', 'url': '', 'cap': ''}
- args['sec'] = sec
- args['t'] = t
- cookie = soup.find("cookie").string
- except:
- dialog = xbmcgui.Dialog()
- dialog.ok("Unexpected page content", "Unexpected page content returned from Icefilms.info")
- return
- quality_list = soup.findAll("div", { "class" : "ripdiv" })
- quality_options = []
- for quality in quality_list:
- quality_options.append(quality.b.string)
- print quality_options
- if AUTO_BEST_QUALITY:
- quality_select = 0
- elif AUTO_DVDRIP_QUALITY:
- if u'DVDRip / Standard Def' in quality_options:
- quality_select=quality_options.index(u'DVDRip / Standard Def')
- else:
- quality_select = dialog.select('Unable to understand quality options, pelase select quality', quality_options)
- print quality_select
- if quality_select < 0:
- return
- else:
- quality_select = dialog.select('Select quality', quality_options)
- print quality_select
- if quality_select < 0:
- return
- for quality in quality_list:
- if quality_options[quality_select] == quality.b.string:
- quality_choice = quality
- break
- mirror_list = quality_choice.findAll("p")
- mirror_options = []
- mirror_id = []
- multiple_parts = False
- for mirror in mirror_list:
- if len(mirror.contents) > 0:
- if len(mirror.contents[0]) > 2: #Multi part
- links = mirror.findAll("a")
- if AUTO_PLAY_MIRRORS and AUTO_PLAY_PARTS:
- part_urls = []
- failed = False
- for link in links:
- part_id = link['onclick'][3:len(link['onclick'])-1]
- part_url = GetSource(int(part_id), args, cookie)
- if part_url == None:
- failed = True
- break
- part_urls.append(part_url)
- if not failed:
- url1 = HandleVidlink(part_urls[0])[0]
- if len(part_urls) > 1:
- url2 = HandleVidlink(part_urls[1])[0]
- else:
- url2 = ''
- if len(part_urls) > 2:
- url3 = HandleVidlink(part_urls[2])[0]
- else:
- url3 = ''
- if len(part_urls) > 3:
- url4 = HandleVidlink(part_urls[3])[0]
- else:
- url4 = ''
- StreamSource(name, url1, url2, url3, url4)
- return
- else:
- multiple_parts = True
- for link in links:
- print mirror.next
- mirror_options.append(mirror.next + link.next)
- mirror_id.append(link['onclick'][3:len(link['onclick'])-1])
- else: #Single part
- link = mirror.find("a")
- if AUTO_PLAY_MIRRORS:
- mega_upload_url = GetSource(int(link['onclick'][3:len(link['onclick'])-1]), args, cookie)
- page=HandleVidlink(mega_upload_url)
- if page != None:
- resolved_url= page[0]
- StreamSource(name, resolved_url)
- return
- else:
- mirror_options.append(link.next[0:len(link.next)-2])
- mirror_id.append(link['onclick'][3:len(link['onclick'])-1])
- if AUTO_PLAY_MIRRORS and not multiple_parts: #Failed to play any mirror.
- dialog.ok("Streaming failed", "No working mirror found")
- return
- print mirror_options;
- print mirror_id;
- mirror_select = dialog.select('Select mirror', mirror_options)
- print mirror_select
- if mirror_select < 0:
- return
- #AUTO_PLAY_PARTS
- mega_upload_url = GetSource(int(mirror_id[mirror_select]), args, cookie)
- page=HandleVidlink(mega_upload_url)
- if page == None:
- return
- resolved_url= page[0]
- StreamSource(name, resolved_url)
- def GetSource(id, args, cookie):
- m = random.randrange(100, 300) * -1
- s = random.randrange(5, 50)
- params = copy.copy(args)
- params['id'] = id
- params['m'] = m
- params['s'] = s
- paramsenc = urllib.urlencode(params)
- body = GetURL(ICEFILMS_AJAX, params = paramsenc, cookie = cookie)
- print 'response: %s' % body
- source = re.search('url=(http[^&]+)', body).group(1)
- url = urllib.unquote(source)
- print 'url: %s' % url
- return url
- def StreamSource(name,url1, url2 = '', url3 = '', url4 = ''):
- print 'attempting to stream file'
- WaitIf()
- #print url1
- #print url2
- #print url3
- #print url4
- download = False #Can't get it to work :\
- if not download:
- #pl=xbmc.PlayList(1)
- #pl.clear()
- list_item = xbmcgui.ListItem(name, iconImage="DefaultVideoBig.png", thumbnailImage='', path=url1)
- #xbmc.PlayList(1).add(url1, list_item)
- #print 'thread1 started'
- #if not url2=='':
- # xbmc.PlayList(1).add(url2, list_item)
- # print 'thread2 started'
- #if not url3=='':
- # xbmc.PlayList(1).add(url3, list_item)
- # print 'thread3 started'
- #if not url4=='':
- # xbmc.PlayList(1).add(url4, list_item)
- # print 'thread4 started'
- try:
- #xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),True,pl)
- #xbmc.Player().play(pl)
- list_item.setProperty( "IsPlayable", "true" )
- xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),True,list_item)
- except:
- print 'file streaming failed'
- Notification("Streaming failed", "Streaming failed")
- else:
- print 'starting threads'
- CreateDirectory(DOWNLOAD_PATH)
- pl=xbmc.PlayList(1)
- pl.clear()
- list_item = xbmcgui.ListItem('', iconImage="DefaultVideoBig.png", thumbnailImage='')
- d_path1 = os.path.join(DOWNLOAD_PATH, 'part1.avi')
- d_thread1 = KThread(target=urllib.urlretrieve, args=(url1, d_path1))
- d_thread1.start()
- xbmc.PlayList(1).add(d_path1, list_item)
- print 'thread1 started'
- if not url2=='':
- d_path2 = os.path.join(DOWNLOAD_PATH, 'part2.avi')
- d_thread2 = KThread(target=urllib.urlretrieve, args=(url2, d_path2))
- d_thread2.start()
- xbmc.PlayList(1).add(d_path2, list_item)
- print 'thread2 started'
- if not url3=='':
- d_path3 = os.path.join(DOWNLOAD_PATH, 'part3.avi')
- d_thread3 = KThread(target=urllib.urlretrieve, args=(url3, d_path3))
- d_thread3.start()
- xbmc.PlayList(1).add(d_path3, list_item)
- print 'thread3 started'
- if not url4=='':
- d_path4 = os.path.join(DOWNLOAD_PATH, 'part4.avi')
- d_thread4 = KThread(target=urllib.urlretrieve, args=(url4, d_path4))
- d_thread4.start()
- xbmc.PlayList(1).add(d_path4, list_item)
- print 'thread4 started'
- #xbmc.Player().play(pl)
- xbmc.sleep(10000) # Set a 10 second delay to allow the file start downloading a bit.
- print 'wait completed'
- #list_item = xbmcgui.ListItem('', iconImage="DefaultVideoBig.png", thumbnailImage='', path=d_path1)
- #list_item.setProperty( "IsPlayable", "true" )
- #xbmcplugin.setResolvedUrl(int(sys.argv[ 1 ]),True,pl)
- xbmc.Player().play(pl)
- #thread2 = threading.Thread(target=xbmcplugin.setResolvedUrl, args=(int(sys.argv[ 1 ]),True,list_item))
- #thread2 = threading.Thread(target=xbmc.Player( xbmc.PLAYER_CORE_DVDPLAYER ).play, args=(d_path, list_item))
- while xbmc.Player().isPlayingVideo():
- pass
- while os.path.exists(d_path1):
- try:
- os.remove(d_path1)
- break
- except:
- pass
- class KThread(threading.Thread):
- def __init__(self, *args, **keywords):
- threading.Thread.__init__(self, *args, **keywords)
- self.killed = False
- def start(self):
- self.__run_backup = self.run
- self.run = self.__run
- threading.Thread.start(self)
- def __run(self):
- sys.settrace(self.globaltrace)
- self.__run_backup()
- self.run = self.__run_backup
- def globaltrace(self, frame, why, arg):
- if why == 'call':
- return self.localtrace
- else:
- return None
- def localtrace(self, frame, why, arg):
- if self.killed:
- if why == 'line':
- raise SystemExit()
- return self.localtrace
- def kill(self):
- self.killed = True
- def HandleVidlink(url):
- #video link preflight, pays attention to settings / checks if url is mega or 2shared
- ismega = re.search('\.megaupload\.com/', url)
- is2shared = re.search('\.2shared\.com/', url)
- if ismega is not None:
- WaitIf()
- mu=megaroutines.megaupload(DATA_PATH)
- link=mu.resolve_megaup(url)
- finished = DoWait(link[3], link[4])
- if finished == True:
- return link
- else:
- return None
- elif is2shared is not None:
- Notify('big','2Shared','2Shared is not supported by this addon. (Yet)','')
- return False
- #shared2url=SHARED2_HANDLER(url)
- #return shared2url
- def WaitIf():
- #killing playback is necessary if switching playing of one megaup/2share stream to another
- if xbmc.Player().isPlayingVideo() == True:
- xbmc.Player().stop()
- def DoWait(account, wait_time):
- # do the necessary wait, with a nice notice and pre-set waiting time. I have found the below waiting times to never fail.
- if account == 'platinum':
- return HandleWait(int(wait_time),'Megaupload','Loading video with your *Platinum* account.')
- elif account == 'premium':
- return HandleWait(int(wait_time),'Megaupload','Loading video with your *Premium* account.')
- elif account == 'free':
- return HandleWait(int(wait_time),'Megaupload Free User','Loading video with your free account.')
- else:
- return HandleWait(int(wait_time),'Megaupload','Loading video.')
- def HandleWait(time_to_wait,title,text):
- print 'waiting '+str(time_to_wait)+' secs'
- pDialog = xbmcgui.DialogProgress()
- ret = pDialog.create(' '+title)
- secs=0
- percent=0
- cancelled = False
- while secs < time_to_wait:
- secs = secs + 1
- percent = int((100 * secs)/time_to_wait)
- secs_left = str((time_to_wait - secs))
- remaining_display = ' Wait '+secs_left+' seconds for the video stream to activate...'
- pDialog.update(percent,' '+text,remaining_display)
- xbmc.sleep(1000)
- if (pDialog.iscanceled()):
- cancelled = True
- break
- if cancelled == True:
- print 'wait cancelled'
- return False
- else:
- print 'done waiting'
- return True
- ###################
- ### Auto-update ###
- ###################
- def AutoUpdateLibrary():
- if ADDON.getSetting('auto_update') == "false":
- return
- print "IceLibrary running an automatic update"
- xbmc.executebuiltin('CancelAlarm(updatelibrary)')
- timer_amounts = {}
- timer_amounts['0'] = '120'
- timer_amounts['1'] = '300'
- timer_amounts['2'] = '600'
- timer_amounts['3'] = '900'
- timer_amounts['4'] = '1440'
- #only do this if we are not playing anything
- if xbmc.Player().isPlaying() == False:
- if ADDON.getSetting('update_tvshows') == "true":
- UpdateFavorites(True)
- #xbmc.executebuiltin('UpdateLibrary(video,' + TV_SHOWS_PATH + ')')
- if ADDON.getSetting('update_movies') == "true":
- UpdateMovies(True)
- #xbmc.executebuiltin('UpdateLibrary(video,' + MOVIES_PATH + ')')
- xbmc.executebuiltin('UpdateLibrary(video)')
- #reset the timer
- xbmc.executebuiltin('AlarmClock(updatelibrary,XBMC.RunScript(plugin.video.icelibrary,"?mode=100"),' +
- timer_amounts[ADDON.getSetting('update_timer')] + ',true)')
- print "IceLibrary update complete"
- ##################
- ### Addon menu ###
- ##################
- def AddonMenu(): #homescreen
- print 'IceLibrary menu'
- AddOption('Movies',True, 1000)
- AddOption('TV shows',True, 2000)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def MoviesMenu(): #1000
- print 'Movie menu'
- AddOption('Update movies',False, 1100)
- AddOption('Pick movies',True, 1200)
- AddOption('Setup movies',True, 1300)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def UpdateMovies(silent = False): #1100
- GetFromPath("movies", True, MOVIES_PATH, "/movies/added/1", 'added', silent)
- def MoviesListMenu(): #1200
- AddOption('A-Z',True, 1210)
- AddOption('Genres',True, 1220)
- AddOption('Popular',True, 1230)
- AddOption('Highly rated',True, 1240)
- AddOption('Newly released',True, 1250)
- AddOption('Newly added',True, 1260)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def MoviesAlphabetMenu(): #1210
- print 'Movies alphabet screen'
- for character in AZ_DIRECTORIES:
- AddOption(character,True,1211,character)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def MoviesLetterScreen(name): #1211
- print 'Movies letter ' + str(name) + ' screen'
- GetFromPath("movies", False, MOVIES_DATA_PATH, "/movies/a-z/" + str(name), str(name))
- AddOptionsFromFile("movies", str(name), 20, False)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def MovieGenresMenu(): #1220
- print 'Movies genres screen'
- AddOption("Action",True,1221,"action")
- AddOption("Animation",True,1221,"animation")
- AddOption("Comedy",True,1221,"comedy")
- AddOption("Documentary",True,1221,"documentary")
- AddOption("Drama",True,1221,"drama")
- AddOption("Family",True,1221,"family")
- AddOption("Horror",True,1221,"horror")
- AddOption("Romance",True,1221,"romance")
- AddOption("Sci-Fi",True,1221,"sci-fi")
- AddOption("Thriller",True,1221,"thriller")
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def MovieGenreScreen(name): #1221
- print 'Movies genre ' + str(name) + ' screen'
- GetFromPath("movies", False, MOVIES_DATA_PATH, "/movies/added/" + str(name), str(name))
- AddOptionsFromFile("movies", str(name),20, False)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def MoviePopularScreen(): #1230
- print 'Movies popular screen'
- GetFromPath("movies", False, MOVIES_DATA_PATH, "/movies/popular/1", "popular")
- AddOptionsFromFile("movies", "popular",20, False)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def MovieRating(): #1240
- print 'Movies rating screen'
- GetFromPath("movies", False, MOVIES_DATA_PATH, "/movies/rating/1", "rating")
- AddOptionsFromFile("movies", "rating",20, False)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def MovieReleased(): #1250
- print 'Movies release screen'
- GetFromPath("movies", False, MOVIES_DATA_PATH, "/movies/release/1", "release")
- AddOptionsFromFile("movies", "release",20, False)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def MovieAdded(): #1260
- print 'Movies added screen'
- GetFromPath("movies", False, MOVIES_DATA_PATH, "/movies/added/1", "added")
- AddOptionsFromFile("movies", "added",20, False)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def MoviesSetupMenu(): #1300
- print 'Movies setup screen'
- AddOption("Scrape all movies",False,1310)
- AddOption("Add IceLibrary movie directory to XBMC sources",False,1320)
- AddOption("Remove the movie directory and all (Icefilms) movie files",False,1330)
- AddOption("Install auto update code in autoexec.py",False,1340)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def GetAllMovies(): #1310
- GetAllAZ("movies", True, MOVIES_PATH, "/movies/a-z/")
- def AddMovieDirectory(): #1320
- SetupIceLibrary("movies")
- def RemoveMovieDirectory(): #1330
- RemoveDirectory(MOVIES_PATH)
- def TVShowsMenu(): #2000
- print 'TV shows menu'
- AddOption('Update favorites',True, 2100)
- AddOption('View favorites',True, 2200)
- AddOption('Add favorites',True, 2300)
- AddOption('Setup TV shows',True, 2400)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def UpdateFavorites(silent = False): #2100
- GetFavorites("favorites.dat", silent)
- def FavoritesListScreen(): #2200
- AddOptionsFromFile("TV shows", "favorites",40, False)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def TVShowListMenu(): #2300
- AddOption('A-Z',True, 2310)
- AddOption('Genres',True, 2320)
- AddOption('Popular',True, 2330)
- AddOption('Highly rated',True, 2340)
- AddOption('Newly released',True, 2350)
- AddOption('Newly added',True, 2360)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def TVShowAlphabetMenu(): #2310
- print 'TV shows alphabet screen'
- for character in AZ_DIRECTORIES:
- AddOption(character,True,2311,character)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def TVShowLetterScreen(name): #2311
- print 'TV shows letter ' + str(name) + ' screen'
- GetFromPath("TV shows", False, TV_SHOWS_DATA_PATH, "/tv/a-z/" + str(name), str(name))
- AddOptionsFromFile("TV shows", str(name),30, True)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def TVShowGenresMenu(): #2320
- print 'TV shows genres screen'
- AddOption("Action",True,2321,"action")
- AddOption("Animation",True,2321,"animation")
- AddOption("Comedy",True,2321,"comedy")
- AddOption("Documentary",True,2321,"documentary")
- AddOption("Drama",True,2321,"drama")
- AddOption("Family",True,2321,"family")
- AddOption("Horror",True,2321,"horror")
- AddOption("Romance",True,2321,"romance")
- AddOption("Sci-Fi",True,2321,"sci-fi")
- AddOption("Thriller",True,2321,"thriller")
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def TVShowGenreScreen(name): #2321
- print 'TV shows genre ' + str(name) + ' screen'
- GetFromPath("TV shows", False, TV_SHOWS_DATA_PATH, "/tv/added/" + str(name), str(name))
- AddOptionsFromFile("TV shows", str(name),30, True)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def TVShowPopularScreen(): #2330
- print 'TV shows popular screen'
- GetFromPath("TV shows", False, TV_SHOWS_DATA_PATH, "/tv/popular/1", "popular")
- AddOptionsFromFile("TV shows", "popular",30, True)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def TVShowRating(): #2340
- print 'TV shows rating screen'
- GetFromPath("TV shows", False, TV_SHOWS_DATA_PATH, "/tv/rating/1", "rating")
- AddOptionsFromFile("TV shows", "rating",30, True)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def TVShowReleased(): #2350
- print 'TV shows release screen'
- GetFromPath("TV shows", False, TV_SHOWS_DATA_PATH, "/tv/release/1", "release")
- AddOptionsFromFile("TV shows", "release",30, True)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def TVShowAdded(): #2360
- print 'TV shows added screen'
- GetFromPath("TV shows", False, TV_SHOWS_DATA_PATH, "/tv/added/1", "added")
- AddOptionsFromFile("TV shows", "added",30, True)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def TVShowSetupMenu(): #2400
- print 'TV shows setup screen'
- AddOption("Add IceLibrary TV shows directory to XBMC sources",False,2410)
- AddOption("Remove the TV shows directory and all (Icefilms) TV shows",False,2420)
- AddOption("Delete favorites file",False,2430)
- AddOption("Install auto update code in autoexec.py",False,2440)
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- def AddTVShowDirectory(): #2410
- SetupIceLibrary("TV shows")
- def RemoveTVShowDirectory(): #2420
- RemoveDirectory(TV_SHOWS_PATH)
- def DeleteFavoritesFile(): #2430
- DeleteFavorites()
- def AddOption(text, isFolder, mode, name=''):
- li = xbmcgui.ListItem(text)
- url = sys.argv[0]+'?mode=' + str(mode) + '&name='+ name
- return xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=li, isFolder=isFolder)
- def AddOptionsFromFile(type, name, mode, remove_favorites):
- file_data = LoadData(type, str(name) + ".dat")
- if remove_favorites:
- favorites_data = LoadData(type, "favorites.dat")
- for data in file_data:
- exclude = False
- for favorite in favorites_data:
- if len(data) > 0 and len(favorite) > 0:
- if data[1]==favorite[1]:
- exclude = True
- if not exclude:
- if len(data) > 0:
- index = file_data.index(data)
- text = CleanFileName(data[0], True, use_blanks = False)
- AddOption(text,False,str(mode),str(name)+':'+str(index))
- else:
- for data in file_data:
- if len(data) > 0:
- index = file_data.index(data)
- AddOption(data[0],False,str(mode),str(name)+':'+str(index))
- xbmcplugin.endOfDirectory(int(sys.argv[1]))
- ########################
- ### Params and stuff ###
- ########################
- def GetParams():
- param=[]
- paramstring=sys.argv[len(sys.argv)-1]
- if len(paramstring)>=2:
- cleanedparams=paramstring.replace('?','')
- if (paramstring[len(paramstring)-1]=='/'):
- paramstring=paramstring[0:len(paramstring)-2]
- pairsofparams=cleanedparams.split('&')
- param={}
- for i in range(len(pairsofparams)):
- splitparams={}
- splitparams=pairsofparams[i].split('=')
- if (len(splitparams))==2:
- param[splitparams[0]]=splitparams[1]
- return param
- params=GetParams()
- url=None
- name=None
- mode=None
- href=None
- try:
- url=urllib.unquote_plus(params["url"])
- except:
- pass
- try:
- name=urllib.unquote_plus(params["name"])
- except:
- pass
- try:
- mode=int(params["mode"])
- except:
- pass
- try:
- href=urllib.unquote_plus(params["href"])
- except:
- pass
- print '==========================PARAMS:\nHREF: %s\nNAME: %s\nMODE: %s\nURL: %s\nMYHANDLE: %s\nPARAMS: %s' % ( href, name, mode, url, sys.argv[1], params )
- if mode==None: #Main menu
- AddonMenu()
- elif mode==10: #Run stream
- LoginMegaupload()
- LaunchSTRM(name, href)
- elif mode==20: #Add movie
- AddMovie(name)
- elif mode==30: #Add TV show to favorites
- AddToFavorites(name)
- elif mode==40: #Remove TV show from favorites
- RemoveFromFavorites(name)
- elif mode==100: #Update the library and set a timer for the next update
- AutoUpdateLibrary()
- elif mode==1000: #Movies menu
- MoviesMenu()
- elif mode==1100: #Update movies
- UpdateMovies()
- elif mode==1200: #Pick movies
- MoviesListMenu()
- elif mode==1210: #Alphabet list
- MoviesAlphabetMenu()
- elif mode==1211: #A
- MoviesLetterScreen(name)
- elif mode==1220: #Genres
- MovieGenresMenu()
- elif mode==1221: #Action
- MovieGenreScreen(name)
- elif mode==1230: #Popular
- MoviePopularScreen()
- elif mode==1240: #Rating
- MovieRating()
- elif mode==1250: #Release
- MovieReleased()
- elif mode==1260: #Added
- MovieAdded()
- elif mode==1300: #Setup movies
- MoviesSetupMenu()
- elif mode==1310: #Get all movies
- GetAllMovies()
- elif mode==1320: #Add movie folder to XBMC sources
- AddMovieDirectory()
- elif mode==1330: #Remove movie folder
- RemoveMovieDirectory()
- elif mode==1340: #Setup auto update
- SetupAutoUpdate()
- elif mode==2000: #TV Shows menu
- TVShowsMenu()
- elif mode==2100: #Update TV Shows
- UpdateFavorites()
- elif mode==2200: #View favorites
- FavoritesListScreen()
- elif mode==2300: #Add favorite menu
- TVShowListMenu()
- elif mode==2310: #Alphabet list
- TVShowAlphabetMenu()
- elif mode==2311: #A
- TVShowLetterScreen(name)
- elif mode==2320: #Genres
- TVShowGenresMenu()
- elif mode==2321: #Action
- TVShowGenreScreen(name)
- elif mode==2330: #Popular
- TVShowPopularScreen()
- elif mode==2340: #Rating
- TVShowRating()
- elif mode==2350: #Release
- TVShowReleased()
- elif mode==2360: #Added
- TVShowAdded()
- elif mode==2400: #Setup TV Shows
- TVShowSetupMenu()
- elif mode==2410: #Add TV shows folder to XBMC sources
- AddTVShowDirectory()
- elif mode==2420: #Remove TV shows folder
- RemoveTVShowDirectory()
- elif mode==2430: #Remove favorites file
- DeleteFavoritesFile()
- elif mode==2440: #Setup auto update
- SetupAutoUpdate()
Add Comment
Please, Sign In to add comment