PageRenderTime 36ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/default.py

https://bitbucket.org/wesada/xbmc-icefilms
Python | 2278 lines | 2212 code | 36 blank | 30 comment | 16 complexity | dc4570ae00bc0c3bddc2854e7b8891c6 MD5 | raw file
  1. #!/usr/bin/python
  2. #Icefilms.info v1.0.10 - anarchintosh / daledude / westcoast13 2011-07-02
  3. # Quite convoluted code. Needs a good cleanup for v1.1.0
  4. #standard module imports
  5. import sys,os
  6. import time,re
  7. import urllib,urllib2,cookielib,base64
  8. import xbmc,xbmcplugin,xbmcgui,xbmcaddon
  9. import unicodedata
  10. import random
  11. import copy
  12. #imports of things bundled with addon
  13. import clean_dirs,htmlcleaner
  14. from xgoogle.BeautifulSoup import BeautifulSoup,BeautifulStoneSoup
  15. from xgoogle.search import GoogleSearch
  16. from mega import megaroutines
  17. from metautils import metahandlers
  18. def getSiteURL():
  19. ao = xbmcaddon.Addon(id='plugin.video.icefilms')
  20. url = ao.getSetting('icefilms-url')
  21. return url
  22. # global constants
  23. ICEFILMS_URL = getSiteURL()
  24. ICEFILMS_AJAX = ICEFILMS_URL+'membersonly/components/com_iceplayer/video.phpAjaxResp.php'
  25. ICEFILMS_REFERRER = 'http://www.icefilms.info'
  26. USER_AGENT = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3'
  27. def xbmcpath(path,filename):
  28. translatedpath = os.path.join(xbmc.translatePath( path ), ''+filename+'')
  29. return translatedpath
  30. def Notify(typeq,title,message,times):
  31. #simplified way to call notifications. common notifications here.
  32. if title == '':
  33. title='Icefilms Notification'
  34. if typeq == 'small':
  35. if times == '':
  36. times='5000'
  37. smallicon=handle_file('smallicon')
  38. xbmc.executebuiltin("XBMC.Notification("+title+","+message+","+times+","+smallicon+")")
  39. if typeq == 'big':
  40. dialog = xbmcgui.Dialog()
  41. dialog.ok(' '+title+' ', ' '+message+' ')
  42. if typeq == 'megaalert1':
  43. ip = xbmc.getIPAddress()
  44. title='Megaupload Alert for IP '+ip
  45. message="Either you've reached your daily download limit\n or your IP is already downloading a file."
  46. dialog = xbmcgui.Dialog()
  47. dialog.ok(' '+title+' ', ' '+message+' ')
  48. if typeq == 'megaalert2':
  49. ip = xbmc.getIPAddress()
  50. title='Megaupload Info for IP '+ip
  51. message="No problems! You have not reached your limit."
  52. dialog = xbmcgui.Dialog()
  53. dialog.ok(' '+title+' ', ' '+message+' ')
  54. addon = xbmcaddon.Addon(id='plugin.video.icefilms')
  55. #get path to me
  56. icepath = addon.getAddonInfo('path')
  57. #paths etc need sorting out. do for v1.1.0
  58. icedatapath = 'special://profile/addon_data/plugin.video.icefilms'
  59. metapath = icedatapath+'/mirror_page_meta_cache'
  60. downinfopath = icedatapath+'/downloadinfologs'
  61. transdowninfopath = xbmcpath(downinfopath,'')
  62. transmetapath = xbmcpath(metapath,'')
  63. translatedicedatapath = xbmcpath(icedatapath,'')
  64. art = icepath+'/resources/art'
  65. def handle_file(filename,getmode=''):
  66. #bad python code to add a get file routine.
  67. if filename == 'captcha':
  68. return_file = xbmcpath(icedatapath,'CaptchaChallenge.txt')
  69. elif filename == 'mirror':
  70. return_file = xbmcpath(icedatapath,'MirrorPageSource.txt')
  71. elif filename == 'episodesrc':
  72. return_file = xbmcpath(icedatapath,'EpisodePageSource.txt')
  73. elif filename == 'pageurl':
  74. return_file = xbmcpath(icedatapath,'PageURL.txt')
  75. elif filename == 'mediapath':
  76. return_file = xbmcpath(downinfopath,'MediaPath.txt')
  77. #extra thing to provide show name with year if going via episode list.
  78. elif filename == 'mediatvshowname':
  79. return_file = xbmcpath(downinfopath,'TVShowName.txt')
  80. #extra thing to provide season name.
  81. elif filename == 'mediatvseasonname':
  82. return_file = xbmcpath(downinfopath,'TVSeasonName.txt')
  83. elif filename == 'videoname':
  84. return_file = xbmcpath(metapath,'VideoName.txt')
  85. elif filename == 'sourcename':
  86. return_file = xbmcpath(metapath,'SourceName.txt')
  87. elif filename == 'description':
  88. return_file = xbmcpath(metapath,'Description.txt')
  89. elif filename == 'poster':
  90. return_file = xbmcpath(metapath,'Poster.txt')
  91. elif filename == 'mpaa':
  92. return_file = xbmcpath(metapath,'mpaa.txt')
  93. elif filename == 'listpic':
  94. return_file = xbmcpath(metapath,'listpic.txt')
  95. elif filename == 'smallicon':
  96. return_file = xbmcpath(art,'smalltransparent2.png')
  97. elif filename == 'homepage':
  98. return_file = xbmcpath(art,'homepage.png')
  99. elif filename == 'movies':
  100. return_file = xbmcpath(art,'movies.png')
  101. elif filename == 'music':
  102. return_file = xbmcpath(art,'music.png')
  103. elif filename == 'tvshows':
  104. return_file = xbmcpath(art,'tvshows.png')
  105. elif filename == 'movies_fav':
  106. return_file = xbmcpath(art,'movies_fav.png')
  107. elif filename == 'tvshows_fav':
  108. return_file = xbmcpath(art,'tvshows_fav.png')
  109. elif filename == 'other':
  110. return_file = xbmcpath(art,'other.png')
  111. elif filename == 'search':
  112. return_file = xbmcpath(art,'search.png')
  113. elif filename == 'standup':
  114. return_file = xbmcpath(art,'standup.png')
  115. elif filename == 'megapic':
  116. return_file = xbmcpath(art,'megaupload.png')
  117. elif filename == 'shared2pic':
  118. return_file = xbmcpath(art,'2shared.png')
  119. if getmode == '':
  120. return return_file
  121. if getmode == 'open':
  122. try:
  123. opened_return_file=openfile(return_file)
  124. return opened_return_file
  125. except:
  126. print 'opening failed'
  127. #useful global strings:
  128. iceurl = ICEFILMS_URL
  129. def openfile(filename):
  130. fh = open(filename, 'r')
  131. contents=fh.read()
  132. fh.close()
  133. return contents
  134. def save(filename,contents):
  135. fh = open(filename, 'w')
  136. fh.write(contents)
  137. fh.close()
  138. def appendfile(filename,contents):
  139. fh = open(filename, 'a')
  140. fh.write(contents)
  141. fh.close()
  142. def DLDirStartup(selfAddon):
  143. # Startup routines for handling and creating special download directory structure
  144. SpecialDirs=selfAddon.getSetting('use-special-structure')
  145. if SpecialDirs == 'true':
  146. mypath=str(selfAddon.getSetting('download-folder'))
  147. if mypath != '' or mypath is not None:
  148. if os.path.exists(mypath):
  149. initial_path=os.path.join(mypath,'Icefilms Downloaded Videos')
  150. tvpath=os.path.join(initial_path,'TV Shows')
  151. moviepath=os.path.join(initial_path,'Movies')
  152. tv_path_exists=os.path.exists(tvpath)
  153. movie_path_exists=os.path.exists(moviepath)
  154. if tv_path_exists == False or movie_path_exists == False:
  155. #IF BASE DIRECTORY STRUCTURE DOESN'T EXIST, CREATE IT
  156. #Also Add README files to TV Show and Movies direcories.
  157. #(readme files stops folders being deleted when running the DirCleaner)
  158. if tv_path_exists == False:
  159. os.makedirs(tvpath)
  160. tvreadme='Add this folder to your XBMC Library, and set it as TV to scan for metadata with TVDB.'
  161. tvreadmepath=os.path.join(tvpath,'README.txt')
  162. save(tvreadmepath,tvreadme)
  163. if movie_path_exists == False:
  164. os.makedirs(moviepath)
  165. moviereadme='Add this folder to your XBMC Library, and set it as Movies to scan for metadata with TheMovieDB.'
  166. moviereadmepath=os.path.join(moviepath,'README.txt')
  167. save(moviereadmepath,moviereadme)
  168. else:
  169. #IF DIRECTORIES EXIST, CLEAN DIRECTORY STRUCTURE (REMOVE EMPTY DIRECTORIES)
  170. cl=clean_dirs.DirCleaner()
  171. cl.DelEmptyFolders(tvpath)
  172. cl.DelEmptyFolders(moviepath)
  173. def LoginStartup(selfAddon):
  174. #Get whether user has set an account to use.
  175. Account = selfAddon.getSetting('megaupload-account')
  176. mu=megaroutines.megaupload(translatedicedatapath)
  177. #delete old logins
  178. mu.delete_login()
  179. if Account == 'false':
  180. print 'Account: '+'no account set'
  181. elif Account == 'true':
  182. #check for megaupload login and do it
  183. megauser = selfAddon.getSetting('megaupload-username')
  184. megapass = selfAddon.getSetting('megaupload-password')
  185. login=mu.set_login(megauser,megapass)
  186. if megapass != '' and megauser != '':
  187. if login is False:
  188. print 'Account: '+'login failed'
  189. Notify('big','Megaupload','Login failed. Megaupload will load with no account.','')
  190. elif login is True:
  191. print 'Account: '+'login succeeded'
  192. HideSuccessfulLogin = selfAddon.getSetting('hide-successful-login-messages')
  193. if HideSuccessfulLogin == 'false':
  194. Notify('small','Megaupload', 'Account login successful.','')
  195. if megapass == '' or megauser == '':
  196. print 'no login details specified, using no account'
  197. Notify('big','Megaupload','Login failed. Megaupload will load with no account.','')
  198. def ContainerStartup(selfAddon):
  199. #delete zips from the 'downloaded meta zips' dir that have equivalent text files.
  200. #have to do this at startup because it is not possible to delete the original file
  201. #after extracting, because the file is extracted by a built in xbmc function not python
  202. # (python won't wait until file has finished extracting before going on to run next lines)
  203. #define dl directory
  204. dlzips=os.path.join(translatedicedatapath,'downloaded meta zips')
  205. try:
  206. thefiles=os.listdir(dlzips)
  207. for thefile in thefiles:
  208. filestring=str(thefile)
  209. if filestring.endswith('.txt'):
  210. filestring=re.sub('.txt','.zip',filestring)
  211. os.remove(os.path.join(dlzips,filestring))
  212. except:
  213. print 'could not delete original file!'
  214. else:
  215. print 'deleted unnecessary zip.'
  216. metapath=os.path.join(translatedicedatapath,'meta_caches')
  217. #delete the meta folder if there are no covers. (cleanup failed installs)
  218. if os.path.exists(metapath):
  219. if not os.path.exists(os.path.join(metapath,'themoviedb','covers','tt0011130')):
  220. import shutil
  221. try:
  222. shutil.rmtree(metapath)
  223. except:
  224. print 'Failed to delete meta folder'
  225. return False
  226. #Quick hack for v1.0.0 --- only run if meta_caches does not exist
  227. if not os.path.exists(metapath):
  228. #Movie Meta Container Strings
  229. mv_date='9/Feb/2011'
  230. mv_db='http://www.megaupload.com/?d=U1RTPGQS'
  231. mv_base='http://www.megaupload.com/?d=CE07S1EJ'
  232. mv_db_base_size=230
  233. mv_additional=''
  234. mv_additional_size=0
  235. #TV Meta Container Strings
  236. tv_date=''
  237. tv_db=''
  238. tv_base=''
  239. tv_db_base_size=0
  240. tv_additional=''
  241. tv_additional_size=0
  242. #Offer to download the metadata
  243. dialog = xbmcgui.Dialog()
  244. ret = dialog.yesno('Download Meta Containers '+mv_date+' ?', 'There is a metadata container avaliable.','Install it to get images and info for movies.', 'Would you like to get it? Its a large '+str(mv_db_base_size)+'MB download.','Remind me later', 'Install')
  245. if ret==True:
  246. #download dem files
  247. get_db_zip=Zip_DL_and_Install(mv_db,'themoviedb','database')
  248. get_cover_zip=Zip_DL_and_Install(mv_base,'themoviedb','covers')
  249. #do nice notification
  250. if get_db_zip==True and get_cover_zip==True:
  251. Notify('small','Metacontainer Installation Success','','')
  252. elif get_db_zip==False or get_cover_zip==False:
  253. Notify('small','Metacontainer Installation Failure','','')
  254. def Zip_DL_and_Install(url,dbtype,installtype):
  255. #define dl directory
  256. dlzips=os.path.join(translatedicedatapath,'downloaded meta zips')
  257. #get the download url
  258. mu=megaroutines.megaupload(translatedicedatapath)
  259. print 'URL:',url
  260. thefile=mu.resolve_megaup(url)
  261. #define the path to save it to
  262. filepath=os.path.normpath(os.path.join(dlzips,thefile[1]))
  263. print 'FILEPATH: ',filepath
  264. filepath_exists=os.path.exists(filepath)
  265. #if zip does not already exist, download from url, with nice display name.
  266. if filepath_exists==False:
  267. do_wait(thefile[3])
  268. print 'downloading zip'
  269. Download(thefile[0],filepath,dbtype+' '+installtype)
  270. #make a text file with the same name as zip, to act as a very simple download log.
  271. textfile=re.sub('.zip','',thefile[1])
  272. textfilepath=os.path.join(dlzips,textfile+'.txt')
  273. save(textfilepath,' ')
  274. elif filepath_exists==True:
  275. print 'zip already downloaded, attempting extraction'
  276. print '!!!!handling meta install!!!!'
  277. mc=metahandlers.MetaContainer()
  278. install=mc.Install_Icefilms_Container(translatedicedatapath,filepath,dbtype,installtype)
  279. return install
  280. def Startup_Routines(selfAddon):
  281. # avoid error on first run if no paths exists, by creating paths
  282. if not os.path.exists(translatedicedatapath):
  283. os.makedirs(translatedicedatapath)
  284. if not os.path.exists(transmetapath):
  285. os.makedirs(transmetapath)
  286. if not os.path.exists(transdowninfopath):
  287. os.makedirs(transdowninfopath)
  288. dlzips=os.path.join(translatedicedatapath,'downloaded meta zips')
  289. if not os.path.exists(dlzips):
  290. os.makedirs(dlzips)
  291. #force refresh addon repositories, to check for updates.
  292. #xbmc.executebuiltin('UpdateAddonRepos')
  293. # Run the startup routines for special download directory structure
  294. DLDirStartup(selfAddon)
  295. # Run the login startup routines
  296. LoginStartup(selfAddon)
  297. # Run the container checking startup routines, if enable meta is set to true
  298. EnableMeta = selfAddon.getSetting('use-meta')
  299. if EnableMeta=='true':
  300. ContainerStartup(selfAddon)
  301. def CATEGORIES(): # (homescreen of addon)
  302. #get settings
  303. selfAddon = xbmcaddon.Addon(id='plugin.video.icefilms')
  304. #run startup stuff
  305. Startup_Routines(selfAddon)
  306. print 'Homescreen'
  307. #get necessary paths
  308. homepage=handle_file('homepage','')
  309. tvshows=handle_file('tvshows','')
  310. movies=handle_file('movies','')
  311. music=handle_file('music','')
  312. standup=handle_file('standup','')
  313. other=handle_file('other','')
  314. search=handle_file('search','')
  315. #add directories
  316. HideHomepage = selfAddon.getSetting('hide-homepage')
  317. addDir('TV Shows',iceurl+'tv/a-z/1',50,tvshows)
  318. addDir('Movies',iceurl+'movies/a-z/1',51,movies)
  319. addDir('Music',iceurl+'music/a-z/1',52,music)
  320. addDir('Stand Up Comedy',iceurl+'standup/a-z/1',53,standup)
  321. addDir('Other',iceurl+'other/a-z/1',54,other)
  322. if HideHomepage == 'false':
  323. addDir('Homepage',iceurl+'index',56,homepage)
  324. addDir('Favourites',iceurl,57,os.path.join(art,'favourites.png'))
  325. addDir('Search',iceurl,55,search)
  326. def prepare_list(directory,dircontents):
  327. #create new empty list
  328. stringList = []
  329. #Open all files in dir
  330. for thefile in dircontents:
  331. try:
  332. filecontents=openfile(os.path.join(directory,thefile))
  333. #add this to list
  334. stringList.append(filecontents)
  335. except:
  336. print 'problem with opening a favourites item'
  337. #sort list alphabetically and return it.
  338. tupleList = [(x.lower(), x) for x in stringList]
  339. tupleList.sort()
  340. return [x[1] for x in tupleList]
  341. def favRead(string):
  342. try:
  343. splitter=re.split('\|+', string)
  344. name=splitter[0]
  345. url=splitter[1]
  346. mode=int(splitter[2])
  347. try:
  348. imdb_id=str(splitter[3])
  349. except:
  350. imdb_id=''
  351. except:
  352. return None
  353. else:
  354. return name,url,mode,imdb_id
  355. def addFavourites(enablemetadata,directory,dircontents):
  356. #get the strings of data from the files, and return them alphabetically
  357. stringlist=prepare_list(directory,dircontents)
  358. if enablemetadata == True:
  359. metaget=metahandlers.MovieMetaData(translatedicedatapath)
  360. #for each string
  361. for thestring in stringlist:
  362. #split it into its component parts
  363. info = favRead(thestring)
  364. if info is not None:
  365. if enablemetadata == True:
  366. #return the metadata dictionary
  367. if info[3] is not None:
  368. meta=metaget.get_movie_meta(info[3])
  369. if meta is None:
  370. #add all the items without meta
  371. addDir(info[0],info[1],info[2],'',delfromfav=True)
  372. else:
  373. #add directories with meta
  374. addDir(info[0],info[1],info[2],'',metainfo=meta,delfromfav=True,imdb=info[3])
  375. else:
  376. #add all the items without meta
  377. addDir(info[0],info[1],info[2],'',delfromfav=True)
  378. else:
  379. #add all the items without meta
  380. addDir(info[0],info[1],info[2],'',delfromfav=True)
  381. def setView(content, viewType):
  382. #get settings
  383. selfAddon = xbmcaddon.Addon(id='plugin.video.icefilms')
  384. # kept for reference only
  385. #movies_view = selfAddon.getSetting('movies-view')
  386. #tvshows_view = selfAddon.getSetting('tvshows-view')
  387. #episodes_view = selfAddon.getSetting('episodes-view')
  388. # set content type so library shows more views and info
  389. xbmcplugin.setContent(int(sys.argv[1]), content)
  390. if selfAddon.getSetting('auto-view') == 'true':
  391. xbmc.executebuiltin("Container.SetViewMode(%s)" % selfAddon.getSetting(viewType) )
  392. # set sort methods - probably we don't need all of them
  393. xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_UNSORTED )
  394. xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_LABEL )
  395. xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RATING )
  396. xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_DATE )
  397. xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_PROGRAM_COUNT )
  398. xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_VIDEO_RUNTIME )
  399. xbmcplugin.addSortMethod( handle=int( sys.argv[ 1 ] ), sortMethod=xbmcplugin.SORT_METHOD_GENRE )
  400. def FAVOURITES(url):
  401. #Favourites folder.
  402. #get necessary paths
  403. tvshows=handle_file('tvshows_fav','')
  404. movies=handle_file('movies_fav','')
  405. addDir('TV Shows',iceurl,570,tvshows)
  406. addDir('Movies',iceurl,571,movies)
  407. #Movie Favourites folder.
  408. def MOVIE_FAVOURITES(url):
  409. #get settings
  410. selfAddon = xbmcaddon.Addon(id='plugin.video.icefilms')
  411. favpath=os.path.join(translatedicedatapath,'Favourites')
  412. moviefav=os.path.join(favpath,'Movies')
  413. try:
  414. moviedircontents=os.listdir(moviefav)
  415. except:
  416. moviedircontents=None
  417. if moviedircontents == None:
  418. Notify('big','No Movie Favourites Saved','To save a favourite press the C key on a movie or\n TV Show and select Add To Icefilms Favourites','')
  419. else:
  420. #add clear favourites entry - Not sure if we must put it here, cause it will mess up the sorting
  421. #addExecute('* Clear Favourites Folder *',url,58,os.path.join(art,'deletefavs.png'))
  422. #handler for all movie favourites
  423. if moviedircontents is not None:
  424. #get the necessary meta stuff
  425. use_meta=os.path.exists(os.path.join(translatedicedatapath,'meta_caches'))
  426. meta_setting = selfAddon.getSetting('use-meta')
  427. #add without metadata -- imdb is still passed for use with Add to Favourites
  428. if use_meta==False or meta_setting=='false':
  429. addFavourites(False,moviefav,moviedircontents)
  430. #add with metadata -- imdb is still passed for use with Add to Favourites
  431. elif use_meta==True and meta_setting=='true':
  432. addFavourites(True,moviefav,moviedircontents)
  433. else:
  434. print 'moviedircontents is none!'
  435. # Enable library mode & set the right view for the content
  436. setView('movies', 'movies-view')
  437. #TV Shows Favourites folder
  438. def TV_FAVOURITES(url):
  439. #get settings
  440. selfAddon = xbmcaddon.Addon(id='plugin.video.icefilms')
  441. favpath=os.path.join(translatedicedatapath,'Favourites')
  442. tvfav=os.path.join(favpath,'TV')
  443. try:
  444. tvdircontents=os.listdir(tvfav)
  445. except:
  446. tvdircontents=None
  447. if tvdircontents == None:
  448. Notify('big','No TV Favourites Saved','To save a favourite press the C key on a movie or\n TV Show and select Add To Icefilms Favourites','')
  449. else:
  450. #add clear favourites entry - Not sure if we must put it here, cause it will mess up the sorting
  451. #addExecute('* Clear Favourites Folder *',url,58,os.path.join(art,'deletefavs.png'))
  452. #handler for all tv favourites
  453. if tvdircontents is not None:
  454. #get the necessary meta stuff
  455. use_meta=os.path.exists(os.path.join(translatedicedatapath,'meta_caches'))
  456. meta_setting = selfAddon.getSetting('use-meta')
  457. #add without metadata -- imdb is still passed for use with Add to Favourites
  458. if use_meta==False or meta_setting=='false':
  459. addFavourites(False,tvfav,tvdircontents)
  460. #add with metadata -- imdb is still passed for use with Add to Favourites
  461. elif use_meta==True and meta_setting=='true':
  462. addFavourites(True,tvfav,tvdircontents)
  463. else:
  464. print 'tvshows dircontents is none!'
  465. # Enable library mode & set the right view for the content
  466. setView('movies', 'tvshows-view')
  467. def URL_TYPE(url):
  468. #Check whether url is a tv episode list or movie/mirrorpage
  469. if url.startswith(iceurl+'ip'):
  470. print 'url is a mirror page url'
  471. return 'mirrors'
  472. elif url.startswith(iceurl+'tv/series'):
  473. print 'url is a tv ep list url'
  474. return 'episodes'
  475. def METAFIXER(url):
  476. #Icefilms urls passed to me will have their proper names and imdb numbers returned.
  477. source=GetURL(url)
  478. url_type=URL_TYPE(url)
  479. #get proper name from the page. (in case it is a weird name)
  480. if url_type=='mirrors':
  481. #get imdb number.
  482. match=re.compile('<a class=iframe href=http://www.imdb.com/title/(.+?)/ ').findall(source)
  483. #check if it is an episode.
  484. epcheck=re.search('<a href=/tv/series/',source)
  485. #if it is, return the proper series name as opposed to the mirror page name.
  486. if epcheck is not None:
  487. tvget=re.compile('<a href=/tv/series/(.+?)>').findall(source)
  488. tvurl=iceurl+'tv/series/'+str(tvget[0])
  489. #load ep page and get name from that. sorry icefilms bandwidth!
  490. tvsource=GetURL(tvurl)
  491. name=re.compile('<h1>(.+?)<a class').findall(tvsource)
  492. #return mirror page name.
  493. if epcheck is None:
  494. name=re.compile('''<span style="font-size:large;color:white;">(.+?)</span>''').findall(source)
  495. name=CLEANUP(name[0])
  496. return name,match[0]
  497. elif url_type=='episodes':
  498. #TV
  499. name=re.compile('<h1>(.+?)<a class').findall(source)
  500. match=re.compile('href="http://www.imdb.com/title/(.+?)/"').findall(source)
  501. name=CLEANUP(name[0])
  502. return name,match[0]
  503. def ADD_TO_FAVOURITES(name,url,imdbnum):
  504. #Creates a new text file in favourites folder. The text file is named after the items name, and contains the name, url and relevant mode.
  505. print 'Adding to favourites: name: %s, imdbnum: %s, url: %s' % (name, imdbnum, url)
  506. if name is not None and url is not None:
  507. #Set favourites path, and create it if it does'nt exist.
  508. favpath=os.path.join(translatedicedatapath,'Favourites')
  509. tvfav=os.path.join(favpath,'TV')
  510. moviefav=os.path.join(favpath,'Movies')
  511. try:
  512. os.makedirs(tvfav)
  513. except:
  514. pass
  515. try:
  516. os.makedirs(moviefav)
  517. except:
  518. pass
  519. #Check what kind of url it is and set themode and savepath (helpful for metadata) accordingly
  520. #fix name and imdb number for Episode List entries in Search.
  521. if imdbnum == 'nothing':
  522. metafix=METAFIXER(url)
  523. name=metafix[0]
  524. imdbnum=metafix[1]
  525. url_type=URL_TYPE(url)
  526. if url_type=='mirrors':
  527. themode='100'
  528. savepath=moviefav
  529. elif url_type=='episodes':
  530. themode='12'
  531. savepath=tvfav
  532. print 'NAME:',name,'URL:',url,'IMDB NUMBER:',imdbnum
  533. #encode the filename to the safe string
  534. adjustedname=base64.urlsafe_b64encode(name)
  535. #Save the new favourite if it does not exist.
  536. NewFavFile=os.path.join(savepath,adjustedname+'.txt')
  537. if not os.path.exists(NewFavFile):
  538. #Use | as separators that can be used by re.split when reading favourites folder.
  539. favcontents=name+'|'+url+'|'+themode+'|'+imdbnum
  540. save(NewFavFile,favcontents)
  541. else:
  542. print 'favourite already exists'
  543. else:
  544. print 'name or url is none:'
  545. print 'NAME: ',name
  546. print 'URL: ',url
  547. def DELETE_FROM_FAVOURITES(name,url):
  548. #encode the filename to the safe string
  549. name=base64.urlsafe_b64encode(name)
  550. favpath=os.path.join(translatedicedatapath,'Favourites')
  551. url_type=URL_TYPE(url)
  552. if url_type=='mirrors':
  553. itempath=os.path.join(favpath,'Movies',name+'.txt')
  554. elif url_type=='episodes':
  555. itempath=os.path.join(favpath,'TV',name+'.txt')
  556. if os.path.exists(itempath):
  557. os.remove(itempath)
  558. def CLEAR_FAVOURITES(url):
  559. dialog = xbmcgui.Dialog()
  560. ret = dialog.yesno('WARNING!', 'Delete all your favourites?','','','Cancel','Go Nuclear')
  561. if ret==True:
  562. import shutil
  563. favpath=os.path.join(translatedicedatapath,'Favourites')
  564. tvfav=os.path.join(favpath,'TV')
  565. moviefav=os.path.join(favpath,'Movies')
  566. try:
  567. shutil.rmtree(tvfav)
  568. except:
  569. pass
  570. try:
  571. shutil.rmtree(moviefav)
  572. except:
  573. pass
  574. def ICEHOMEPAGE(url):
  575. addDir('Recently Added',iceurl+'index',60,os.path.join(art,'recently added.png'))
  576. addDir('Latest Releases',iceurl+'index',61,os.path.join(art,'latest releases.png'))
  577. addDir('Being Watched Now',iceurl+'index',62,os.path.join(art,'being watched now.png'))
  578. #delete tv show name file
  579. tvshowname=handle_file('mediatvshowname','')
  580. try:
  581. os.remove(tvshowname)
  582. except:
  583. pass
  584. def RECENT(url):
  585. link=GetURL(url)
  586. homepage=re.compile('<h1>Recently Added</h1>(.+?)<h1>Statistics</h1>').findall(link)
  587. for scrape in homepage:
  588. scrape='<h1>Recently Added</h1>'+scrape+'<h1>Statistics</h1>'
  589. recadd=re.compile('<h1>Recently Added</h1>(.+?)<h1>Latest Releases</h1>').findall(scrape)
  590. for scraped in recadd:
  591. mirlinks=re.compile('<a href=(.+?)>(.+?)</a>').findall(scraped)
  592. for url,name in mirlinks:
  593. url=iceurl+url
  594. name=CLEANUP(name)
  595. addDir(name,url,100,'',disablefav=True)
  596. def LATEST(url):
  597. link=GetURL(url)
  598. homepage=re.compile('<h1>Recently Added</h1>(.+?)<h1>Statistics</h1>').findall(link)
  599. for scrape in homepage:
  600. scrape='<h1>Recently Added</h1>'+scrape+'<h1>Statistics</h1>'
  601. latrel=re.compile('<h1>Latest Releases</h1>(.+?)<h1>Being Watched Now</h1>').findall(scrape)
  602. for scraped in latrel:
  603. mirlinks=re.compile('<a href=(.+?)>(.+?)</a>').findall(scraped)
  604. for url,name in mirlinks:
  605. url=iceurl+url
  606. name=CLEANUP(name)
  607. addDir(name,url,100,'',disablefav=True)
  608. def WATCHINGNOW(url):
  609. link=GetURL(url)
  610. homepage=re.compile('<h1>Recently Added</h1>(.+?)<h1>Statistics</h1>').findall(link)
  611. for scrape in homepage:
  612. scrapy='<h1>Recently Added</h1>'+scrape+'<h1>Statistics</h1>'
  613. watnow=re.compile('<h1>Being Watched Now</h1>(.+?)<h1>Statistics</h1>').findall(scrapy)
  614. for scraped in watnow:
  615. mirlinks=re.compile('href=(.+?)>(.+?)</a>').findall(scraped)
  616. for url,name in mirlinks:
  617. url=iceurl+url
  618. name=CLEANUP(name)
  619. addDir(name,url,100,'',disablefav=True)
  620. def SEARCH(url):
  621. kb = xbmc.Keyboard('', 'Search Icefilms.info', False)
  622. kb.doModal()
  623. if (kb.isConfirmed()):
  624. search = kb.getText()
  625. if search != '':
  626. tvshowname=handle_file('mediatvshowname','')
  627. seasonname=handle_file('mediatvseasonname','')
  628. DoEpListSearch(search)
  629. DoSearch(search,0)
  630. DoSearch(search,1)
  631. DoSearch(search,2)
  632. #delete tv show name file, do the same for season name file
  633. try:
  634. os.remove(tvshowname)
  635. except:
  636. pass
  637. try:
  638. os.remove(seasonname)
  639. except:
  640. pass
  641. def DoSearch(search,page):
  642. gs = GoogleSearch('site:http://www.icefilms.info/ip '+search+'')
  643. gs.results_per_page = 25
  644. gs.page = page
  645. results = gs.get_results()
  646. for res in results:
  647. name=res.title.encode('utf8')
  648. name=CLEANSEARCH(name)
  649. url=res.url.encode('utf8')
  650. addDir(name,url,100,'')
  651. def DoEpListSearch(search):
  652. tvurl='http://www.icefilms.info/tv/series'
  653. # use urllib.quote_plus() on search instead of re.sub ?
  654. searcher=urllib.quote_plus(search)
  655. #searcher=re.sub(' ','+',search)
  656. url='http://www.google.com/search?hl=en&q=site:'+tvurl+'+'+searcher+'&btnG=Search&aq=f&aqi=&aql=&oq='
  657. link=GetURL(url)
  658. match=re.compile('<h3 class="r"><a href="'+tvurl+'(.+?)"(.+?)">(.+?)</h3>').findall(link)
  659. for myurl,interim,name in match:
  660. if len(interim) < 80:
  661. name=CLEANSEARCH(name)
  662. hasnameintitle=re.search(search,name,re.IGNORECASE)
  663. if hasnameintitle is not None:
  664. myurl=tvurl+myurl
  665. myurl=re.sub('&amp;','',myurl)
  666. addDir(name,myurl,12,'')
  667. def CLEANSEARCH(name):
  668. name=re.sub('<em>','',name)
  669. name=re.sub('</em>','',name)
  670. name=re.sub('DivX - icefilms.info','',name)
  671. name=re.sub('</a>','',name)
  672. name=re.sub('<b>...</b>','',name)
  673. name=re.sub('- icefilms.info','',name)
  674. name=re.sub('.info','',name)
  675. name=re.sub('- icefilms','',name)
  676. name=re.sub(' -icefilms','',name)
  677. name=re.sub('-icefilms','',name)
  678. name=re.sub('icefilms','',name)
  679. name=re.sub('DivX','',name)
  680. name=re.sub('- Episode List','- Episode List',name)
  681. name=re.sub('-Episode List','- Episode List',name)
  682. #name=re.sub('&#39;',"'",name)
  683. #name=re.sub('&amp;','&',name)
  684. return name
  685. def CLEANUP(name):
  686. # clean names of annoying garbled text
  687. name=re.sub('</a>','',name)
  688. name=re.sub('<b>HD</b>',' *HD*',name)
  689. #name=re.sub('&#xF4;','o',name)
  690. #name=re.sub('&#xE9;',"e",name)
  691. #name=re.sub('&#xEB;',"e",name)
  692. #name=re.sub('&#xC6;','AE',name)
  693. #name=re.sub('&#x27;',"'",name)
  694. #name=re.sub('&#xED;','i',name)
  695. #name=re.sub('&frac12;',' 1/2',name)
  696. #name=re.sub('&#xBD;',' 1/2',name)
  697. #name=re.sub('&#x26;','&',name)
  698. #name=re.sub('&#x22;','',name)
  699. return name
  700. def TVCATEGORIES(url):
  701. caturl = iceurl+'tv/'
  702. setmode = '11'
  703. addDir('A-Z Directories',caturl+'a-z/1',10,os.path.join(art,'az directories.png'))
  704. ADDITIONALCATS(setmode,caturl)
  705. def MOVIECATEGORIES(url):
  706. caturl = iceurl+'movies/'
  707. setmode = '2'
  708. addDir('A-Z Directories',caturl+'a-z/1',1,os.path.join(art,'az directories.png'))
  709. ADDITIONALCATS(setmode,caturl)
  710. def MUSICCATEGORIES(url):
  711. caturl = iceurl+'music/'
  712. setmode = '2'
  713. addDir('A-Z List',caturl+'a-z/1',setmode,os.path.join(art,'az lists.png'))
  714. ADDITIONALCATS(setmode,caturl)
  715. def STANDUPCATEGORIES(url):
  716. caturl = iceurl+'standup/'
  717. setmode = '2'
  718. addDir('A-Z List',caturl+'a-z/1',setmode,os.path.join(art,'az lists.png'))
  719. ADDITIONALCATS(setmode,caturl)
  720. def OTHERCATEGORIES(url):
  721. caturl = iceurl+'other/'
  722. setmode = '2'
  723. addDir('A-Z List',caturl+'a-z/1',setmode,os.path.join(art,'az lists.png'))
  724. ADDITIONALCATS(setmode,caturl)
  725. def ADDITIONALCATS(setmode,caturl):
  726. if caturl == iceurl+'movies/':
  727. addDir('HD 720p',caturl,63,os.path.join(art,'HD 720p.png'))
  728. PopRatLat(setmode,caturl,'1')
  729. addDir('Genres',caturl,64,os.path.join(art,'genres.png'))
  730. def PopRatLat(modeset,caturl,genre):
  731. if caturl == iceurl+'tv/':
  732. setmode = '11'
  733. elif caturl is not iceurl+'tv/':
  734. setmode = '2'
  735. addDir('Popular',caturl+'popular/'+genre,setmode,os.path.join(art,'popular.png'))
  736. addDir('Highly Rated',caturl+'rating/'+genre,setmode,os.path.join(art,'highly rated.png'))
  737. addDir('Latest Releases',caturl+'release/'+genre,setmode,os.path.join(art,'latest releases.png'))
  738. addDir('Recently Added',caturl+'added/'+genre,setmode,os.path.join(art,'recently added.png'))
  739. def HD720pCat(url):
  740. PopRatLat('2',url,'hd')
  741. def Genres(url):
  742. addDir('Action',url,70,'')
  743. addDir('Animation',url,71,'')
  744. addDir('Comedy',url,72,'')
  745. addDir('Documentary',url,73,'')
  746. addDir('Drama',url,74,'')
  747. addDir('Family',url,75,'')
  748. addDir('Horror',url,76,'')
  749. addDir('Romance',url,77,'')
  750. addDir('Sci-Fi',url,78,'')
  751. addDir('Thriller',url,79,'')
  752. def Action(url):
  753. PopRatLat('2',url,'action')
  754. def Animation(url):
  755. PopRatLat('2',url,'animation')
  756. def Comedy(url):
  757. PopRatLat('2',url,'comedy')
  758. def Documentary(url):
  759. PopRatLat('2',url,'documentary')
  760. def Drama(url):
  761. PopRatLat('2',url,'drama')
  762. def Family(url):
  763. PopRatLat('2',url,'family')
  764. def Horror(url):
  765. PopRatLat('2',url,'horror')
  766. def Romance(url):
  767. PopRatLat('2',url,'romance')
  768. def SciFi(url):
  769. PopRatLat('2',url,'sci-fi')
  770. def Thriller(url):
  771. PopRatLat('2',url,'thriller')
  772. def MOVIEA2ZDirectories(url):
  773. setmode = '2'
  774. caturl = iceurl+'movies/a-z/'
  775. #Add number directory
  776. addDir ('#1234',caturl+'1',setmode,os.path.join(art,'letters','1.png'))
  777. #Generate A-Z list and add directories for all letters.
  778. A2Z=[chr(i) for i in xrange(ord('A'), ord('Z')+1)]
  779. for theletter in A2Z:
  780. addDir (theletter,caturl+theletter,setmode,os.path.join(art,'letters',theletter+'.png'))
  781. def TVA2ZDirectories(url):
  782. setmode = '11'
  783. caturl = iceurl+'tv/a-z/'
  784. #Add number directory
  785. addDir ('#1234',caturl+'1',setmode,os.path.join(art,'letters','1.png'))
  786. #Generate A-Z list and add directories for all letters.
  787. A2Z=[chr(i) for i in xrange(ord('A'), ord('Z')+1)]
  788. for theletter in A2Z:
  789. addDir (theletter,caturl+theletter,setmode,os.path.join(art,'letters',theletter+'.png'))
  790. def MOVIEINDEX(url):
  791. #Indexer for most things. (Not just movies.)
  792. #get settings
  793. selfAddon = xbmcaddon.Addon(id='plugin.video.icefilms')
  794. # set content type so library shows more views and info
  795. xbmcplugin.setContent(int(sys.argv[1]), 'movies')
  796. meta_path=os.path.join(translatedicedatapath,'meta_caches')
  797. use_meta=os.path.exists(meta_path)
  798. meta_setting = selfAddon.getSetting('use-meta')
  799. link=GetURL(url)
  800. scrape=re.compile('<a name=i id=(.+?)></a><img class=star><a href=/(.+?)>(.+?)<br>').findall(link)
  801. #add without metadata -- imdb is still passed for use with Add to Favourites
  802. if use_meta==False or meta_setting=='false':
  803. for imdb_id,url,name in scrape:
  804. name=CLEANUP(name)
  805. addDir(name,iceurl+url,100,'',imdb='tt'+str(imdb_id))
  806. #add with metadata
  807. elif use_meta==True and meta_setting=='true':
  808. #initialise meta class before loop
  809. metaget=metahandlers.MovieMetaData(translatedicedatapath)
  810. for imdb_id,url,name in scrape:
  811. #clean name of unwanted stuff
  812. name=CLEANUP(name)
  813. url=iceurl+url
  814. #return the metadata dictionary
  815. meta=metaget.get_movie_meta(imdb_id)
  816. #debugs
  817. #print 'meta_name:'+str(name)
  818. #print 'meta_imdb_id:'+str(imdb_id)
  819. #print 'meta_video_url:'+str(url)
  820. #print 'meta_data:'+str(meta)
  821. #print 'meta_imdb_id:',meta['imdb_id']
  822. if meta is None:
  823. #add directories without meta
  824. addDir(name,url,100,'')
  825. else:
  826. #add directories with meta
  827. addDir(name,url,100,'',metainfo=meta,imdb='tt'+str(imdb_id))
  828. def TVINDEX(url):
  829. #Indexer for TV Shows only.
  830. link=GetURL(url)
  831. match=re.compile('<a name=i id=(.+?)></a><img class=star><a href=/(.+?)>(.+?)</a>').findall(link)
  832. for imdb_id,url,name in match:
  833. name=CLEANUP(name)
  834. addDir(name,iceurl+url,12,'')
  835. def TVSEASONS(url):
  836. # displays by seasons. pays attention to settings.
  837. #get settings
  838. selfAddon = xbmcaddon.Addon(id='plugin.video.icefilms')
  839. FlattenSingleSeasons = selfAddon.getSetting('flatten-single-season')
  840. source=GetURL(url)
  841. #Save the tv show name for use in special download directories.
  842. tvshowname=handle_file('mediatvshowname','')
  843. match=re.compile('<h1>(.+?)<a class').findall(source)
  844. save(tvshowname,match[0])
  845. ep_list = str(BeautifulSoup(source).find("span", { "class" : "list" } ))
  846. season_list=re.compile('<h4>(.+?)</h4>').findall(ep_list)
  847. listlength=len(season_list)
  848. for seasons in season_list:
  849. if FlattenSingleSeasons==True and listlength <= 1:
  850. #proceed straight to adding episodes.
  851. TVEPISODES(seasons,source=ep_list)
  852. else:
  853. #save episode page source code
  854. save(handle_file('episodesrc'),ep_list)
  855. #add season directories
  856. addDir(seasons,'',13,'')
  857. def TVEPISODES(name,url=None,source=None):
  858. #Save the season name for use in the special download directories.
  859. save(handle_file('mediatvseasonname'),name)
  860. #If source was'nt passed to function, open the file it should be saved to.
  861. if source is None:
  862. source = openfile(handle_file('episodesrc'))
  863. #special hack to deal with annoying re problems when recieving brackets ( )
  864. if re.search('\(',name) is not None:
  865. name = str((re.split('\(+', name))[0])
  866. #name=str(name[0])
  867. #quick hack of source code to simplfy scraping.
  868. source=re.sub('</span>','<h4>',source)
  869. #get all the source under season heading.
  870. #Use .+?/h4> not .+?</h4> for The Daily Show et al to work.
  871. match=re.compile('<h4>'+name+'.+?/h4>(.+?)<h4>').findall(source)
  872. for seasonSRC in match:
  873. TVEPLINKS(seasonSRC)
  874. def TVEPLINKS(source):
  875. # displays all episodes in the source it is passed.
  876. match=re.compile('<img class="star" /><a href="/(.+?)&amp;">(.+?)</a>').findall(source)
  877. for url,name in match:
  878. name=CLEANUP(name)
  879. addDir(name,iceurl+url,100,'')
  880. def LOADMIRRORS(url):
  881. # This proceeds from the file page to the separate frame where the mirrors can be found,
  882. # then executes code to scrape the mirrors
  883. link=GetURL(url)
  884. #print link
  885. posterfile=handle_file('poster','')
  886. videonamefile=handle_file('videoname','')
  887. descriptionfile=handle_file('description','')
  888. mpaafile=handle_file('mpaa','')
  889. mediapathfile=handle_file('mediapath','')
  890. #---------------Begin phantom metadata getting--------
  891. #Save metadata on page to files, for use when playing.
  892. # Also used for creating the download directory structures.
  893. try:
  894. os.remove(posterurl)
  895. except:
  896. print 'posterurl does not exist'
  897. try:
  898. os.remove(mpaafile)
  899. except:
  900. print 'mpaafile does not exist'
  901. # get and save videoname
  902. namematch=re.compile('''<span style="font-size:large;color:white;">(.+?)</span>''').findall(link)
  903. save(videonamefile,namematch[0])
  904. # get and save description
  905. match2=re.compile('<th>Description:</th><td>(.+?)<').findall(link)
  906. try:
  907. save(descriptionfile,match2[0])
  908. except:
  909. pass
  910. # get and save poster link
  911. try:
  912. imgcheck1 = re.search('<img width=250 src=', link)
  913. imgcheck2 = re.search('/noref.php\?url=', link)
  914. if imgcheck1 is not None:
  915. match4=re.compile('<img width=250 src=(.+?) style').findall(link)
  916. save(posterfile,match4[0])
  917. if imgcheck2 is not None:
  918. match5=re.compile('/noref.php\?url=(.+?)>').findall(link)
  919. save(posterfile,match5[0])
  920. except:
  921. pass
  922. #get and save mpaa
  923. mpaacheck = re.search('MPAA Rating:', link)
  924. if mpaacheck is not None:
  925. match4=re.compile('<th>MPAA Rating:</th><td>(.+?)</td>').findall(link)
  926. mpaa=re.sub('Rated ','',match4[0])
  927. try:
  928. save(mpaafile,mpaa)
  929. except:
  930. pass
  931. ########### get and save potential file path. This is for use in download function later on.
  932. epcheck1 = re.search('Episodes</a>', link)
  933. epcheck2 = re.search('Episode</a>', link)
  934. if epcheck1 is not None or epcheck2 is not None:
  935. shownamepath=handle_file('mediatvshowname','')
  936. if os.path.exists(shownamepath):
  937. #open media file if it exists, as that has show name with date.
  938. showname=openfile(shownamepath)
  939. else:
  940. #fall back to scraping show name without date from the page.
  941. print 'USING FALLBACK SHOW NAME'
  942. fallbackshowname=re.compile("alt\='Show series\: (.+?)'").findall(link)
  943. showname=fallbackshowname[0]
  944. try:
  945. #if season name file exists
  946. seasonnamepath=handle_file('mediatvseasonname','')
  947. if os.path.exists(seasonnamepath):
  948. seasonname=openfile(seasonnamepath)
  949. save(mediapathfile,'TV Shows/'+showname+'/'+seasonname)
  950. else:
  951. save(mediapathfile,'TV Shows/'+showname)
  952. except:
  953. print "FAILED TO SAVE TV SHOW FILE PATH!"
  954. else:
  955. save(mediapathfile,'Movies/'+namematch[0])
  956. #---------------End phantom metadata getting stuff --------------
  957. match=re.compile('/membersonly/components/com_iceplayer/(.+?)" width=').findall(link)
  958. match[0]=re.sub('%29',')',match[0])
  959. match[0]=re.sub('%28','(',match[0])
  960. for url in match:
  961. mirrorpageurl = iceurl+'membersonly/components/com_iceplayer/'+url
  962. mirror_page=GetURL(mirrorpageurl, save_cookie = True)
  963. # check for recaptcha
  964. has_recaptcha = check_for_captcha(mirror_page)
  965. if has_recaptcha is False:
  966. GETMIRRORS(mirrorpageurl,mirror_page)
  967. elif has_recaptcha is True:
  968. RECAPTCHA(mirrorpageurl)
  969. def check_for_captcha(source):
  970. #check for recaptcha in the page source, and return true or false.
  971. has_recaptcha = re.search('recaptcha_challenge_field', source)
  972. if has_recaptcha is None:
  973. return False
  974. elif has_recaptcha is not None:
  975. return True
  976. def RECAPTCHA(url):
  977. print 'initiating recaptcha passthrough'
  978. link=GetURL(url)
  979. match=re.compile('<iframe src="http://www.google.com/recaptcha/api/noscript\?k\=(.+?)" height').findall(link)
  980. for token in match:
  981. surl = 'http://www.google.com/recaptcha/api/challenge?k=' + token
  982. tokenlink=GetURL(surl)
  983. matchy=re.compile("challenge : '(.+?)'").findall(tokenlink)
  984. for challenge in matchy:
  985. imageurl='http://www.google.com/recaptcha/api/image?c='+challenge
  986. captchafile=handle_file('captcha','')
  987. pageurlfile=handle_file('pageurl','')
  988. #hacky method --- save all captcha details and mirrorpageurl to file, to reopen in next step
  989. save(captchafile, challenge)
  990. save(pageurlfile, url)
  991. #addDir uses imageurl as url, to avoid xbmc displaying old cached image as the fresh captcha
  992. addDir('Enter Captcha - Type the letters',imageurl,99,imageurl)
  993. def CATPCHAENTER(surl):
  994. url=handle_file('pageurl','open')
  995. kb = xbmc.Keyboard('', 'Type the letters in the captcha image', False)
  996. kb.doModal()
  997. if (kb.isConfirmed()):
  998. userInput = kb.getText()
  999. if userInput != '':
  1000. challengeToken=handle_file('captcha','open')
  1001. print 'challenge token: '+challengeToken
  1002. parameters = urllib.urlencode({'recaptcha_challenge_field': challengeToken, 'recaptcha_response_field': userInput})
  1003. link=GetURL(url, params = parameters)
  1004. has_recaptcha = check_for_captcha(link)
  1005. if has_recaptcha is False:
  1006. GETMIRRORS(url,link)
  1007. elif has_recaptcha is True:
  1008. Notify('big', 'Text does not match captcha image!', 'To try again, close this box and then: \n Press backspace twice, and reselect your video.', '')
  1009. elif userInput == '':
  1010. Notify('big', 'No text entered!', 'To try again, close this box and then: \n Press backspace twice, and reselect your video.', '')
  1011. def GETMIRRORS(url,link):
  1012. # This scrapes the megaupload mirrors from the separate url used for the video frame.
  1013. # It also displays them in an informative fashion to user.
  1014. # Displays in three directory levels: HD / DVDRip etc , Source, PART
  1015. print "getting mirrors for: %s" % url
  1016. #get settings
  1017. selfAddon = xbmcaddon.Addon(id='plugin.video.icefilms')
  1018. #hacky method -- save page source to file
  1019. mirrorfile=handle_file('mirror','')
  1020. save(mirrorfile, link)
  1021. #check for the existence of categories, and set values.
  1022. if re.search('<div class=ripdiv><b>DVDRip / Standard Def</b>', link) is not None: dvdrip = 1
  1023. else: dvdrip = 0
  1024. if re.search('<div class=ripdiv><b>HD 720p</b>', link) is not None: hd720p = 1
  1025. else: hd720p = 0
  1026. if re.search('<div class=ripdiv><b>DVD Screener</b>', link) is not None: dvdscreener = 1
  1027. else: dvdscreener = 0
  1028. if re.search('<div class=ripdiv><b>R5/R6 DVDRip</b>', link) is not None: r5r6 = 1
  1029. else: r5r6 = 0
  1030. FlattenSrcType = selfAddon.getSetting('flatten-source-type')
  1031. #only detect and proceed directly to adding sources if flatten sources setting is true
  1032. if FlattenSrcType == 'true':
  1033. #add up total number of categories.
  1034. total = dvdrip + hd720p + dvdscreener + r5r6
  1035. #if there is only one category, skip to adding sources.
  1036. if total == 1:
  1037. if dvdrip == 1:
  1038. DVDRip(url)
  1039. elif hd720p == 1:
  1040. HD720p(url)
  1041. elif dvdscreener == 1:
  1042. DVDScreener(url)
  1043. elif r5r6 == 1:
  1044. R5R6(url)
  1045. #if there are multiple categories, add sub directories.
  1046. elif total > 1:
  1047. addCatDir(url,dvdrip,hd720p,dvdscreener,r5r6)
  1048. #if flattensources is set to false, don't flatten
  1049. elif FlattenSrcType == 'false':
  1050. addCatDir(url,dvdrip,hd720p,dvdscreener,r5r6)
  1051. def addCatDir(url,dvdrip,hd720p,dvdscreener,r5r6):
  1052. if dvdrip == 1:
  1053. addDir('DVDRip',url,101,os.path.join(art,'source_types','dvd.png'))
  1054. if hd720p == 1:
  1055. addDir('HD 720p',url,102,os.path.join(art,'source_types','hd720p.png'))
  1056. if dvdscreener == 1:
  1057. addDir('DVD Screener',url,103,os.path.join(art,'source_types','dvdscreener.png'))
  1058. if r5r6 == 1:
  1059. addDir('R5/R6 DVDRip',url,104,os.path.join(art,'source_types','r5r6.png'))
  1060. def Add_Multi_Parts(name,url,icon):
  1061. #StackMulti = selfAddon.getSetting('stack-multi-part')
  1062. #StackMulti=='false'
  1063. #if StackMulti=='true':
  1064. #save list of urls to later be stacked when user selects part
  1065. addExecute(name,url,200,icon)
  1066. #elif StackMulti=='false':
  1067. # addExecute(name,url,200,icon)
  1068. def PART(scrap,sourcenumber,args,cookie,hide2shared,megapic,shared2pic):
  1069. #check if source exists
  1070. sourcestring='Source #'+sourcenumber
  1071. checkforsource = re.search(sourcestring, scrap)
  1072. #if source exists proceed.
  1073. if checkforsource is not None:
  1074. #print 'Source #'+sourcenumber+' exists'
  1075. #check if source contains multiple parts
  1076. multiple_part = re.search('<p>Source #'+sourcenumber+':', scrap)
  1077. if multiple_part is not None:
  1078. #print sourcestring+' has multiple parts'
  1079. #get all text under source if it has multiple parts
  1080. multi_part_source=re.compile('<p>Source #'+sourcenumber+': (.+?)PART 1(.+?)</i><p>').findall(scrap)
  1081. #put scrape back together
  1082. for sourcescrape1,sourcescrape2 in multi_part_source:
  1083. scrape=sourcescrape1+'PART 1'+sourcescrape2
  1084. pair = re.compile("onclick='go\((\d+)\)'>PART\s+(\d+)").findall(scrape)
  1085. for id, partnum in pair:
  1086. url = GetSource(id, args, cookie)
  1087. # check if source is megaupload or 2shared, and add all parts as links
  1088. ismega = re.search('\.megaupload\.com/', url)
  1089. is2shared = re.search('\.2shared\.com/', url)
  1090. if ismega is not None:
  1091. partname='Part '+partnum
  1092. fullname=sourcestring+' | MU | '+partname
  1093. Add_Multi_Parts(fullname,url,megapic)
  1094. elif is2shared is not None and hide2shared == 'false':
  1095. partname='Part '+partnum
  1096. fullname=sourcestring+' | 2S | '+partname
  1097. Add_Multi_Parts(fullname,url,shared2pic)
  1098. # if source does not have multiple parts...
  1099. elif multiple_part is None:
  1100. # print sourcestring+' is single part'
  1101. # find corresponding '<a rel=?' entry and add as a one-link source
  1102. source5=re.compile('<a\s+rel='+sourcenumber+'.+?onclick=\'go\((\d+)\)\'>Source\s+#'+sourcenumber+':').findall(scrap)
  1103. # print source5
  1104. for id in source5:
  1105. url = GetSource(id, args, cookie)
  1106. ismega = re.search('\.megaupload\.com/', url)
  1107. is2shared = re.search('\.2shared\.com/', url)
  1108. if ismega is not None:
  1109. # print 'Source #'+sourcenumber+' is hosted by megaupload'
  1110. fullname=sourcestring+' | MU | Full'
  1111. addExecute(fullname,url,200,megapic)
  1112. elif is2shared is not None and hide2shared == 'false':
  1113. # print 'Source #'+sourcenumber+' is hosted by 2shared'
  1114. fullname=sourcestring+' | 2S | Full'
  1115. addExecute(fullname,url,200,shared2pic)
  1116. def GetSource(id, args, cookie):
  1117. m = random.randrange(100, 300) * -1
  1118. s = random.randrange(5, 50)
  1119. params = copy.copy(args)
  1120. params['id'] = id
  1121. params['m'] = m
  1122. params['s'] = s
  1123. paramsenc = urllib.urlencode(params)
  1124. body = GetURL(ICEFILMS_AJAX, params = paramsenc, cookie = cookie)
  1125. print 'response: %s' % body
  1126. source = re.search('url=(http[^&]+)', body).group(1)
  1127. url = urllib.unquote(source)
  1128. print 'url: %s' % url
  1129. return url
  1130. def SOURCE(page, sources):
  1131. # check for sources containing multiple parts or just one part
  1132. # get settings
  1133. selfAddon = xbmcaddon.Addon(id='plugin.video.icefilms')
  1134. hide2shared = selfAddon.getSetting('hide-2shared')
  1135. megapic=handle_file('megapic','')
  1136. shared2pic=handle_file('shared2pic','')
  1137. # extract the ingredients used to generate the XHR request
  1138. #
  1139. # set here:
  1140. #
  1141. # iqs: not used?
  1142. # url: not used?
  1143. # cap: form field for recaptcha? - always set to empty in the JS
  1144. # sec: secret identifier: hardwired in the JS
  1145. # t: token: hardwired in the JS
  1146. #
  1147. # set in GetSource:
  1148. #
  1149. # m: starts at 0, decremented each time a mousemove event is fired e.g. -123
  1150. # s: seconds since page loaded (> 5, < 250)
  1151. # id: source ID in the link's onclick attribute (extracted in PART)
  1152. args = {
  1153. 'iqs': '',
  1154. 'url': '',
  1155. 'cap': ''
  1156. }
  1157. sec = re.search("f\.lastChild\.value=\"([^']+)\",a", page).group(1)
  1158. t = re.search('"&t=([^"]+)",', page).group(1)
  1159. args['sec'] = sec
  1160. args['t'] = t
  1161. cookie = re.search('<cookie>(.+?)</cookie>', page).group(1)
  1162. print "saved cookie: %s" % cookie
  1163. # create a list of numbers: 1-21
  1164. num = 1
  1165. numlist = list('1')
  1166. while num < 21:
  1167. num = num+1
  1168. numlist.append(str(num))
  1169. #for every number, run PART.
  1170. #The first thing PART does is check whether that number source exists...
  1171. #...so it's not as CPU intensive as you might think.
  1172. for thenumber in numlist:
  1173. PART(sources,thenumber,args,cookie,hide2shared,megapic,shared2pic)
  1174. def DVDRip(url):
  1175. link=handle_file('mirror','open')
  1176. #string for all text under standard def border
  1177. defcat=re.compile('<div class=ripdiv><b>DVDRip / Standard Def</b>(.+?)</div>').findall(link)
  1178. for scrape in defcat:
  1179. SOURCE(link, scrape)
  1180. def HD720p(url):
  1181. link=handle_file('mirror','open')
  1182. #string for all text under hd720p border
  1183. defcat=re.compile('<div class=ripdiv><b>HD 720p</b>(.+?)</div>').findall(link)
  1184. for scrape in defcat:
  1185. SOURCE(link, scrape)
  1186. def DVDScreener(url):
  1187. link=handle_file('mirror','open')
  1188. #string for all text under dvd screener border
  1189. defcat=re.compile('<div class=ripdiv><b>DVD Screener</b>(.+?)</div>').findall(link)
  1190. for scrape in defcat:
  1191. SOURCE(link, scrape)
  1192. def R5R6(url):
  1193. link=handle_file('mirror','open')
  1194. #string for all text under r5/r6 border
  1195. defcat=re.compile('<div class=ripdiv><b>R5/R6 DVDRip</b>(.+?)</div>').findall(link)
  1196. for scrape in defcat:
  1197. SOURCE(link, scrape)
  1198. class TwoSharedDownloader:
  1199. def __init__(self):
  1200. self.cookieString = ""
  1201. self.re2sUrl = re.compile('(?<=window.location \=\')([^\']+)')
  1202. def returnLink(self, pageUrl):
  1203. # Open the 2Shared page and read its source to htmlSource
  1204. request = urllib2.Request(pageUrl)
  1205. response = urllib2.urlopen(request)
  1206. htmlSource = response.read()
  1207. # Search the source for link to the video and store it for later use
  1208. match = self.re2sUrl.search(htmlSource)
  1209. fileUrl = match.group(0)
  1210. # Extract the cookies set by visiting the 2Shared page
  1211. cookies = cookielib.CookieJar()
  1212. cookies.extract_cookies(response, request)
  1213. # Format the cookies so they can be used in XBMC
  1214. for item in cookies._cookies['.2shared.com']['/']:
  1215. self.cookieString += str(item) + "=" + str(cookies._cookies['.2shared.com']['/'][item].value) + "; "
  1216. self.cookieString += "WWW_JSESSIONID=" + str(cookies._cookies['www.2shared.com']['/']['JSESSIONID'].value)
  1217. # Arrange the spoofed header string in a format XBMC can read
  1218. headers = urllib.quote("User-Agent=Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)|Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8|Accept-Language=en-us,en;q=0.5|Accept-Encoding=gzip,deflate|Accept-Charset=ISO-8859-1,utf-8;q=0.7,*;q=0.7|Keep-Alive=115|Referer=" + pageUrl + "|Cookie=" + self.cookieString)
  1219. # Append the header string to the file URL
  1220. pathToPlay = fileUrl + "?" + headers
  1221. # Return the valid link
  1222. return pathToPlay
  1223. def SHARED2_HANDLER(url):
  1224. downloader2Shared = TwoSharedDownloader()
  1225. vidFile = downloader2Shared.returnLink(url)
  1226. #vidFile = TwoSharedDownloader.returnLink(url)
  1227. print str(vodFile)
  1228. match=re.compile('http\:\/\/(.+?)\.dc1').findall(vidFile)
  1229. for urlbulk in match:
  1230. finalurl='http://'+urlbulk+'.avi'
  1231. print '2Shared Direct Link: '+finalurl
  1232. return finalurl
  1233. #req = urllib2.Request(url)
  1234. #req.add_header('User-Agent', USER_AGENT)
  1235. #req.add_header('Referer', url)
  1236. #jar = cookielib.FileCookieJar("cookies")
  1237. #opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(jar))
  1238. #response = opener.open(req)
  1239. #link=response.read()
  1240. #response.close()
  1241. #dirlink=re.compile("window.location ='(.+?)';").findall(link)
  1242. #for surl in dirlink:
  1243. # return surl
  1244. def GetURL(url, params = None, referrer = ICEFILMS_REFERRER, cookie = None, save_cookie = False):
  1245. # print 'GetUrl: ' + url
  1246. # print 'params: ' + repr(params)
  1247. # print 'referrer: ' + repr(referrer)
  1248. # print 'cookie: ' + repr(cookie)
  1249. # print 'save_cookie: ' + repr(save_cookie)
  1250. if params:
  1251. req = urllib2.Request(url, params)
  1252. # req.add_header('Content-type', 'application/x-www-form-urlencoded')
  1253. else:
  1254. req = urllib2.Request(url)
  1255. req.add_header('User-Agent', USER_AGENT)
  1256. # as of 2011-06-02, IceFilms sources aren't displayed unless a valid referrer header is supplied:
  1257. # http://forum.xbmc.org/showpost.php?p=810288&postcount=1146
  1258. if referrer:
  1259. req.add_header('Referer', referrer)
  1260. if cookie:
  1261. req.add_header('Cookie', cookie)
  1262. # avoid Python >= 2.5 ternary operator for backwards compatibility
  1263. # http://wiki.xbmc.org/index.php?title=Python_Development#Version
  1264. response = urllib2.urlopen(req)
  1265. body = response.read()
  1266. if save_cookie:
  1267. setcookie = response.info().get('Set-Cookie', None)
  1268. print "Set-Cookie: %s" % repr(setcookie)
  1269. if setcookie:
  1270. setcookie = re.search('([^=]+=[^=;]+)', setcookie).group(1)
  1271. body = body + '<cookie>' + setcookie + '</cookie>'
  1272. response.close()
  1273. return body
  1274. def WaitIf():
  1275. #killing playback is necessary if switching playing of one megaup/2share stream to another
  1276. if xbmc.Player().isPlayingVideo() == True:
  1277. #currentvid=xbmc.Player().getPlayingFile()
  1278. #isice = re.search('.megaupload', currentvid)
  1279. xbmc.Player().stop()
  1280. def Get_Path(srcname,vidname):
  1281. #get settings
  1282. selfAddon = xbmcaddon.Addon(id='plugin.video.icefilms')
  1283. #get path for download
  1284. mypath=os.path.normpath(str(selfAddon.getSetting('download-folder')))
  1285. if os.path.exists(mypath):
  1286. #if source is split into parts, attach part number to the videoname.
  1287. if re.search('Part',srcname) is not None:
  1288. srcname=(re.split('\|+', srcname))[-1]
  1289. vidname=vidname+' part'+((re.split('\ +', srcname))[-1])
  1290. #add file extension
  1291. vidname = vidname+'.avi'
  1292. else:
  1293. #add file extension
  1294. vidname = vidname+'.avi'
  1295. initial_path=os.path.join(mypath,'Icefilms Downloaded Videos')
  1296. #is use special directory structure set to true?
  1297. SpecialDirs=selfAddon.getSetting('use-special-structure')
  1298. if SpecialDirs == 'true':
  1299. mediapath=os.path.normpath(handle_file('mediapath','open'))
  1300. mediapath=os.path.join(initial_path,mediapath)
  1301. if not os.path.exists(mediapath):
  1302. os.makedirs(mediapath)
  1303. finalpath=os.path.join(mediapath,vidname)
  1304. return finalpath
  1305. elif SpecialDirs == 'false':
  1306. mypath=os.path.join(initial_path,vidname)
  1307. return mypath
  1308. else:
  1309. return 'path not set'
  1310. def Item_Meta(name):
  1311. #set metadata, for selected source. this is done from 'phantom meta'.
  1312. # ie, meta saved earlier when we loaded the mirror page.
  1313. # very important that things are contained within try blocks, because streaming will fail if something in this function fails.
  1314. #set name and description, unicode cleaned.
  1315. try: open_vidname=handle_file('videoname','open')
  1316. except:
  1317. vidname = ''
  1318. print 'OPENING VIDNAME FAILED!'
  1319. else:
  1320. try: get_vidname = htmlcleaner.clean(open_vidname)
  1321. except:
  1322. print 'CLEANING VIDNAME FAILED! :',open_vidname
  1323. vidname = open_vidname
  1324. else: vidname = get_vidname
  1325. try: open_desc=handle_file('description','open')
  1326. except:
  1327. description = ''
  1328. print 'OPENING DESCRIPTION FAILED!'
  1329. else:
  1330. try: get_desc = htmlcleaner.clean(open_desc)
  1331. except:
  1332. print 'CLEANING DESCRIPTION FAILED! :',open_desc
  1333. description = open_desc
  1334. else: description = get_desc
  1335. #set other metadata strings from strings saved earlier
  1336. try: get_poster=handle_file('poster','open')
  1337. except: poster = ''
  1338. else: poster = get_poster
  1339. try: get_mpaa=handle_file('mpaa','open')
  1340. except: mpaa = None
  1341. else: mpaa = get_mpaa
  1342. #srcname=handle_file('sourcename','open')
  1343. srcname=name
  1344. listitem = xbmcgui.ListItem(srcname)
  1345. if not mpaa:
  1346. listitem.setInfo('video', {'Title': vidname, 'plotoutline': description, 'plot': description})
  1347. if mpaa:
  1348. listitem.setInfo('video', {'Title': vidname, 'plotoutline': description, 'plot': description, 'mpaa': mpaa})
  1349. listitem.setThumbnailImage(poster)
  1350. return listitem
  1351. def do_wait(account):
  1352. if account == 'premium':
  1353. return handle_wait(1,'Megaupload','Loading video with your *Premium* account.')
  1354. elif account == 'free':
  1355. return handle_wait(26,'Megaupload Free User','Loading video with your free account.')
  1356. elif account == 'none':
  1357. return handle_wait(46,'Megaupload','Loading video.')
  1358. def handle_wait(time_to_wait,title,text):
  1359. print 'waiting '+str(time_to_wait)+' secs'
  1360. pDialog = xbmcgui.DialogProgress()
  1361. ret = pDialog.create(' '+title)
  1362. secs=0
  1363. percent=0
  1364. increment = int(100 / time_to_wait)
  1365. cancelled = False
  1366. while secs < time_to_wait:
  1367. secs = secs + 1
  1368. percent = increment*secs
  1369. secs_left = str((time_to_wait - secs))
  1370. remaining_display = ' Wait '+secs_left+' seconds for the video stream to activate...'
  1371. pDialog.update(percent,' '+text,remaining_display)
  1372. xbmc.sleep(1000)
  1373. if (pDialog.iscanceled()):
  1374. cancelled = True
  1375. break
  1376. if cancelled == True:
  1377. print 'wait cancelled'
  1378. return False
  1379. else:
  1380. print 'done waiting'
  1381. return True
  1382. def Handle_Vidlink(url):
  1383. #video link preflight, pays attention to settings / checks if url is mega or 2shared
  1384. ismega = re.search('\.megaupload\.com/', url)
  1385. is2shared = re.search('\.2shared\.com/', url)
  1386. if ismega is not None:
  1387. WaitIf()
  1388. mu=megaroutines.megaupload(translatedicedatapath)
  1389. link=mu.resolve_megaup(url)
  1390. finished = do_wait(link[3])
  1391. if finished == True:
  1392. return link
  1393. else:
  1394. return None
  1395. elif is2shared is not None:
  1396. Notify('big','2Shared','2Shared is not supported by this addon. (Yet)','')
  1397. return False
  1398. #shared2url=SHARED2_HANDLER(url)
  1399. #return shared2url
  1400. def Stream_Source(name,url):
  1401. link=Handle_Vidlink(url)
  1402. listitem=Item_Meta(name)
  1403. print 'attempting to stream file'
  1404. try:
  1405. #directly call xbmc player (provides more options)
  1406. xbmc.Player( xbmc.PLAYER_CORE_DVDPLAYER ).play( link[0], listitem )
  1407. except:
  1408. print 'file streaming failed'
  1409. Notify('megaalert','','','')
  1410. def Download_Source(name,url):
  1411. #get proper name of vid
  1412. vidname=handle_file('videoname','open')
  1413. mypath=Get_Path(name,vidname)
  1414. if mypath == 'path not set':
  1415. Notify('Download Alert','You have not set the download folder.\n Please access the addon settings and set it.','','')
  1416. else:
  1417. if os.path.isfile(mypath) is True:
  1418. Notify('Download Alert','The video you are trying to download already exists!','','')
  1419. else:
  1420. link=Handle_Vidlink(url)
  1421. print 'attempting to download file'
  1422. try:
  1423. Download(link[0], mypath, vidname)
  1424. except:
  1425. print 'download failed'
  1426. def Check_Mega_Limits(name,url):
  1427. WaitIf()
  1428. mu=megaroutines.megaupload(translatedicedatapath)
  1429. limit=mu.dls_limited()
  1430. if limit is True:
  1431. Notify('megaalert1','','','')
  1432. elif limit is False:
  1433. Notify('megaalert2','','','')
  1434. def Kill_Streaming(name,url):
  1435. xbmc.Player().stop()
  1436. class StopDownloading(Exception):
  1437. def __init__(self, value):
  1438. self.value = value
  1439. def __str__(self):
  1440. return repr(self.value)
  1441. def Download(url, dest, displayname=False):
  1442. #get settings
  1443. selfAddon = xbmcaddon.Addon(id='plugin.video.icefilms')
  1444. if displayname == False:
  1445. displayname=url
  1446. DeleteIncomplete=selfAddon.getSetting('delete-incomplete-downloads')
  1447. dp = xbmcgui.DialogProgress()
  1448. dp.create('Downloading', '', displayname)
  1449. start_time = time.time()
  1450. try:
  1451. urllib.urlretrieve(url, dest, lambda nb, bs, fs: _pbhook(nb, bs, fs, dp, start_time))
  1452. except:
  1453. if DeleteIncomplete == 'true':
  1454. #delete partially downloaded file if setting says to.
  1455. while os.path.exists(dest):
  1456. try:
  1457. os.remove(dest)
  1458. break
  1459. except:
  1460. pass
  1461. #only handle StopDownloading (from cancel), ContentTooShort (from urlretrieve), and OS (from the race condition); let other exceptions bubble
  1462. if sys.exc_info()[0] in (urllib.ContentTooShortError, StopDownloading, OSError):
  1463. return 'false'
  1464. else:
  1465. raise
  1466. return 'downloaded'
  1467. def QuietDownload(url, dest):
  1468. #possibly useful in future addon versions
  1469. #dp = xbmcgui.DialogProgress()
  1470. #dp.create('Downloading', '', name)
  1471. start_time = time.time()
  1472. try:
  1473. #urllib.urlretrieve(url, dest, lambda nb, bs, fs: _pbhook(nb, bs, fs, dp, start_time))
  1474. urllib.urlretrieve(url, dest)
  1475. #xbmc.Player().play(dest)
  1476. except:
  1477. #delete partially downloaded file
  1478. while os.path.exists(dest):
  1479. try:
  1480. #os.remove(dest)
  1481. break
  1482. except:
  1483. pass
  1484. #only handle StopDownloading (from cancel), ContentTooShort (from urlretrieve), and OS (from the race condition); let other exceptions bubble
  1485. if sys.exc_info()[0] in (urllib.ContentTooShortError, StopDownloading, OSError):
  1486. return 'false'
  1487. else:
  1488. raise
  1489. return 'downloaded'
  1490. def _pbhook(numblocks, blocksize, filesize, dp, start_time):
  1491. try:
  1492. percent = min(numblocks * blocksize * 100 / filesize, 100)
  1493. currently_downloaded = float(numblocks) * blocksize / (1024 * 1024)
  1494. kbps_speed = numblocks * blocksize / (time.time() - start_time)
  1495. if kbps_speed > 0:
  1496. eta = (filesize - numblocks * blocksize) / kbps_speed
  1497. else:
  1498. eta = 0
  1499. kbps_speed = kbps_speed / 1024
  1500. total = float(filesize) / (1024 * 1024)
  1501. # print (
  1502. # percent,
  1503. # numblocks,
  1504. # blocksize,
  1505. # filesize,
  1506. # currently_downloaded,
  1507. # kbps_speed,
  1508. # eta,
  1509. # )
  1510. mbs = '%.02f MB of %.02f MB' % (currently_downloaded, total)
  1511. e = 'Speed: %.02f Kb/s ' % kbps_speed
  1512. e += 'ETA: %02d:%02d' % divmod(eta, 60)
  1513. dp.update(percent, mbs, e)
  1514. #print percent, mbs, e
  1515. except:
  1516. percent = 100
  1517. dp.update(percent)
  1518. if dp.iscanceled():
  1519. dp.close()
  1520. raise StopDownloading('Stopped Downloading')
  1521. def addExecute(name,url,mode,iconimage):
  1522. # A list item that executes the next mode, but does'nt clear the screen of current list items.
  1523. #encode url and name, so they can pass through the sys.argv[0] related strings
  1524. sysname = urllib.quote_plus(name)
  1525. sysurl = urllib.quote_plus(url)
  1526. u = sys.argv[0] + "?url=" + sysurl + "&mode=" + str(mode) + "&name=" + sysname
  1527. ok=True
  1528. liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
  1529. liz.setInfo( type="Video", infoLabels={ "Title": name } )
  1530. #handle adding context menus
  1531. contextMenuItems = []
  1532. contextMenuItems.append(('Download', 'XBMC.RunPlugin(%s?mode=201&name=%s&url=%s)' % (sys.argv[0], sysname, sysurl)))
  1533. contextMenuItems.append(('Download with jDownloader', 'XBMC.RunPlugin(plugin://plugin.program.jdownloader/?action=addlink&url=%s)' % (sysurl)))
  1534. contextMenuItems.append(('Check Mega Limits', 'XBMC.RunPlugin(%s?mode=202&name=%s&url=%s)' % (sys.argv[0], sysname, sysurl)))
  1535. contextMenuItems.append(('Kill Streams', 'XBMC.RunPlugin(%s?mode=203&name=%s&url=%s)' % (sys.argv[0], sysname, sysurl)))
  1536. liz.addContextMenuItems(contextMenuItems, replaceItems=True)
  1537. ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=False)
  1538. return ok
  1539. def addDir(name, url, mode, iconimage, metainfo=False, imdb=False, delfromfav=False, total=False, disablefav=False):
  1540. meta = metainfo
  1541. ### addDir with context menus and meta support ###
  1542. #encode url and name, so they can pass through the sys.argv[0] related strings
  1543. sysname = urllib.quote_plus(name)
  1544. sysurl = urllib.quote_plus(url)
  1545. #get nice unicode name text.
  1546. #name has to pass through lots of weird operations earlier in the script,
  1547. #so it should only be unicodified just before it is displayed.
  1548. name = htmlcleaner.clean(name)
  1549. u = sys.argv[0] + "?url=" + sysurl + "&mode=" + str(mode) + "&name=" + sysname
  1550. ok = True
  1551. #handle adding meta
  1552. if meta == False:
  1553. liz = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
  1554. liz.setInfo(type="Video", infoLabels={"Title": name})
  1555. if meta is not False:
  1556. liz = xbmcgui.ListItem(name, iconImage=meta['cover_url'], thumbnailImage=meta['cover_url'])
  1557. # XXX squashed bug: XBMC gives an incredibly inaccurate and unhelpful error:
  1558. #
  1559. # ERROR: Error Type: exceptions.TypeError
  1560. # ERROR: Error Contents: argument 1 must be unicode or str
  1561. #
  1562. # in an unrelated part of the code unless we ensure these values have the correct type (usually a string)
  1563. infoLabels = {}
  1564. infoLabels['code'] = str(meta['imdb_id'])
  1565. infoLabels['duration'] = str(meta['duration']) # XXX: was int
  1566. infoLabels['genre'] = str(meta['genres'])
  1567. infoLabels['mpaa'] = str(meta['mpaa'])
  1568. infoLabels['plot'] = meta['plot'] # XXX: don't try (and fail) to coerce Unicode to ASCII
  1569. infoLabels['premiered'] = str(meta['premiered'])
  1570. infoLabels['rating'] = float(meta['rating']) # XXX: was str
  1571. infoLabels['studio'] = meta['studios'] # XXX: don't try (and fail) to coerce Unicode to ASCII
  1572. infoLabels['title'] = name # XXX: don't try (and fail) to coerce Unicode to ASCII
  1573. try:
  1574. trailer_id = re.match('^[^v]+v=(.{11}).*', meta['trailer_url']).group(1)
  1575. infoLabels['trailer'] = "plugin://plugin.video.youtube/?action=play_video&videoid=%s" % trailer_id
  1576. except:
  1577. infoLabels['trailer'] = ''
  1578. liz.setInfo(type="Video", infoLabels=infoLabels)
  1579. ########
  1580. #handle adding context menus
  1581. contextMenuItems = []
  1582. # add/delete favourite
  1583. if disablefav is False: # disable fav is necessary for the scrapes in the homepage category.
  1584. if delfromfav is True:
  1585. #settings for when in the Favourites folder
  1586. contextMenuItems.append(('Delete from Ice Favourites', u'XBMC.RunPlugin(%s?mode=111&name=%s&url=%s)' % (sys.argv[0], sysname, sysurl)))
  1587. else:
  1588. #if directory is an episode list or movie
  1589. if mode == 100 or mode == 12:
  1590. if mode == 100:
  1591. contextMenuItems.append(('Movie Information', 'XBMC.Action(Info)'))
  1592. if imdb is not False:
  1593. sysimdb = urllib.quote_plus(str(imdb))
  1594. else:
  1595. #if no imdb number, it will have no metadata in Favourites
  1596. sysimdb = urllib.quote_plus('nothing')
  1597. contextMenuItems.append(('Add to Ice Favourites', u'XBMC.RunPlugin(%s?mode=110&name=%s&url=%s&imdbnum=%s)' % (sys.argv[0], sysname, sysurl, sysimdb)))
  1598. # switch on/off library mode (have it appear in list after favourite options)
  1599. if inLibraryMode():
  1600. contextMenuItems.append(('Switch off Library mode', u'XBMC.RunPlugin(%s?mode=300)' % (sys.argv[0])))
  1601. else:
  1602. contextMenuItems.append(('Switch to Library Mode', u'XBMC.RunPlugin(%s?mode=300)' % (sys.argv[0])))
  1603. if contextMenuItems:
  1604. liz.addContextMenuItems(contextMenuItems, replaceItems=True)
  1605. #########
  1606. #Do some crucial stuff
  1607. if total is False:
  1608. ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True)
  1609. if total is not False:
  1610. ok = xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=u, listitem=liz, isFolder=True, totalItems=int(total))
  1611. return ok
  1612. #VANILLA ADDDIR (kept for reference)
  1613. def VaddDir(name,url,mode,iconimage):
  1614. u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)
  1615. ok=True
  1616. liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
  1617. liz.setInfo( type="Video", infoLabels={ "Title": name } )
  1618. ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
  1619. return ok
  1620. # switch in and out of library mode
  1621. def toggleLibraryMode():
  1622. container_folder_path = xbmc.getInfoLabel('Container.FolderPath')
  1623. if inLibraryMode():
  1624. xbmc.executebuiltin("XBMC.ActivateWindow(VideoFiles,%s)" % container_folder_path)
  1625. # do not cacheToDisc cuz we want this code rerun
  1626. xbmcplugin.endOfDirectory( int(sys.argv[1]), succeeded=True, updateListing=False, cacheToDisc=False )
  1627. else:
  1628. xbmc.executebuiltin("XBMC.ActivateWindow(VideoLibrary,%s)" % container_folder_path)
  1629. # do not cacheToDisc cuz we want this code rerun
  1630. xbmcplugin.endOfDirectory( int(sys.argv[1]), succeeded=True, updateListing=False, cacheToDisc=False )
  1631. def inLibraryMode():
  1632. return xbmc.getCondVisibility("[Window.IsActive(videolibrary)]")
  1633. def get_params():
  1634. param=[]
  1635. paramstring=sys.argv[2]
  1636. if len(paramstring)>=2:
  1637. params=sys.argv[2]
  1638. cleanedparams=params.replace('?','')
  1639. if (params[len(params)-1]=='/'):
  1640. params=params[0:len(params)-2]
  1641. pairsofparams=cleanedparams.split('&')
  1642. param={}
  1643. for i in range(len(pairsofparams)):
  1644. splitparams={}
  1645. splitparams=pairsofparams[i].split('=')
  1646. if (len(splitparams))==2:
  1647. param[splitparams[0]]=splitparams[1]
  1648. return param
  1649. params=get_params()
  1650. url=None
  1651. name=None
  1652. mode=None
  1653. imdbnum=None
  1654. try:
  1655. url=urllib.unquote_plus(params["url"])
  1656. except:
  1657. pass
  1658. try:
  1659. name=urllib.unquote_plus(params["name"])
  1660. except:
  1661. pass
  1662. try:
  1663. imdbnum=urllib.unquote_plus(params["imdbnum"])
  1664. except:
  1665. pass
  1666. try:
  1667. mode=int(params["mode"])
  1668. except:
  1669. pass
  1670. print '==========================PARAMS:\nURL: %s\nNAME: %s\nMODE: %s\nIMDBNUM: %s\nMYHANDLE: %s\nPARAMS: %s' % ( url, name, mode, imdbnum, sys.argv[1], params )
  1671. if mode==None: #or url==None or len(url)<1:
  1672. print ""
  1673. CATEGORIES()
  1674. elif mode==50:
  1675. print ""+url
  1676. TVCATEGORIES(url)
  1677. elif mode==51:
  1678. print ""+url
  1679. MOVIECATEGORIES(url)
  1680. elif mode==52:
  1681. print ""+url
  1682. MUSICCATEGORIES(url)
  1683. elif mode==53:
  1684. print ""+url
  1685. STANDUPCATEGORIES(url)
  1686. elif mode==54:
  1687. print ""+url
  1688. OTHERCATEGORIES(url)
  1689. elif mode==55:
  1690. print ""+url
  1691. SEARCH(url)
  1692. elif mode==56:
  1693. print ""+url
  1694. ICEHOMEPAGE(url)
  1695. elif mode==57:
  1696. print ""+url
  1697. FAVOURITES(url)
  1698. elif mode==570:
  1699. print ""+url
  1700. TV_FAVOURITES(url)
  1701. elif mode==571:
  1702. print ""+url
  1703. MOVIE_FAVOURITES(url)
  1704. elif mode==58:
  1705. print ""+url
  1706. CLEAR_FAVOURITES(url)
  1707. elif mode==60:
  1708. print ""+url
  1709. RECENT(url)
  1710. elif mode==61:
  1711. print ""+url
  1712. LATEST(url)
  1713. elif mode==62:
  1714. print ""+url
  1715. WATCHINGNOW(url)
  1716. elif mode==63:
  1717. print ""+url
  1718. HD720pCat(url)
  1719. elif mode==64:
  1720. print ""+url
  1721. Genres(url)
  1722. elif mode==70:
  1723. print ""+url
  1724. Action(url)
  1725. elif mode==71:
  1726. print ""+url
  1727. Animation(url)
  1728. elif mode==72:
  1729. print ""+url
  1730. Comedy(url)
  1731. elif mode==73:
  1732. print ""+url
  1733. Documentary(url)
  1734. elif mode==74:
  1735. print ""+url
  1736. Drama(url)
  1737. elif mode==75:
  1738. print ""+url
  1739. Family(url)
  1740. elif mode==76:
  1741. print ""+url
  1742. Horror(url)
  1743. elif mode==77:
  1744. print ""+url
  1745. Romance(url)
  1746. elif mode==78:
  1747. print ""+url
  1748. SciFi(url)
  1749. elif mode==79:
  1750. print ""+url
  1751. Thriller(url)
  1752. elif mode==1:
  1753. print ""+url
  1754. MOVIEA2ZDirectories(url)
  1755. elif mode==2:
  1756. print ""+url
  1757. MOVIEINDEX(url)
  1758. elif mode==10:
  1759. print ""+url
  1760. TVA2ZDirectories(url)
  1761. elif mode==11:
  1762. print ""+url
  1763. TVINDEX(url)
  1764. elif mode==12:
  1765. print ""+url
  1766. TVSEASONS(url)
  1767. elif mode==13:
  1768. print ""+url
  1769. TVEPISODES(name,url)
  1770. elif mode==99:
  1771. print ""+url
  1772. CATPCHAENTER(url)
  1773. elif mode==100:
  1774. print ""+url
  1775. LOADMIRRORS(url)
  1776. elif mode==101:
  1777. print ""+url
  1778. DVDRip(url)
  1779. elif mode==102:
  1780. print ""+url
  1781. HD720p(url)
  1782. elif mode==103:
  1783. print ""+url
  1784. DVDScreener(url)
  1785. elif mode==104:
  1786. print ""+url
  1787. R5R6(url)
  1788. elif mode==110:
  1789. # if you dont use the "url", "name" params() then you need to define the value# along with the other params.
  1790. ADD_TO_FAVOURITES(name,url,imdbnum)
  1791. elif mode==111:
  1792. print ""+url
  1793. DELETE_FROM_FAVOURITES(name,url)
  1794. elif mode==200:
  1795. print ""+url
  1796. Stream_Source(name,url)
  1797. elif mode==201:
  1798. Download_Source(name,url)
  1799. elif mode==202:
  1800. Check_Mega_Limits(name,url)
  1801. elif mode==203:
  1802. Kill_Streaming(name,url)
  1803. elif mode==300:
  1804. toggleLibraryMode()
  1805. xbmcplugin.endOfDirectory(int(sys.argv[1]))