PageRenderTime 63ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/teh_tools.py

https://github.com/HIGHWAY99/plugin.video.vidics4
Python | 1723 lines | 1663 code | 8 blank | 52 comment | 53 complexity | 5acde5d775ecfcb99403c8669237cd8c MD5 | raw file
  1. ### ############################################################################################################
  2. ### #
  3. ### # Project: # teh_tools - by The Highway 2013.
  4. ### # Author: # The Highway
  5. ### # Version: # (ever changing)
  6. ### # Description: # My collection of common tools.
  7. ### #
  8. ### ############################################################################################################
  9. ### ############################################################################################################
  10. __plugin__ = "Vidics4.com"
  11. __authors__ = "The Highway"
  12. plugin_id = "plugin.video.vidics4"
  13. ### ############################################################################################################
  14. ### ############################################################################################################
  15. import xbmc,xbmcplugin,xbmcgui,xbmcaddon,xbmcvfs
  16. try: import requests ### <import addon="script.module.requests" version="1.1.0"/> ###
  17. except: t='' ### See https://github.com/kennethreitz/requests ###
  18. import urllib,urllib2,re,os,sys,htmllib,string,StringIO,logging,random,array,time,datetime
  19. import urlresolver
  20. import copy
  21. try: import json
  22. except ImportError: import simplejson as json
  23. try: import StorageServer
  24. except: import storageserverdummy as StorageServer
  25. cache = StorageServer.StorageServer(plugin_id)
  26. #import SimpleDownloader as downloader
  27. from t0mm0.common.net import Net as net
  28. from t0mm0.common.addon import Addon
  29. from config import *
  30. ### ############################################################################################################
  31. ### ############################################################################################################
  32. ### ### Common Imports ###
  33. ### ######################
  34. ### import shutil, md5, base64, unicodedata, threading, string
  35. ### import resources.lib.common as common
  36. ### import xbmc, xbmcplugin, xbmcgui, xbmcaddon, xbmcvfs, common
  37. ### import os.path, sys, urllib, urllib2, cookielib, string, httplib, socket, random
  38. ### import os, re, math, binascii, datetime, HTMLParser
  39. ### from BeautifulSoup import BeautifulStoneSoup
  40. ### from BeautifulSoup import BeautifulSoup , Tag, NavigableString
  41. ### try: from xml.etree import ElementTree
  42. ### except: from elementtree import ElementTree
  43. ### from xbmcgui import Dialog
  44. ### import copy
  45. ### requests, httplib, urlparse
  46. ### from operator import itemgetter
  47. ### from metahandler import metahandlers
  48. ### from metahandler import metacontainers
  49. ###
  50. ###
  51. ###
  52. ###
  53. ###
  54. ###
  55. ###
  56. ###
  57. ###
  58. ### ############################################################################################################
  59. ### ############################################################################################################
  60. def get_params():
  61. param=[]
  62. paramstring=sys.argv[2]
  63. if len(paramstring)>=2:
  64. params=sys.argv[2]
  65. cleanedparams=params.replace('?','')
  66. if (params[len(params)-1]=='/'):
  67. params=params[0:len(params)-2]
  68. pairsofparams=cleanedparams.split('&')
  69. param={}
  70. for i in range(len(pairsofparams)):
  71. splitparams={}
  72. splitparams=pairsofparams[i].split('=')
  73. if (len(splitparams))==2:
  74. param[splitparams[0]]=splitparams[1]
  75. return param
  76. ### ############################################################################################################
  77. ### ############################################################################################################
  78. cache = StorageServer.StorageServer(plugin_id)
  79. addon = Addon(plugin_id, sys.argv)
  80. local = xbmcaddon.Addon(id=plugin_id)
  81. __settings__ = xbmcaddon.Addon(id=plugin_id)
  82. __home__ = __settings__.getAddonInfo('path')
  83. addonPath = __settings__.getAddonInfo('path')
  84. artPath = addonPath+'/art/' #special://home/addons/plugin.video.theanimehighway/art
  85. if __settings__.getSetting("debug-enable") == "true":debugging=True #if (debugging==True):
  86. else: debugging=False
  87. if __settings__.getSetting("debug-show") == "true": shoDebugging=True #if (showDebugging==True):
  88. else: shoDebugging=False
  89. _debugging=debugging; _shoDebugging=shoDebugging
  90. params=get_params()
  91. ICON = os.path.join(__home__, 'icon.png')
  92. fanart = os.path.join(__home__, 'fanart.jpg')
  93. _addon=Addon(ps('_addon_id'), sys.argv);
  94. def addst(r,s=''): return _addon.get_setting(r) ## Get Settings
  95. def addpr(r,s=''): return _addon.queries.get(r,s) ## Get Params
  96. def cFL(t,c=ps('default_cFL_color')): ### For Coloring Text ###
  97. return '[COLOR '+c+']'+t+'[/COLOR]'
  98. ### ############################################################################################################
  99. ### ############################################################################################################
  100. url=None; urlbac=None; name=None; name2=None; type2=None; favcmd=None; mode=None; scr=None; imgfan=None; show=None; category=None
  101. try: category=urllib.unquote_plus(params["cat"])
  102. except: pass
  103. if category==None: category='Base'
  104. try:
  105. url=urllib.unquote_plus(params["url"])
  106. urlbac=url
  107. except: pass
  108. try: scr=urllib.unquote_plus(params["scr"])
  109. except: pass
  110. try: imgfan=urllib.unquote_plus(params["fan"])
  111. except: pass
  112. try: favcmd=urllib.unquote_plus(params["fav"])
  113. except: pass
  114. try: name=urllib.unquote_plus(params["name"])
  115. except: pass
  116. try: name2=urllib.unquote_plus(params["nm"])
  117. except: pass
  118. try: show=urllib.unquote_plus(params["show"])
  119. except: pass
  120. try: type2=int(params["tp"])
  121. except: pass
  122. try: mode=int(params["mode"])
  123. except: pass
  124. ### ############################################################################################################
  125. ### ############################################################################################################
  126. ICON8 = os.path.join(artPath, 'icon_watchdub.png');ICON7 = os.path.join(artPath, 'icon_dubhappy.png');ICON6 = os.path.join(artPath, 'iconDAOn2.png');ICON5 = os.path.join(artPath, 'iconA44couk.png');ICON4 = os.path.join(artPath, 'icongd.png');ICON3 = os.path.join(artPath, 'iconAPlus.png');ICON2 = os.path.join(artPath, 'iconA44.png');ICON1 = os.path.join(artPath, 'iconAG.png');ICON0 = os.path.join(__home__, 'icon.png')
  127. fanart8 = os.path.join(artPath, 'fanart_watchdub.jpg');fanart7 = os.path.join(artPath, 'fanart_dubhappy.jpg');fanart6 = os.path.join(artPath, 'fanartDAOn2.jpg');fanart5 = os.path.join(artPath, 'fanartA44couk.jpg');fanart4 = os.path.join(artPath, 'fanartgd.jpg');fanart3 = os.path.join(artPath, 'fanartAPlus.jpg');fanart2 = os.path.join(artPath, 'fanartA44.jpg');fanart1 = os.path.join(artPath, 'fanartAG.jpg');fanart0 = os.path.join(__home__, 'fanart.jpg')
  128. if type2==8: #site 8
  129. fanart = os.path.join(artPath, 'fanart_watchdub.jpg');ICON = os.path.join(artPath, 'icon_watchdub.png');mainSite='http://www.watchdub.com/'
  130. elif type2==7: #site 7
  131. fanart = os.path.join(artPath, 'fanart_dubhappy.jpg');ICON = os.path.join(artPath, 'icon_dubhappy.png');mainSite='http://www.dubhappy.eu/'
  132. elif type2==6: #site 6
  133. fanart = os.path.join(artPath, 'fanartDAOn2.jpg');ICON = os.path.join(artPath, 'iconDAOn2.png');mainSite='http://dubbedanimeon.com/'
  134. elif type2==5: #site 5
  135. fanart = os.path.join(artPath, 'fanartA44couk.jpg');ICON = os.path.join(artPath, 'iconA44couk.png');mainSite='http://www.anime44.co.uk/'
  136. if ('-anime' in url) and ('http://' not in url): url = mainSite + 'subanime/' + url
  137. if ('-anime' in url) and ('http://' not in scr) and (artPath not in scr): scr = mainSite + 'subanime/' + scr
  138. if ('-anime' in url) and ('http://' not in imgfan) and (artPath not in imgfan): imgfan = mainSite + 'subanime/' + imgfan
  139. #if ('-anime' not in url) and ('http://' not in url): url = mainSite + 'english-dubbed/' + url
  140. #if ('-anime' not in url) and ('http://' not in scr) and (artPath not in scr): scr = mainSite + 'english-dubbed/' + scr
  141. #if ('-anime' not in url) and ('http://' not in imgfan) and (artPath not in imgfan): imgfan = mainSite + 'english-dubbed/' + imgfan
  142. #if ('alpha-anime' in url): url.replace('alpha-anime','subanime')
  143. #if ('alpha-movies' in url): url.replace('alpha-movies','subanime')
  144. #if ('alpha-anime' in show): show.replace('alpha-anime','subanime')
  145. #if ('alpha-movies' in show): show.replace('alpha-movies','subanime')
  146. elif type2==4: #site 4
  147. fanart = os.path.join(artPath, 'fanartgd.jpg');ICON = os.path.join(artPath, 'icongd.png');mainSite='http://www.gooddrama.net/'
  148. elif type2==3: #site 3
  149. fanart = os.path.join(artPath, 'fanartplus.jpg');ICON = os.path.join(artPath, 'iconplus.png');mainSite='http://www.animeplus.tv/'
  150. elif type2==2: #site 2
  151. fanart = os.path.join(artPath, 'fanartA44.jpg');ICON = os.path.join(artPath, 'iconA44.png');mainSite='http://www.anime44.com/'
  152. else: #site 1
  153. fanart = os.path.join(artPath, 'fanartAG.jpg');ICON = os.path.join(artPath, 'iconAG.png');mainSite='http://www.animeget.com/'
  154. ### ############################################################################################################
  155. ### ############################################################################################################
  156. SiteBits=['nosite','animeget.com','anime44.com','animeplus.tv','gooddrama.net','anime44.co.uk','dubbedanimeon.com','dubhappy.eu','watchdub.com']
  157. SiteNames=['nosite','[COLOR blue][COLOR white]Anime[/COLOR]Get[/COLOR]','[COLOR red][COLOR white]Anime[/COLOR]44[/COLOR]','[COLOR darkblue][COLOR white]Anime[/COLOR]Plus[/COLOR]','[COLOR grey]Good[COLOR white]Drama[/COLOR][/COLOR]','[COLOR maroon][COLOR white]Anime[/COLOR]Zone[/COLOR]','[COLOR teal]Dubbed[COLOR white]Anime[/COLOR]On [/COLOR]','[COLOR cornflowerblue][COLOR white]dub[/COLOR]happy[/COLOR]','[COLOR cornflowerblue]Watch[/COLOR][COLOR white]Dub[/COLOR]','','']
  158. SitePrefixes=['nosite','','','','','subanime/','','','','','','','','','','','','']
  159. SiteSufixes= ['nosite','','','','','.html','','','','','','','','','','','','','']
  160. SiteSearchUrls= ['nosite','http://www.animeget.com/search','http://www.anime44.com/anime/search?search_submit=Go&key=','http://www.animeplus.tv/anime/search?search_submit=Go&key=','http://www.gooddrama.net/drama/search?stype=drama&search_submit=Go&key=','No Search Engine for VideoZone','http://dubbedanimeon.com/?s=','','','','','','','']
  161. SiteSearchMethod= ['nosite','post','get','get','get','VideoZone','get','','','','','','','']
  162. Sites=['animeget.com','anime44.com','animeplus.tv','gooddrama.net','anime44.co.uk','dubbedanimeon.com','dubhappy.eu','watchdub.com']
  163. MyAlphabet=['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']
  164. MyColors=['red','blue','darkblue','grey','maroon','teal','cornflowerblue','cornflowerblue','','','','']
  165. MyBrowser=['User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3']
  166. ### ############################################################################################################
  167. MyVideoLinkSrcMatches=['src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"' ,'src="(.+?)"' ,'src="(.+?)"', 'src="(.+?)"']
  168. MyVideoLinkSrcMatchesB=['src="(.+?)"', '<embed.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"', '<iframe.+?src="(.+?)"' ,'src="(.+?)"' ,'src="(.+?)"', 'src="(.+?)"']
  169. MyVideoLinkBrackets=['<iframe.+?src="(.+?)"', '<embed.+?src="(.+?)"', '<object.+?data="(.+?)"']
  170. MyAlphabet= ['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']
  171. MyBrowser= ['User-Agent','Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.3) Gecko/2008092417 Firefox/3.0.3']
  172. MySourcesV= ['videoweed.es', 'video44.net', 'novamov.com', 'dailymotion.com', 'videofun.me', 'yourupload.com', 'video.google.com', 'vidzur.com', 'upload2.com','putlocker.com','videoslasher.com','vidbull.com', 'uploadc.com', 'veevr.com', 'rutube.ru']
  173. #MySourcesV= ['videoweed.es', 'video44.net', 'novamov.com', 'dailymotion.com', 'videofun.me', 'yourupload.com', 'video.google.com', 'vidzur.com', 'upload2.com','putlocker.com','videoslasher.com','vidbull.com', 'UploadC', 'veevr.com', 'rutube.ru', 'MP4UPLOAD' ,'AUENGINE']
  174. MyIconsV= [artPath + 'videoweed.jpg', artPath + 'video44a.png', artPath + 'novamov.jpg', artPath + 'dailymotion.jpg', artPath + 'videofun.png', artPath + 'yourupload.jpg', artPath + 'googlevideo.gif', artPath + 'vidzur.png', artPath + 'upload2.png', artPath + 'putlocker.png', artPath + 'BLANK.png', artPath + 'BLANK.png', artPath + 'BLANK.png', artPath + 'BLANK.png', artPath + 'BLANK.png', artPath + 'BLANK.png', artPath + 'BLANK.png', artPath + 'BLANK.png', artPath + 'BLANK.png']#BLANK.png
  175. MyNamesV= ['VideoWeed', 'Video44', 'NovaMov', 'DailyMotion', 'VideoFun', 'YourUpload', 'Google Video', 'VidZur', 'Upload2', 'PutLocker', 'VideoSlasher', 'VidBull', 'UploadC', 'Veevr', 'RuTube', 'MP4Upload' ,'AUEngine']
  176. MyColorsV= ['lime', 'red', 'silver', 'green', 'cyan', 'grey', 'blue', 'orange', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white', 'white']
  177. ### ############################################################################################################
  178. ### ############################################################################################################
  179. def getURLr(url,dReferer):
  180. try:
  181. req = urllib2.Request(url,dReferer)
  182. req.add_header(MyBrowser[0], MyBrowser[1])
  183. req.add_header('Referer', dReferer)
  184. response = urllib2.urlopen(req)
  185. link=response.read()
  186. response.close()
  187. return(link)
  188. except:
  189. return('none')
  190. def getURL(url):
  191. try:
  192. req = urllib2.Request(url)
  193. req.add_header(MyBrowser[0], MyBrowser[1])
  194. response = urllib2.urlopen(req)
  195. link=response.read()
  196. response.close()
  197. return(link)
  198. except:
  199. return('none')
  200. def postURL(url,postStr):
  201. postData=urllib.urlencode(postStr)
  202. req = urllib2.Request(url,postData)
  203. req.add_header(MyBrowser[0], MyBrowser[1])
  204. response = urllib2.urlopen(req)
  205. link=response.read()
  206. response.close()
  207. return(link)
  208. def notification(header="", message="", sleep=5000 ):
  209. xbmc.executebuiltin( "XBMC.Notification(%s,%s,%i)" % ( header, message, sleep ) )
  210. #notify(msg=message, title=header, delay=sleep, image=ICON)
  211. #notify(msg=message, title='[COLOR green][B]'+header+'[/B][/COLOR]', delay=sleep, image=ICON0)
  212. ### ############################################################################################################
  213. ##Example##VaddDir('[COLOR blue]' + text[0] + '[/COLOR]', '', 0, '', False)
  214. def addFolder(name,name2,url,type2,mode,iconimage,categoryA='Blank'):
  215. ###addDir(name,name2,url,type2,mode,iconimage,fanimage)
  216. if ('http://' in iconimage) or (artPath in iconimage): t=''
  217. else: iconimage = artPath + iconimage
  218. mainSite='http://'+SiteBits[type2]+'/'
  219. addDir(name,name2,mainSite + url,type2,mode,iconimage,fanart,categoryA)
  220. #addDirD(name,name2,mainSite + url,type2,mode,artPath + iconimage,fanart,'wow')
  221. ### from videolinks.py ###
  222. #def addFolder(name,name2,url,type2,mode,iconimage):
  223. # ##addDir(name,name2,url,type2,mode,iconimage,fanimage)
  224. # addDir(name,name2,mainSite + url,type2,mode,artPath + iconimage,fanart)
  225. def addDirF(name,name2,url,favcmd,type2=0,mode=0,iconimage=ICON0,fanimage=fanart0,categoryA='Blank'):
  226. if (debugging==True): print 'Category: ',category,categoryA
  227. categoryA=category+' ::: '+categoryA
  228. u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&nm="+urllib.quote_plus(name2)+"&tp="+str(type2)+"&scr="+urllib.quote_plus(iconimage)+"&fan="+urllib.quote_plus(fanimage)+"&show="+urllib.quote_plus(name2)+"&cat="+categoryA+'&fav='+favcmd
  229. ok=True
  230. liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
  231. liz.setInfo( type="Video", infoLabels={ "Title": name } )
  232. liz.setProperty( "Fanart_Image", fanimage )
  233. ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
  234. return ok
  235. def addDir(name,name2,url,type2,mode,iconimage,fanimage,categoryA='Blank'):
  236. if (debugging==True): print 'Category: ',category,categoryA
  237. categoryA=category+' ::: '+categoryA
  238. u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&nm="+urllib.quote_plus(name2)+"&tp="+str(type2)+"&scr="+urllib.quote_plus(iconimage)+"&fan="+urllib.quote_plus(fanimage)+"&show="+urllib.quote_plus(name2)+"&cat="+categoryA
  239. ok=True
  240. liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
  241. liz.setInfo( type="Video", infoLabels={ "Title": name } )
  242. liz.setProperty( "Fanart_Image", fanimage )
  243. ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
  244. return ok
  245. def addDirD(name,name2,url,type2,mode,iconimage,fanimage,doSorting=False,categoryA='Blank',Labels='none'):#,plot='Blank',genres='none listed',status='none',released='unknown',rating='none',others='none'):
  246. if Labels=='none': Labels={ "Title" : name }
  247. if categoryA=='Blank': categoryA=name
  248. #if (debugging==True): print 'Category: ',category,categoryA
  249. categoryA=category+' ::: '+categoryA
  250. u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&nm="+urllib.quote_plus(name2)+"&tp="+str(type2)+"&scr="+urllib.quote_plus(iconimage)+"&fan="+urllib.quote_plus(fanimage)+"&show="+urllib.quote_plus(name2)+"&cat="+urllib.quote_plus(categoryA)
  251. #
  252. if (debugging==True): print u
  253. vc_tag=visited_DoCheck(u)
  254. #if (name=='Maburaho'): visited_add(u)
  255. if (debugging==True): print vc_tag
  256. #
  257. ok=True
  258. liz=xbmcgui.ListItem(vc_tag+name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
  259. liz.setInfo( type="Video", infoLabels= Labels ) #"Title": "'" + name + "'", "Plot" : plot, "Genres" : genres } )
  260. liz.setProperty( "Fanart_Image", fanimage )
  261. sysname = urllib.quote_plus(name)
  262. sysurl = urllib.quote_plus(url)
  263. sysscr = urllib.quote_plus(iconimage)
  264. sysfan = urllib.quote_plus(fanimage)
  265. #handle adding context menus
  266. contextMenuItems = []
  267. if (debugging==True): print getsetbool('enable-showurl')
  268. if __settings__.getSetting("enable-showurl") == "true":#doesn't work for some odd reason >> #if getsetbool('enable-showurl') == 'true':#
  269. contextMenuItems.append(('[B][COLOR orange]Show[/COLOR][/B] ~ [B]URL[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(name2), type2, 'showurl', sysurl, sysscr, sysfan)))
  270. contextMenuItems.append(('[B][COLOR green]ADD[/COLOR][/B] ~ [B][COLOR tan]Favorite[/COLOR][/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s&show=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(name2), type2, 'add', sysurl, sysscr, sysfan,urllib.quote_plus(name2))))
  271. contextMenuItems.append(('[B][COLOR red]REMOVE[/COLOR][/B] ~ [B][COLOR tan]Favorite[/COLOR][/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s&show=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(name2), type2, 'rem', sysurl, sysscr, sysfan,urllib.quote_plus(name2))))
  272. contextMenuItems.append(('Show Information', 'XBMC.Action(Info)'))
  273. #
  274. #contextMenuItems.append(('[B][COLOR orange]Test[/COLOR][/B] ~ [B]Test[/B]',"notification(%s,%s)" % (sysname,sysurl)))
  275. if (debugging==True): print getset('enable-clearfavorites')
  276. if __settings__.getSetting("enable-clearfavorites") == "true":#if getset('enable-clearfavorites')==True:
  277. contextMenuItems.append(('[B][COLOR yellow]Clear[/COLOR][/B] ~ [B][COLOR tan]Favorites[/COLOR][/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(name2), type2, 'clr', sysurl, sysscr, sysfan)))
  278. liz.addContextMenuItems(contextMenuItems, replaceItems=False)#True#liz.addContextMenuItems(contextMenuItems)
  279. if doSorting==True:
  280. xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_TITLE)
  281. ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
  282. return ok
  283. def addDirV(name,name2,url,type2,mode,iconimage,fanimage,categoryA=''):
  284. u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&nm="+urllib.quote_plus(name2)+"&tp="+str(type2)+"&cat="+categoryA
  285. ok=True
  286. liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
  287. liz.setInfo( type="Video", infoLabels={ "Title": name } )
  288. liz.setProperty( "Fanart_Image", fanimage )
  289. ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=True)
  290. return ok
  291. #def VaddDir(name, url, mode, iconimage, fanimage, is_folder=False,categoryA=''):#VANILLA ADDDIR (kept for reference)
  292. # u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&cat="+categoryA
  293. # ok=True
  294. # liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
  295. # liz.setInfo( type="Video", infoLabels={ "Title": name } )
  296. # liz.setProperty( "Fanart_Image", fanimage )
  297. # ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=is_folder)
  298. # return ok
  299. def VaddDir(name, url, mode, iconimage, fanimage, is_folder=False,categoryA=''):#VANILLA ADDDIR (kept for reference)
  300. u=sys.argv[0]+"?url="+urllib.quote_plus(url)+"&mode="+str(mode)+"&name="+urllib.quote_plus(name)+"&cat="+categoryA
  301. #if (debugging==True): print u
  302. ok=True
  303. liz=xbmcgui.ListItem(name, iconImage="DefaultFolder.png", thumbnailImage=iconimage)
  304. liz.setInfo( type="Video", infoLabels={ "Title": name } )
  305. liz.setProperty( "Fanart_Image", fanimage )
  306. contextMenuItems = []
  307. if __settings__.getSetting("enable-showurl") == "true":
  308. contextMenuItems.append(('[B][COLOR orange]Show[/COLOR][/B] ~ [B]URL[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],mode , urllib.quote_plus(name), urllib.quote_plus(name), 877, 'showurl', urllib.quote_plus(url), urllib.quote_plus(iconimage), urllib.quote_plus(fanimage))))
  309. liz.addContextMenuItems(contextMenuItems, replaceItems=True)#True#liz.addContextMenuItems(contextMenuItems)
  310. ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=is_folder)
  311. return ok
  312. ### from theanimehighway.py ###
  313. #def addLink(name,url,iconimage):
  314. # ok=True
  315. # liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
  316. # liz.setInfo( type="Video", infoLabels={ "Title": name } )
  317. # ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
  318. # return ok
  319. def addLink(name,url,iconimage=ICON,fanimage=fanart,shoname='none',downloadable=True):
  320. ok=True
  321. if shoname=='none':
  322. try: shoname=show
  323. except: shoname=name
  324. if fanimage==fanart:
  325. try: fanimage=imgfan
  326. except: pass
  327. if iconimage in MyIconsV:
  328. try:
  329. iconimage=scr
  330. except: pass
  331. #
  332. #liz=xbmcgui.ListItem(name, iconImage=artPath+"blank.gif", thumbnailImage=iconimage)
  333. liz=xbmcgui.ListItem(name, iconImage="DefaultVideo.png", thumbnailImage=iconimage)
  334. ##if (debugging==True): print 'sitename name: '+SiteNames[type2] + name
  335. ##liz.setInfo( type="Video", infoLabels={ "Title": name } )
  336. Studio=name
  337. if (' - [COLOR grey]' in Studio): Studio = Studio.split(' - [COLOR grey]')[0]
  338. if (' [COLOR grey]- ' in Studio): Studio = Studio.split(' [COLOR grey]- ')[0]
  339. if ('[COLOR grey] - ' in Studio): Studio = Studio.split('[COLOR grey] - ')[0]
  340. if (' - [COLOR' in Studio): Studio = Studio.split(' - [COLOR')[0]
  341. showtitle=shoname
  342. if (' [COLOR lime](English Dubbed)[/COLOR]' in showtitle):
  343. Studio += ' [COLOR lime](English Dubbed)[/COLOR]'
  344. showtitle = showtitle.replace(' [COLOR lime](English Dubbed)[/COLOR]','')
  345. elif ('English Dubbed' in showtitle): Studio += ' [COLOR lime](English Dubbed)[/COLOR]'
  346. elif ('Eng Dubbed' in showtitle): Studio += ' [COLOR lime](English Dubbed)[/COLOR]'
  347. elif ('Dubbed' in showtitle): Studio += ' [COLOR lime](Dubbed)[/COLOR]'
  348. elif ('English Subbed' in showtitle): Studio += ' [COLOR lime](English Subbed)[/COLOR]'
  349. elif ('Eng Subbed' in showtitle): Studio += ' [COLOR lime](English Subbed)[/COLOR]'
  350. elif ('Subbed' in showtitle): Studio += ' [COLOR lime](Subbed)[/COLOR]'
  351. liz.setInfo( type="Video", infoLabels={ "Title": showtitle, "Studio": Studio } )
  352. #liz.setProperty( "Fanart_Image", fanimage )
  353. contextMenuItems = []
  354. if (debugging==True): print getset('enable-showurl')
  355. if __settings__.getSetting("enable-showurl") == "true":#if getset('enable-showurl')=='true':
  356. contextMenuItems.append(('[B][COLOR orange]Show[/COLOR][/B] ~ [B]URL[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],0 , urllib.quote_plus(shoname), urllib.quote_plus(shoname), 0, 'showurl', urllib.quote_plus(url), iconimage, fanimage)))
  357. if (__settings__.getSetting("enable-downloading") == "true") and (downloadable == True):#if getset('enable-downloading',True)=='True':
  358. #if ('videofun.me' not in url) and ('videoweed.es' not in url) and ('dailymotion.com' not in url):
  359. if ('novamov.com' not in url) and ('videoweed.es' not in url) and ('dailymotion.com' not in url):
  360. contextMenuItems.append(('[B][COLOR purple]Download[/COLOR][/B] ~ [B]File[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],0 , urllib.quote_plus(shoname), urllib.quote_plus(shoname), 0, 'download', urllib.quote_plus(url), iconimage, fanimage)))
  361. liz.addContextMenuItems(contextMenuItems, replaceItems=True)#True#liz.addContextMenuItems(contextMenuItems)
  362. ##liz.addContextMenuItems([('[B][COLOR green]D[/COLOR][/B][B]ownload[/B]',"downloadfile(url,name)")])
  363. #liz.addContextMenuItems([('[B][COLOR green]D[/COLOR][/B][B]ownload[/B]',"XBMC.RunPlugin(%s?mode=%s&name=%s&url=%s)"%(sys.argv[0],999,name,url))])
  364. ##xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_LABEL)
  365. ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=liz)
  366. return ok
  367. ### ############################################################################################################
  368. def getset(idSetting):#,defaultValue=''):#Addon.getSetting('idNameOfSetting')
  369. return __settings__.getSetting(idSetting)#==defaultValue
  370. def getsetbool(idSetting):#Addon.getSetting('idNameOfSetting') #Method seems to be an utter failure for BOOL(true/false)'s
  371. #if (debugging==True): print __settings__.getSetting(idSetting) == 'true'
  372. return __settings__.getSetting(idSetting) == 'true'
  373. def getsetbool_(idSetting):#Addon.getSetting('idNameOfSetting') #Method seems to be an utter failure for BOOL(true/false)'s
  374. #if (debugging==True): print __settings__.getSetting(idSetting) == 'true'
  375. #try: tst=__settings__.getSetting(idSetting) == 'true'
  376. try: tst=__settings__.getSetting(idSetting)
  377. except: tst='False'
  378. if (tst=='true') or (tst=='True') or (tst=='TRUE'): return True
  379. else: return False
  380. #return __settings__.getSetting(idSetting) == 'true'
  381. ### ############################################################################################################
  382. def download_it_now(url,name):## mode=1901 ##
  383. name=name.strip()
  384. if ('[/COLOR]' in name): name=name.replace('[/COLOR]','')
  385. if ('[COLOR lime]' in name): name=name.replace('[COLOR lime]','')
  386. if ('[/color]' in name): name=name.replace('[/color]','')
  387. if ('[color lime]' in name): name=name.replace('[color lime]','')
  388. #if ('' in name): name=name.replace('','')
  389. #if ('' in name): name=name.replace('','')
  390. #if ('' in name): name=name.replace('','')
  391. notification(name,'Attempting Download...')
  392. download_file_prep(url,name,name,name)
  393. ## Example of how to connect to this addon's download feature from another plugin: ##
  394. #### xbmc.executebuiltin('XBMC.RunPlugin(%s?mode=1901&url=%s&name=%s)' % ('plugin://plugin.video.theanimehighway/', urllib.quote_plus(stream_url), urllib.quote_plus(title)))
  395. #### Simply make sure to include the quoted name and url for this function to work.
  396. #### File must be for a downloadable file or video stream, not for a page with a video on it.
  397. def download_metapack(url, dest, displayname=False):
  398. print 'Downloading Metapack'
  399. print 'URL: %s' % url
  400. print 'Destination: %s' % dest
  401. if not displayname:
  402. displayname = url
  403. dlg = xbmcgui.DialogProgress()
  404. dlg.create('Downloading', '', displayname)
  405. start_time = time.time()
  406. if os.path.isfile(dest):
  407. print 'File to be downloaded already esists'
  408. return True
  409. try:
  410. urllib.urlretrieve(url, dest, lambda nb, bs, fs: _pbhook(nb, bs, fs, dlg, start_time))
  411. except:
  412. #only handle StopDownloading (from cancel),
  413. #ContentTooShort (from urlretrieve), and OS (from the race condition);
  414. #let other exceptions bubble
  415. if sys.exc_info()[0] in (urllib.ContentTooShortError, StopDownloading, OSError):
  416. return False
  417. else:
  418. raise
  419. return True
  420. ###
  421. ### Dialog DialogBusy DialogButton Menu DialogContentSettings DialogContentMenu DialogExtendedProgressBar
  422. ### DialogFavourites DialogKaiToast DialogKeyboard DialogOK DialogProgress DialogVolumeBar DialogVideoScan
  423. ### DialogVideoInfo DialogTextViewer DialogSlider DialogSelect DialogSeekBar DialogYesNo
  424. ###
  425. def download_file(url='',name='temp',localfilename='temp',localpath=artPath,filext='.flv'):
  426. t=''
  427. ###url='https://github.com/HIGHWAY99/plugin.video.theanimehighway/archive/master.zip'
  428. ###localfilename='plugin.video.theanimehighway.zip'
  429. ###localpath=__home__
  430. #localfilewithpath=os.path.join(localpath,localfilename)
  431. #if (debugging==True): print 'Attempting to download "' + localfilename + '" to "' + localfilewithpath + '" from: ' + url
  432. ###dialogbox('To: ' + localfilewithpath,'Download File: ' + localfilename,'From: ' + url,'[COLOR red]This is still being tested.[/COLOR]')
  433. #if os.path.isfile(localfilewithpath):
  434. # if (debugging==True): print 'File to be downloaded already esists.'
  435. # notification('Download: '+localfilename,'File already exists.')#This function may never happen.
  436. # return
  437. #dialog = xbmcgui.Dialog()
  438. #if dialog.yesno('Download File', 'Do you wish to download this file?','File: ' + localfilename,'To: ' + localpath):
  439. # notification('Attempting to Download File',localfilename + '[CR] This function is still being tested.')#This function may never happen.
  440. # try: dp = xbmcgui.DialogProgressBG() ## Only works on daily build of XBMC.
  441. # except: dp = xbmcgui.DialogProgress()
  442. # dp.create('Downloading', '', localfilename)
  443. # ####
  444. # ####urllib.urlretrieve(url, dest, lambda nb, bs, fs: _pbhookb(nb, bs, fs, dlg, start_time))
  445. # ####
  446. # urllib.urlretrieve(url, localfilewithpath, lambda nb, bs, fs: _pbhookb(nb, bs, fs, dlg, start_time))
  447. # #urllib.urlretrieve(url, localfilewithpath)
  448. # notification('Download File','Download Complete.[CR] ' + localfilename,15000)
  449. # dialogbox_ok('File Size: ' + str(os.path.getsize(localfilewithpath)) + ' (bytes)','Download Complete','Note:','Make sure the size seems right.')
  450. # ###total_size += os.path.getsize(fp)
  451. ###
  452. ###
  453. ###notification('Download File','Sorry this feature is not yet implimented.')#This function may never happen.
  454. def _pbhookb(numblocks, blocksize, filesize, dlg, start_time):
  455. try:
  456. percent = min(numblocks * blocksize * 100 / filesize, 100)
  457. currently_downloaded = float(numblocks) * blocksize / (1024 * 1024)
  458. kbps_speed = numblocks * blocksize / (time.time() - start_time)
  459. if kbps_speed > 0:
  460. eta = (filesize - numblocks * blocksize) / kbps_speed
  461. else:
  462. eta = 0
  463. kbps_speed /= 1024
  464. total = float(filesize) / (1024 * 1024)
  465. mbs = '%.02f MB of %.02f MB' % (currently_downloaded, total)
  466. est = 'Speed: %.02f Kb/s ' % kbps_speed
  467. est += 'ETA: %02d:%02d' % divmod(eta, 60)
  468. dlg.update(percent, mbs, est)
  469. except:
  470. percent = 100
  471. dlg.update(percent)
  472. #if dlg.iscanceled(): ## used for xbmcgui.DialogProgress() but causes an error with xbmcgui.DialogProgressBG()
  473. # dlg.close()
  474. # raise StopDownloading('Stopped Downloading')
  475. def download_file_frodo(url='',name='temp',localfilename='temp',localpath=artPath,filext='.flv'):
  476. localfilewithpath=os.path.join(localpath,localfilename)
  477. if (debugging==True): print 'Attempting to download "' + localfilename + '" to "' + localfilewithpath + '" from: ' + url
  478. #dialogbox('To: ' + localfilewithpath,'Download File: ' + localfilename,'From: ' + url,'[COLOR red]This is still being tested.[/COLOR]')
  479. if os.path.isfile(localfilewithpath):
  480. if (debugging==True): print 'File to be downloaded already esists.'
  481. notification('Download: '+localfilename,'File already exists.')#This function may never happen.
  482. return
  483. dialog = xbmcgui.Dialog()
  484. if dialog.yesno('Download File', 'Do you wish to download this file?','File: ' + localfilename,'To: ' + localpath):
  485. notification('Attempting to Download File',localfilename + '[CR] This function is still being tested.')#This function may never happen.
  486. dp = xbmcgui.DialogProgress()
  487. dp.create('Downloading', '', localfilename)
  488. start_time = time.time()
  489. urllib.urlretrieve(url, localfilewithpath, lambda nb, bs, fs: _pbhookb_frodo(nb, bs, fs, dp, start_time)) #urllib.urlretrieve(url, localfilewithpath)
  490. ##urllib.urlretrieve(url, localfilewithpath, lambda nb, bs, fs: _pbhookb_frodo(nb, bs, fs, dlg, start_time)) #urllib.urlretrieve(url, localfilewithpath)
  491. notification('Download File','Download Complete.[CR] ' + localfilename,15000)
  492. dialogbox_ok('File Size: ' + str(os.path.getsize(localfilewithpath)) + ' (bytes)','Download Complete','Note:','Make sure the size seems right.')
  493. #total_size += os.path.getsize(fp)
  494. #notification('Download File','Sorry this feature is not yet implimented.')#This function may never happen.
  495. def _pbhookb_frodo(numblocks, blocksize, filesize, dlg, start_time):
  496. try:
  497. percent = min(numblocks * blocksize * 100 / filesize, 100)
  498. currently_downloaded = float(numblocks) * blocksize / (1024 * 1024)
  499. kbps_speed = numblocks * blocksize / (time.time() - start_time)
  500. if kbps_speed > 0:
  501. eta = (filesize - numblocks * blocksize) / kbps_speed
  502. else:
  503. eta = 0
  504. kbps_speed /= 1024
  505. total = float(filesize) / (1024 * 1024)
  506. mbs = '%.02f MB of %.02f MB' % (currently_downloaded, total)
  507. est = 'Speed: %.02f Kb/s ' % kbps_speed
  508. est += 'ETA: %02d:%02d' % divmod(eta, 60)
  509. dlg.update(percent, mbs, est)
  510. except:
  511. percent = 100
  512. dlg.update(percent)
  513. if dlg.iscanceled(): ## used for xbmcgui.DialogProgress() but causes an error with xbmcgui.DialogProgressBG()
  514. dlg.close()
  515. raise StopDownloading('Stopped Downloading')
  516. def filename_filter_out_year(name=''):
  517. years=re.compile(' \((\d+)\)').findall('__'+name+'__')
  518. for year in years:
  519. name=name.replace(' ('+year+')','')
  520. name=name.strip()
  521. return name
  522. def filename_filter_colorcodes(name=''):
  523. if ('[/color]' in name): name=name.replace('[/color]','')
  524. if ('[/COLOR]' in name): name=name.replace('[/COLOR]','')
  525. if ('[color lime]' in name): name=name.replace('[color lime]','')
  526. if ('[COLOR lime]' in name): name=name.replace('[COLOR lime]','')
  527. if ('[COLOR green]' in name): name=name.replace('[COLOR green]','')
  528. if ('[COLOR yellow]' in name): name=name.replace('[COLOR yellow]','')
  529. if ('[COLOR red]' in name): name=name.replace('[COLOR red]','')
  530. if ('[b]' in name): name=name.replace('[b]','')
  531. if ('[B]' in name): name=name.replace('[B]','')
  532. if ('[/b]' in name): name=name.replace('[/b]','')
  533. if ('[/B]' in name): name=name.replace('[/B]','')
  534. if ('[cr]' in name): name=name.replace('[cr]','')
  535. if ('[CR]' in name): name=name.replace('[CR]','')
  536. if ('[i]' in name): name=name.replace('[i]','')
  537. if ('[I]' in name): name=name.replace('[I]','')
  538. if ('[/i]' in name): name=name.replace('[/i]','')
  539. if ('[/I]' in name): name=name.replace('[/I]','')
  540. if ('[uppercase]' in name): name=name.replace('[uppercase]','')
  541. if ('[UPPERCASE]' in name): name=name.replace('[UPPERCASE]','')
  542. if ('[lowercase]' in name): name=name.replace('[lowercase]','')
  543. if ('[LOWERCASE]' in name): name=name.replace('[LOWERCASE]','')
  544. name=name.strip()
  545. #if ('' in name): name=name.replace('','')
  546. #if ('' in name): name=name.replace('','')
  547. #if ('' in name): name=name.replace('','')
  548. return name
  549. def Download_PrepExt(url,ext='.flv'):
  550. if '.zip' in url: ext='.zip' #Compressed Files
  551. elif '.rar' in url: ext='.rar'
  552. elif '.z7' in url: ext='.z7'
  553. elif '.png' in url: ext='.png' #images
  554. elif '.jpg' in url: ext='.jpg'
  555. elif '.gif' in url: ext='.gif'
  556. elif '.bmp' in url: ext='.bmp'
  557. elif '.jpeg' in url: ext='.jpeg'
  558. elif '.mp4' in url: ext='.mp4' #Videos
  559. elif '.mpeg' in url: ext='.mpeg'
  560. elif '.avi' in url: ext='.avi'
  561. elif '.flv' in url: ext='.flv'
  562. elif '.wmv' in url: ext='.wmv'
  563. elif '.mp3' in url: ext='.mp3' #others
  564. elif '.txt' in url: ext='.txt'
  565. #else: ext='.flv' #Default File Extention ('.flv')
  566. return ext
  567. def download_file_prep(url,name='none',name2='none',show='none',filext='none'):
  568. #
  569. if filext=='none':
  570. if '.zip' in url: filext='.zip' #Compressed Files
  571. elif '.rar' in url: filext='.rar'
  572. elif '.z7' in url: filext='.z7'
  573. elif '.png' in url: filext='.png' #images
  574. elif '.jpg' in url: filext='.jpg'
  575. elif '.gif' in url: filext='.gif'
  576. elif '.mp4' in url: filext='.mp4' #Videos
  577. elif '.mpeg' in url: filext='.mpeg'
  578. elif '.avi' in url: filext='.avi'
  579. elif '.flv' in url: filext='.flv'
  580. elif '.wmv' in url: filext='.wmv'
  581. elif '.mp3' in url: filext='.mp3' #others
  582. elif '.txt' in url: filext='.txt'
  583. else: filext='.flv' #Default File Extention ('.flv')
  584. try: name=filename_filter_colorcodes(name)
  585. except: name=''
  586. try: name2=filename_filter_colorcodes(name2)
  587. except: name2=name
  588. try: show=filename_filter_colorcodes(show)
  589. except: show=name
  590. filname = name + filext
  591. dialog = xbmcgui.Dialog()
  592. if dialog.yesno('Local Path', 'Where would you like to download to?', '', filname, 'Shows', 'Movies'):
  593. localpath = getset('folder-movie')#__settings__.getSetting('folder-movie')
  594. else:
  595. localpath = getset('folder-show')#__settings__.getSetting('folder-show')
  596. if (debugging==True): print localpath
  597. #download_file(url,name,filname,localpath) ## For nightly builds 13.x+
  598. download_file_frodo(url,name,filname,localpath) ## For Frodo builds 12.x
  599. #
  600. #def downloadfile(url,name):
  601. # import SimpleDownloader as downloader
  602. # downloader = downloader.SimpleDownloader()
  603. # url='http://www.xbmcswift.com/en/develop/api.html'
  604. # dlfold='/tmp'
  605. # #dlfold='F:\\xbmc\\theanimehighway\\'
  606. # params = { "url": url, "download_path": dlfold, "Title": name }
  607. # #params = { "url": url, "download_path": "F:\\xbmc\\theanimehighway\\", "Title": name, "live": "true", "duration": "20" }
  608. # filenm = name + ".txt"
  609. # #filenm = name + ".mp4"
  610. # notification('file download: ' + name, 'Downloading "' + url + '" to "' + filenm + '"')
  611. # downloader.download(filenm, params)
  612. ### ############################################################################################################
  613. #def dialogboxyesno(txtMessage="",txtHeader="",txt3="",txt4=""):
  614. # dialog = xbmcgui.Dialog()
  615. # if dialog.yesno(txtHeader, txtMessage, txt3, txt4):
  616. def dialogbox_ok(txtMessage="",txtHeader="",txt3="",txt4=""):
  617. dialog = xbmcgui.Dialog()
  618. ok = dialog.ok(txtHeader, txtMessage, txt3, txt4)
  619. #keyboard = xbmc.Keyboard(txtMessage, txtHeader, passwordField)#("text to show","header text", True="password field"/False="show text")
  620. #import win64clipboard as wc
  621. def copy_to_clipboard(msg):
  622. notification('Copy-to-Clipboard','Sorry this feature is not yet implimented.')
  623. #
  624. #
  625. #if sys.platform == 'win32':
  626. # wc.OpenClipboard()
  627. # wc.EmptyClipboard()
  628. # wc.SetClipboardData(win32con.CF_TEXT, msg)
  629. # wc.CloseClipboard()
  630. #
  631. #
  632. def showkeyboard(txtMessage="",txtHeader="",passwordField=False):
  633. if txtMessage=='None': txtMessage=''
  634. keyboard = xbmc.Keyboard(txtMessage, txtHeader, passwordField)#("text to show","header text", True="password field"/False="show text")
  635. keyboard.doModal()
  636. if keyboard.isConfirmed():
  637. return keyboard.getText()
  638. else:
  639. return False # return ''
  640. def dialogbox_number(Header="",n='',type=0):
  641. #Types: #0 : ShowAndGetNumber #1 : ShowAndGetDate #2 : ShowAndGetTime #3 : ShowAndGetIPAddress dialog = xbmcgui.Dialog()
  642. dlg=xbmcgui.Dialog()
  643. if (n==''): r=dlg.numeric(1,Header)
  644. else: r=dlg.numeric(1,Header,n)
  645. return r
  646. ### ############################################################################################################
  647. def checkForPartNo(url,partInfo=''):
  648. url=urllib.unquote_plus(url)
  649. if '_part_' in urllib.unquote_plus(url):
  650. try:
  651. matchaptn=re.compile('_part_(.+?).').findall(url)
  652. partInfo=' - Part # ' + matchaptn[0]
  653. except:
  654. partInfo=' - Part # ' + 'Unknown'
  655. elif '-part-' in urllib.unquote_plus(url):
  656. try:
  657. matchaptn=re.compile('-part-(.+?).').findall(url)
  658. partInfo=' - Part # ' + matchaptn[0]
  659. except:
  660. partInfo=' - Part # ' + 'Unknown'
  661. elif 'part' in urllib.unquote_plus(url):
  662. try:
  663. matchaptn=re.compile('part(.+?).').findall(url)
  664. partInfo=' - Part # ' + matchaptn[0]
  665. except:
  666. temp=''
  667. return partInfo
  668. ### ############################################################################################################
  669. def aSortMeth(sM,h=int(sys.argv[1])):
  670. xbmcplugin.addSortMethod(handle=h, sortMethod=sM)
  671. def set_view(content='none',view_mode=50,do_sort=False):
  672. if (debugging==True): print 'content type: ',content
  673. if (debugging==True): print 'view mode: ',view_mode
  674. h=int(sys.argv[1])
  675. if (content is not 'none'): xbmcplugin.setContent(h, content)
  676. #types: # set_view()
  677. # 50 CommonRootView
  678. # 51 FullWidthList
  679. # 500 ThumbnailView
  680. # 501 PosterWrapView
  681. # 508 PosterWrapView2_Fanart
  682. # 505 WideIconView
  683. #
  684. #
  685. # set content type so library shows more views and info
  686. if (tfalse(addst("auto-view"))==True):
  687. xbmc.executebuiltin("Container.SetViewMode(%s)" % view_mode)
  688. # set sort methods - probably we don't need all of them
  689. #aSortMeth(xbmcplugin.SORT_METHOD_NONE)
  690. aSortMeth(xbmcplugin.SORT_METHOD_UNSORTED)
  691. aSortMeth(xbmcplugin.SORT_METHOD_TITLE)
  692. aSortMeth(xbmcplugin.SORT_METHOD_TITLE_IGNORE_THE)
  693. aSortMeth(xbmcplugin.SORT_METHOD_VIDEO_TITLE)
  694. aSortMeth(xbmcplugin.SORT_METHOD_VIDEO_SORT_TITLE_IGNORE_THE)
  695. aSortMeth(xbmcplugin.SORT_METHOD_LABEL)
  696. aSortMeth(xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
  697. aSortMeth(xbmcplugin.SORT_METHOD_VIDEO_RATING)
  698. aSortMeth(xbmcplugin.SORT_METHOD_DATE)
  699. aSortMeth(xbmcplugin.SORT_METHOD_VIDEO_YEAR)
  700. #aSortMeth(xbmcplugin.SORT_METHOD_PROGRAM_COUNT)
  701. aSortMeth(xbmcplugin.SORT_METHOD_VIDEO_RUNTIME)
  702. aSortMeth(xbmcplugin.SORT_METHOD_GENRE)
  703. #
  704. aSortMeth(xbmcplugin.SORT_METHOD_FILE)
  705. #aSortMeth(xbmcplugin.SORT_METHOD_VIDEO_RUNTIME)
  706. #aSortMeth(xbmcplugin.SORT_METHOD_VIDEO_RATING)
  707. #aSortMeth(xbmcplugin.SORT_METHOD_STUDIO)
  708. #aSortMeth(xbmcplugin.SORT_METHOD_STUDIO_IGNORE_THE)
  709. #aSortMeth(xbmcplugin.SORT_METHOD_PLAYLIST_ORDER)
  710. aSortMeth(xbmcplugin.SORT_METHOD_EPISODE)
  711. aSortMeth(xbmcplugin.SORT_METHOD_DURATION)
  712. #aSortMeth(xbmcplugin.SORT_METHOD_BITRATE)
  713. #
  714. if (do_sort == True):
  715. #aSortMeth(h, xbmcplugin.SORT_METHOD_TITLE)#xbmcplugin.SORT_METHOD_LABEL
  716. xbmcplugin.addSortMethod(h, xbmcplugin.SORT_METHOD_TITLE)#xbmcplugin.SORT_METHOD_LABEL
  717. #
  718. ####xbmcplugin.addSortMethod(handle=h, sortMethod=xbmcplugin.SORT_METHOD_TRACKNUM)
  719. # #SORT_METHOD_NONE, SORT_METHOD_UNSORTED, SORT_METHOD_VIDEO_TITLE,
  720. # # SORT_METHOD_TRACKNUM, SORT_METHOD_FILE, SORT_METHOD_TITLE
  721. # # SORT_METHOD_TITLE_IGNORE_THE, SORT_METHOD_LABEL
  722. # # SORT_METHOD_LABEL_IGNORE_THE, SORT_METHOD_VIDEO_SORT_TITLE,
  723. # # SORT_METHOD_VIDEO_SORT_TITLE_IGNORE_THE
  724. ### ############################################################################################################
  725. ### from theanimehighway.py ###
  726. #def showurl(name,url,scr=ICON0,imgfan=fanart0,type2=0,mode=0):
  727. # copy_to_clipboard(url)
  728. # if (debugging==True): print url, name, scr, imgfan
  729. # kmsg=showkeyboard(url, name)
  730. def showurl(name,url,scr=ICON,imgfan=fanart,type2=0,mode=0):
  731. copy_to_clipboard(url)
  732. if (debugging==True): print url, name, scr, imgfan
  733. kmsg=showkeyboard(url, name)
  734. ### ############################################################################################################
  735. def metaArt_empty():
  736. saved_fans = cache.get('MetaArt_')
  737. fans = []
  738. cache.set('MetaArt_', str(fans))
  739. notification('[B][COLOR orange]Fanart[/COLOR][/B]','[B] Your Cached Fanart(s) Have Been Wiped Clean. Bye Bye.[/B]')
  740. def emptyFavorites():
  741. saved_favs = cache.get('favourites_')
  742. favs = []
  743. cache.set('favourites_', str(favs))
  744. notification('[B][COLOR orange]Favorites[/COLOR][/B]','[B] Your Favorites Have Been Wiped Clean. Bye Bye.[/B]')
  745. def addfavorite(name,url,scr=ICON0,imgfan=fanart0,tp2=0,mode=0):
  746. if (debugging==True): print name,url,scr,imgfan,tp2,mode
  747. saved_favs = cache.get('favourites_')
  748. favs = []
  749. if saved_favs:
  750. favs = eval(saved_favs)
  751. if favs:
  752. if (name,url,scr,imgfan,tp2,mode) in favs:
  753. notification('[B][COLOR orange]'+name.upper()+'[/COLOR][/B]','[B] Already in your Favorites[/B]')
  754. #xbmc.executebuiltin("XBMC.Notification([B][COLOR orange]"+name.upper()+"[/COLOR][/B],[B] Already in your Favourites[/B],5000,"")")
  755. return
  756. favs.append((name,url,scr,imgfan,tp2,mode))
  757. cache.set('favourites_', str(favs))
  758. notification('[B][COLOR orange]'+name.upper()+'[/COLOR][/B]','[B] Added to Favorites[/B]')
  759. #xbmc.executebuiltin("XBMC.Notification([B][COLOR orange]"+name.upper()+"[/COLOR][/B],[B] Added to Favourites[/B],5000,"")")
  760. def removefavorite(name,url,scr=ICON0,imgfan=fanart0,tp2=0,mode=0):#,scr,imgfan
  761. if (debugging==True): print name,url,scr,imgfan,tp2,mode
  762. saved_favs = cache.get('favourites_')
  763. if saved_favs:
  764. favs = eval(saved_favs)
  765. if (name,url,scr,imgfan,tp2,mode) in favs:
  766. favs.remove((name,url,scr,imgfan,tp2,mode))
  767. cache.set('favourites_', str(favs))
  768. notification('[B][COLOR orange]'+name.upper()+'[/COLOR][/B]','[B] Removed from Favorites[/B]')
  769. if (debugging==True): print name+' Removed from Favorites.'
  770. #set_view('tvshows',int(getset('viewmode-favs')),True)
  771. #VaddDir('[COLOR maroon] Visit with [COLOR tan]Highway[/COLOR] and others @ [COLOR white]#XBMCHUB[/COLOR] on [COLOR white]irc.freenode.net[/COLOR]:6667 [/COLOR]', '', 0, ICON, fanart, False)
  772. #LastPage=page_last_update()
  773. #xbmc.executebuiltin("XBMC.Container.Update(%s)" % (LastPage))
  774. xbmc.executebuiltin("XBMC.Container.Refresh")
  775. #VaddDir('[COLOR maroon] Visit with [COLOR tan]Highway[/COLOR] and others @ [COLOR white]#XBMCHUB[/COLOR] on [COLOR white]irc.freenode.net[/COLOR]:6667 [/COLOR]', '', 0, ICON, fanart, False)
  776. ##xbmc.Container.Refresh
  777. #xbmc.sleep(4000)
  778. elif ((name) in favs):
  779. favs.remove((name))
  780. cache.set('favourites_', str(favs))
  781. notification('[B][COLOR orange]'+name.upper()+'[/COLOR][/B]','[B] Removed from Favorites[/B]')
  782. if (debugging==True): print name+' Removed from Favorites. (Hopefully)'
  783. xbmc.executebuiltin("XBMC.Container.Refresh")
  784. elif favs:
  785. tf=False
  786. for (_name,_url,_scr,_imgfan,_tp2,_mode) in favs:
  787. if (name==_name):
  788. favs.remove((name,_url,_scr,_imgfan,_tp2,_mode))
  789. cache.set('favourites_', str(favs))
  790. notification('[B][COLOR orange]'+name.upper()+'[/COLOR][/B]','[B] Removed from Favorites[/B]')
  791. if (debugging==True): print name+' Removed from Favorites. (Hopefully)'
  792. tf=True
  793. xbmc.executebuiltin("XBMC.Container.Refresh")
  794. return
  795. if (tf==False): notification('[B][COLOR orange]'+name.upper()+'[/COLOR][/B]','[B] not found in your Favorites[/B]')
  796. else:
  797. notification('[B][COLOR orange]'+name.upper()+'[/COLOR][/B]','[B] not found in your Favorites[/B]')
  798. #xbmc.executebuiltin("XBMC.Notification([B][COLOR orange]"+name.upper()+"[/COLOR][/B],[B] Removed from Favourites[/B],5000,"")")
  799. def metaArt_add(show_name,show_title_thetvdb,show_id,url_thetvdb,show_fanart,show_poster,show_bannner,show_desc,show_genres,show_status,show_language,show_network,show_rating):#metaArt_add(match_showname,match_showid,match_thetvdb_url,match_fanart,match_poster,match_banner)
  800. ##if (debugging==True): print name,url,scr,imgfan,tp2,mode
  801. saved_fans = cache.get('MetaArt_')
  802. fans = []
  803. if saved_fans:
  804. fans = eval(saved_fans)
  805. if fans:
  806. if (show_name,show_id,url_thetvdb,show_fanart,show_poster,show_bannner,show_desc) in fans:
  807. #notification('[B][COLOR orange]'+show_name.upper()+'[/COLOR][/B]','[B] Already in your Cached Fanart(s).[/B]')
  808. return
  809. fans.append((show_name,show_title_thetvdb,show_id,url_thetvdb,show_fanart,show_poster,show_bannner,show_desc,show_genres,show_status,show_language,show_network,show_rating))
  810. cache.set('MetaArt_', str(fans))
  811. #notification('[B][COLOR orange]'+show_name.upper()+'[/COLOR][/B]','[B] Added to MetaArt[/B]')
  812. ##xbmc.executebuiltin("XBMC.Notification([B][COLOR orange]"+name.upper()+"[/COLOR][/B],[B] Added to Favourites[/B],5000,"")")
  813. ### ############################################################################################################
  814. def getAlphaFolder(alphaTxt='',typeTxt='',slashTxt=''):
  815. if type2==5: return 'subanime/'
  816. #elif mode==211: return 'alpha-anime/'
  817. #elif mode==311: return 'alpha-movies/'
  818. else: return alphaTxt+typeTxt+slashTxt
  819. def getAlphaEnd(typeTxt='',alphaTxt=''):
  820. if (type2==5) and (typeTxt=='anime'): return '-2'
  821. elif (type2==5) and (typeTxt=='movies'): return '-3'
  822. else: return alphaTxt
  823. def showlistdir(vLetterA,vLetterB,vImageC):#SitePrefixes#SiteSufixes
  824. addFolder('[COLOR ' + MyColors[1] + ']' + vLetterB + '[/COLOR]','shows',getAlphaFolder('alpha-','anime','/') + vLetterA + getAlphaEnd('anime') + SiteSufixes[type2],type2,6,'Glossy_Black\\' + vImageC + '.png')
  825. def movielistdir(vLetterA,vLetterB,vImageC):
  826. addFolder('[COLOR ' + MyColors[1] + ']' + vLetterB + '[/COLOR]','movies',getAlphaFolder('alpha-','movies','/') + vLetterA + getAlphaEnd('movies') + SiteSufixes[type2],type2,6,'Glossy_Black\\' + vImageC + '.png')
  827. ### ############################################################################################################
  828. def clean_filename(filename):
  829. # filename = _1CH.unescape(filename)
  830. return re.sub('[/:"*?<>|]+', ' ', filename)
  831. def ParseDescription(plot): ## Cleans up the dumb number stuff thats ugly.
  832. if ('&#' in plot) and (';' in plot):
  833. if ("&amp;" in plot): plot=plot.replace('&amp;' ,'&')#&amp;#x27;
  834. if ("&#8211;" in plot): plot=plot.replace("&#8211;",";") #unknown
  835. if ("&#8216;" in plot): plot=plot.replace("&#8216;","'")
  836. if ("&#8217;" in plot): plot=plot.replace("&#8217;","'")
  837. if ("&#8220;" in plot): plot=plot.replace('&#8220;','"')
  838. if ("&#8221;" in plot): plot=plot.replace('&#8221;','"')
  839. if ("&#215;" in plot): plot=plot.replace('&#215;' ,'x')
  840. if ("&#x27;" in plot): plot=plot.replace('&#x27;' ,"'")
  841. if ("&#xF4;" in plot): plot=plot.replace('&#xF4;' ,"o")
  842. if ("&#xb7;" in plot): plot=plot.replace('&#xb7;' ,"-")
  843. if ("&#xFB;" in plot): plot=plot.replace('&#xFB;' ,"u")
  844. if ("&#xE0;" in plot): plot=plot.replace('&#xE0;' ,"a")
  845. if ("&#0421;" in plot): plot=plot.replace('&#0421;',"")
  846. if ("&#xE9;" in plot): plot=plot.replace('&#xE9;' ,"e")
  847. if ("&#xE2;" in plot): plot=plot.replace('&#xE2;' ,"a")
  848. if ('&#' in plot) and (';' in plot):
  849. try: matches=re.compile('&#(.+?);').findall(plot)
  850. except: matches=''
  851. if (matches is not ''):
  852. for match in matches:
  853. if (match is not '') and (match is not ' ') and ("&#"+match+";" in plot): plot=plot.replace("&#"+match+";" ,"")
  854. #if ("\xb7" in plot): plot=plot.replace('\xb7' ,"-")
  855. #if ('&#' in plot) and (';' in plot): plot=unescape_(plot)
  856. return plot
  857. def unescape_(s):
  858. p = htmllib.HTMLParser(None)
  859. p.save_bgn()
  860. p.feed(s)
  861. return p.save_end()
  862. def check_ifUrl_isHTML(pathUrl): ## Doesn't work yet. Needs Fixed.
  863. ######## 'http://s12.trollvid.net/videos/'+testString+'/'+vid_id1+'.mp4'
  864. ##timeout=10
  865. ##socket.setdefaulttimeout(timeout) # timeout in seconds
  866. if (debugging==True): print 'TestingUrl: '+pathUrl
  867. try:
  868. req=urllib2.Request(pathUrl)#,timeout=6)
  869. tUrl=urllib2.urlopen(req)
  870. return True
  871. except:
  872. return False
  873. ### ############################################################################################################
  874. def visited_DoCheck(urlToCheck,s='[B][COLOR yellowgreen]@[/COLOR][/B] ',e='[COLOR black]@[/COLOR] '):
  875. #visited_empty()
  876. #return ''
  877. vc=visited_check(urlToCheck)
  878. if (vc==True): return s
  879. else:
  880. ##visited_add(urlToCheck)
  881. return e
  882. def visited_check(urlToCheck):
  883. try: saved_visits = cache.get('visited_')
  884. except: return False
  885. erNoFavs='XBMC.Notification([B][COLOR orange]Favorites[/COLOR][/B],[B]You have no favorites saved.[/B],5000,"")'
  886. if not saved_visits: return False #xbmc.executebuiltin(erNoFavs)
  887. if saved_visits == '[]': return False #xbmc.executebuiltin(erNoFavs)
  888. if saved_visits:
  889. visits = eval(saved_visits)
  890. if (urlToCheck in visits): return True
  891. return False
  892. def visited_empty():
  893. saved_favs = cache.get('visited_')
  894. favs = []
  895. cache.set('visited_', str(favs))
  896. notification('[B][COLOR orange]Visited[/COLOR][/B]','[B] Your Visited Data has been wiped clean. Bye Bye.[/B]')
  897. def visited_add(urlToAdd):
  898. if (urlToAdd==''): return ''
  899. elif (urlToAdd==None): return ''
  900. if (debugging==True): print 'checking rather url has been visited: ' + urlToAdd
  901. saved_visits = cache.get('visited_')
  902. visits = []
  903. if saved_visits:
  904. #if (debugging==True): print 'saved visits: ',saved_visits
  905. visits = eval(saved_visits)
  906. if visits:
  907. if (urlToAdd) in visits: return
  908. visits.append((urlToAdd))
  909. cache.set('visited_', str(visits))
  910. def qp_get(n): ## Deals with errors in using None type within a urllib.quote_plus().
  911. #print n
  912. if (n==''): return ''
  913. elif (n==None): return ''
  914. else: return urllib.quote_plus(n)
  915. def st_get(n): ## Deals with errors in using None type within a str().
  916. #print n
  917. if (n==None): return ''
  918. else: return str(n)
  919. def page_last_get(defaultLastPage=sys.argv[0]+'?mode=0'):
  920. try: last_visited = cache.get('lastpage')
  921. except: return defaultLastPage
  922. erNoFavs='XBMC.Notification([B][COLOR orange]Favorites[/COLOR][/B],[B]You have no favorites saved.[/B],5000,"")'
  923. if not last_visited: return defaultLastPage
  924. if last_visited == '[]': return defaultLastPage
  925. if last_visited == '': return defaultLastPage
  926. if last_visited:
  927. return eval(last_visited)
  928. return defaultLastPage
  929. def page_last_update(defaultLastPage=sys.argv[0]+sys.argv[2]):
  930. cache.set('lastpage', defaultLastPage)
  931. def format_eta(seconds):
  932. minutes, seconds = divmod(seconds, 60)
  933. if minutes > 60:
  934. hours, minutes = divmod(minutes, 60)
  935. return "ETA: %02d:%02d:%02d " % (hours, minutes, seconds)
  936. else:
  937. return "ETA: %02d:%02d " % (minutes, seconds)
  938. def format_time(seconds):
  939. minutes, seconds = divmod(seconds, 60)
  940. if minutes > 60:
  941. hours, minutes = divmod(minutes, 60)
  942. return "%02d:%02d:%02d" % (hours, minutes, seconds)
  943. else:
  944. return "%02d:%02d" % (minutes, seconds)
  945. ### ############################################################################################################
  946. ### ############################################################################################################
  947. class TextBox_FromFile:
  948. # constants
  949. WINDOW = 10147
  950. CONTROL_LABEL = 1
  951. CONTROL_TEXTBOX = 5
  952. def __init__(self, *args, **kwargs):
  953. xbmc.executebuiltin("ActivateWindow(%d)" % ( self.WINDOW, )) # activate the text viewer window
  954. self.win = xbmcgui.Window(self.WINDOW) # get window
  955. xbmc.sleep(1000) # give window time to initialize
  956. self.setControls()
  957. def setControls(self,txtFilepath=__home__,txtFilename='changelog.txt'):
  958. HeaderMsg = "%s - ( v%s )" % (__plugin__,addon.get_version()) # set heading
  959. self.win.getControl(self.CONTROL_LABEL).setLabel(HeaderMsg)
  960. #root = addon.get_path() # set text
  961. txt_path = os.path.join(txtFilepath,txtFilename)
  962. #txt_path = os.path.join(__home__, 'news.txt')
  963. f = open(txt_path)
  964. text = f.read()
  965. self.win.getControl(self.CONTROL_TEXTBOX).setText(text)
  966. ### ############################################################################################################
  967. class TextBox_FromUrl: ## Usage Example: TextBox_FromUrl().load('https://raw.github.com/HIGHWAY99/plugin.video.theanimehighway/master/README.md')
  968. WINDOW = 10147
  969. CONTROL_LABEL = 1
  970. CONTROL_TEXTBOX = 5
  971. HEADER_MESSAGE = "%s - ( v%s )" % (__plugin__,addon.get_version()) # set heading
  972. def load(self, URL_PATH, HEADER_MESSAGE2=''):
  973. if (HEADER_MESSAGE2==''): HEADER_MESSAGE2=self.HEADER_MESSAGE
  974. print 'text window from url: ',URL_PATH #self.URL_PATH
  975. try: text=getURL(URL_PATH)#(self.URL_PATH)
  976. except: text=''
  977. xbmc.executebuiltin("ActivateWindow(%d)" % ( self.WINDOW, )) # activate the text viewer window
  978. self.win = xbmcgui.Window(self.WINDOW) # get window
  979. xbmc.sleep(500) # give window time to initialize
  980. self.win.getControl(self.CONTROL_LABEL).setLabel(HEADER_MESSAGE2)
  981. self.win.getControl(self.CONTROL_TEXTBOX).setText(text)
  982. ### ############################################################################################################
  983. class TextBox2: ## Usage Example: TextBox_FromUrl().load('https://raw.github.com/HIGHWAY99/plugin.video.theanimehighway/master/README.md')
  984. WINDOW = 10147
  985. CONTROL_LABEL = 1
  986. CONTROL_TEXTBOX = 5
  987. HEADER_MESSAGE = "%s - ( v%s )" % (__plugin__,addon.get_version()) # set heading
  988. def load_url(self, URL_PATH, HEADER_MESSAGE2=''):
  989. if (debugging==True): print 'text window from url: ',URL_PATH #self.URL_PATH
  990. try: text=getURL(URL_PATH)#(self.URL_PATH)
  991. except: text=''
  992. self.load_window()
  993. self.set_header(HEADER_MESSAGE2)
  994. self.set_text(text)
  995. def load_file(self, FILE_NAME='changelog.txt', HEADER_MESSAGE2='', FILE_PATH=__home__):
  996. txt_path = os.path.join(FILE_PATH,FILE_NAME)
  997. if (debugging==True): print 'text window from file: ',txt_path
  998. f = open(txt_path)
  999. text = f.read()
  1000. self.load_window()
  1001. self.set_header(HEADER_MESSAGE2)
  1002. self.set_text(text)
  1003. def load_string(self, text_string='', HEADER_MESSAGE2=''):
  1004. self.load_window()
  1005. self.set_header(HEADER_MESSAGE2)
  1006. self.set_text(text_string)
  1007. def load_window(self, sleeptime=500):
  1008. xbmc.executebuiltin("ActivateWindow(%d)" % ( self.WINDOW, )) # activate the text viewer window
  1009. self.win = xbmcgui.Window(self.WINDOW) # get window
  1010. xbmc.sleep(sleeptime) # give window time to initialize
  1011. def set_header(self, HEADER_MESSAGE2=''):
  1012. if (HEADER_MESSAGE2==''): HEADER_MESSAGE2=self.HEADER_MESSAGE
  1013. self.win.getControl(self.CONTROL_LABEL).setLabel(HEADER_MESSAGE2)
  1014. def set_text(self, text=''):
  1015. self.win.getControl(self.CONTROL_TEXTBOX).setText(text)
  1016. ### ############################################################################################################
  1017. ### ############################################################################################################
  1018. class class_itmOBJ(object): ## Thx to those of plugin.video.SportsDevil.
  1019. def __init__(self):
  1020. self.infos_names = []
  1021. self.infos_values = []
  1022. def __getitem__(self, key, type1=1):
  1023. #return self.getInfo_str(key)
  1024. if (type1==1): return self.getInfo_str(key)
  1025. if (type1==2): return self.getInfo_int(key)
  1026. if (type1==3): return self.getInfo_b(key)
  1027. else: return self.getInfo(key)
  1028. def __setitem__(self, key, value):
  1029. self.setInfo(key, value)
  1030. def reset(self):
  1031. self.infos_names = []
  1032. self.infos_values = []
  1033. def setInfo(self, key, value):
  1034. if key in self.infos_names:
  1035. self.infos_values[self.infos_names.index(key)] = value
  1036. else:
  1037. self.infos_names.append(key)
  1038. self.infos_values.append(value)
  1039. #if (debugging==True): print 'value: ',value
  1040. #if (debugging==True): print 'key: '+key
  1041. #if (debugging==True): print 'value set: ',self.infos_values[self.infos_names.index(key)]
  1042. ##if (debugging==True): notification('value',value)
  1043. def getInfo(self, key):
  1044. if (debugging==True): print self.infos_names
  1045. if (debugging==True): print self.infos_values
  1046. if self.infos_names.__contains__(key):
  1047. return self.infos_values[self.infos_names.index(key)]
  1048. return None
  1049. def getInfo_str(self, key):
  1050. if self.infos_names.__contains__(key):
  1051. return self.infos_values[self.infos_names.index(key)]
  1052. return ''
  1053. def getInfo_int(self, key):
  1054. if self.infos_names.__contains__(key):
  1055. return self.infos_values[self.infos_names.index(key)]
  1056. return 0
  1057. def getInfo_b(self, key):
  1058. if self.infos_names.__contains__(key):
  1059. return self.infos_values[self.infos_names.index(key)]
  1060. return False
  1061. def merge(self, item):
  1062. for info_name in item.infos_names:
  1063. if not self[info_name]:
  1064. self[info_name] = item[info_name]
  1065. def __str__(self):
  1066. txt = ''
  1067. for info_name in self.infos_names:
  1068. txt += string.ljust(info_name,15) +':\t' + self[info_name] + '\n'
  1069. return txt
  1070. ### ############################################################################################################
  1071. class class_MyMenu(object):
  1072. def eod(self): ##
  1073. xbmcplugin.endOfDirectory(int(sys.argv[1]))
  1074. def refresh(self): ## To Refresh the Menu.
  1075. xbmc.executebuiltin("XBMC.Container.Refresh")
  1076. def get_u(self,iOBJ): ## To make the plugin URL.
  1077. u=sys.argv[0]
  1078. u+="?url="+urllib.quote_plus(iOBJ['url'])
  1079. u+="&mode="+str(iOBJ['mode'])
  1080. u+="&name="+urllib.quote_plus(iOBJ['name'])
  1081. u+="&nm="+urllib.quote_plus(iOBJ['name2'])
  1082. u+="&tp="+str(iOBJ['type2'])
  1083. u+="&scr="+urllib.quote_plus(iOBJ['image_thumbnail'])
  1084. u+="&fan="+urllib.quote_plus(iOBJ['image_fanart'])
  1085. u+="&show="+urllib.quote_plus(iOBJ['show'])
  1086. u+="&cat="+urllib.quote_plus(iOBJ['category'])
  1087. return u
  1088. def addDir_MI(self,iOBJ): ## For Folders - Menu Items
  1089. #if (debugging==True): print iOBJ
  1090. if (debugging==True): print 'addDir_MI -- label_title: '+iOBJ['label_title']
  1091. ok=True; u=self.get_u(iOBJ)
  1092. if (debugging==True): print 'addDir_MI -- u: '+u
  1093. liz=xbmcgui.ListItem(iOBJ['name'], iconImage="DefaultFolder.png", thumbnailImage=iOBJ['image_thumbnail'])
  1094. liz.setInfo( type="Video", infoLabels={ "Title": iOBJ['label_title'] } )
  1095. liz.setProperty( "Fanart_Image", iOBJ['image_fanart'] )
  1096. ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=iOBJ['isFolder'])
  1097. return ok
  1098. def addDir_FC(self,iOBJ): ## For Folders - Menu Items with %Fav= for special over-ride commands.
  1099. ok=True; u=self.get_u(iOBJ)
  1100. u+='&fav='+iOBJ['favcmd']
  1101. if (debugging==True): print 'addDir_FC -- u: '+u
  1102. liz=xbmcgui.ListItem(iOBJ['name'], iconImage="DefaultFolder.png", thumbnailImage=iOBJ['image_thumbnail'])
  1103. liz.setInfo( type="Video", infoLabels={ "Title": iOBJ['label_title'] } )
  1104. liz.setProperty( "Fanart_Image", iOBJ['image_fanart'] )
  1105. ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=iOBJ['isFolder'])
  1106. return ok
  1107. def addDir_LA(self,iOBJ): ## Label Text
  1108. ok=True; u=self.get_u(iOBJ)
  1109. if (debugging==True): print 'addDir_LA -- u: '+u
  1110. liz=xbmcgui.ListItem(iOBJ['name'], iconImage="DefaultFolder.png", thumbnailImage=iOBJ['image_thumbnail'])
  1111. liz.setInfo( type="Video", infoLabels={ "Title": iOBJ['label_title'] } )
  1112. liz.setProperty( "Fanart_Image", iOBJ['image_fanart'] )
  1113. ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=iOBJ['isFolder'])
  1114. return ok
  1115. def addDir_CM1(self,iOBJ): ## For ??
  1116. ok=True; u=self.get_u(iOBJ)
  1117. if (debugging==True): print 'addDir_CM1 -- u: '+u
  1118. liz=xbmcgui.ListItem(iOBJ['name'], iconImage="DefaultFolder.png", thumbnailImage=iOBJ['image_thumbnail'])
  1119. liz.setInfo( type="Video", infoLabels={ "Title": iOBJ['label_title'] } )
  1120. liz.setProperty( "Fanart_Image", iOBJ['image_fanart'] )
  1121. contextMenuItems = []
  1122. if __settings__.getSetting("enable-showurl") == "true":
  1123. contextMenuItems.append(('[B][COLOR orange]Show[/COLOR][/B] ~ [B]URL[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],iOBJ['mode'] , urllib.quote_plus(iOBJ['name']), urllib.quote_plus(iOBJ['name']), 877, 'showurl', urllib.quote_plus(iOBJ['url']), urllib.quote_plus(iOBJ['image_thumbnail']), urllib.quote_plus(iOBJ['image_fanart']))))
  1124. liz.addContextMenuItems(contextMenuItems, replaceItems=True)
  1125. ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=iOBJ['isFolder']) ## is_folder=False
  1126. return ok
  1127. def addDir_CM2(self,iOBJ,Labels='none'): ## For Folder - Used for show listings.
  1128. if Labels=='none': Labels={ "Title" : iOBJ['label_title'] }
  1129. #Labels=self.get_L(iOBJ,Labels)
  1130. ok=True; u=self.get_u(iOBJ)
  1131. if (debugging==True): print 'addDir_CM2 -- u: '+u
  1132. vc_tag=visited_DoCheck(u)
  1133. if (debugging==True): print vc_tag
  1134. liz=xbmcgui.ListItem(vc_tag+iOBJ['name'], iconImage="DefaultFolder.png", thumbnailImage=iOBJ['image_thumbnail'])
  1135. liz.setInfo( type="Video", infoLabels=Labels )
  1136. liz.setProperty( "Fanart_Image", iOBJ['image_fanart'] )
  1137. contextMenuItems = []
  1138. sysname = urllib.quote_plus(iOBJ['name'])
  1139. sysurl = urllib.quote_plus(iOBJ['url'])
  1140. sysscr = urllib.quote_plus(iOBJ['image_thumbnail'])
  1141. sysfan = urllib.quote_plus(iOBJ['image_fanart'])
  1142. if (debugging==True): print getsetbool('enable-showurl')
  1143. if __settings__.getSetting("enable-showurl") == "true":#doesn't work for some odd reason >> #if getsetbool('enable-showurl') == 'true':#
  1144. contextMenuItems.append(('[B][COLOR orange]Show[/COLOR][/B] ~ [B]URL[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(iOBJ['name2']), type2, 'showurl', sysurl, sysscr, sysfan)))
  1145. contextMenuItems.append(('[B][COLOR green]ADD[/COLOR][/B] ~ [B][COLOR tan]Favorite[/COLOR][/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s&show=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(iOBJ['name2']), type2, 'add', sysurl, sysscr, sysfan,urllib.quote_plus(iOBJ['name2']))))
  1146. contextMenuItems.append(('[B][COLOR red]REMOVE[/COLOR][/B] ~ [B][COLOR tan]Favorite[/COLOR][/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s&show=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(iOBJ['name2']), type2, 'rem', sysurl, sysscr, sysfan,urllib.quote_plus(iOBJ['name2']))))
  1147. contextMenuItems.append(('Show Information', 'XBMC.Action(Info)'))
  1148. contextMenuItems.append(('[B][COLOR orange]Metadata[/COLOR][/B] ~ Show Name', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(iOBJ['name2']), type2, 'metachangeshowname', sysurl, sysscr, sysfan)))
  1149. #contextMenuItems.append(('[B][COLOR orange]Test[/COLOR][/B] ~ [B]Test[/B]',"notification(%s,%s)" % (sysname,sysurl)))
  1150. if (debugging==True): print getset('enable-clearfavorites')
  1151. if __settings__.getSetting("enable-clearfavorites") == "true":#if getset('enable-clearfavorites')==True:
  1152. contextMenuItems.append(('[B][COLOR yellow]Clear[/COLOR][/B] ~ [B][COLOR tan]Favorites[/COLOR][/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],mode , sysname, urllib.quote_plus(iOBJ['name2']), type2, 'clr', sysurl, sysscr, sysfan)))
  1153. liz.addContextMenuItems(contextMenuItems, replaceItems=True)
  1154. if iOBJ['doSorting']==True: ## doSorting=False by default
  1155. xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_TITLE)
  1156. ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz,isFolder=iOBJ['isFolder']) ## is_folder=True
  1157. return ok
  1158. def addLink_(self, iOBJ, downloadable=True): ## For Video Links.
  1159. ok=True; u=self.get_u(iOBJ)
  1160. if (debugging==True): print u
  1161. liz=xbmcgui.ListItem(iOBJ['name'], iconImage="DefaultFolder.png", thumbnailImage=iOBJ['image_thumbnail'])
  1162. if (' - [COLOR grey]' in iOBJ['label_studio']): iOBJ['label_studio']=iOBJ['label_studio'].split(' - [COLOR grey]')[0]
  1163. if (' [COLOR grey]- ' in iOBJ['label_studio']): iOBJ['label_studio']=iOBJ['label_studio'].split(' [COLOR grey]- ')[0]
  1164. if ('[COLOR grey] - ' in iOBJ['label_studio']): iOBJ['label_studio']=iOBJ['label_studio'].split('[COLOR grey] - ')[0]
  1165. if (' - [COLOR' in iOBJ['label_studio']): iOBJ['label_studio']=iOBJ['label_studio'].split(' - [COLOR')[0]
  1166. if (' [COLOR lime](English Dubbed)[/COLOR]' in iOBJ['label_title']):
  1167. iOBJ['label_studio']=iOBJ['label_studio']+' [COLOR lime](English Dubbed)[/COLOR]'
  1168. iOBJ['label_title'] =iOBJ['label_title'].replace(' [COLOR lime](English Dubbed)[/COLOR]','')
  1169. elif ('English Dubbed' in iOBJ['label_title']): iOBJ['label_studio']=iOBJ['label_studio']+' [COLOR lime](English Dubbed)[/COLOR]'
  1170. elif ('Eng Dubbed' in iOBJ['label_title']): iOBJ['label_studio']=iOBJ['label_studio']+' [COLOR lime](English Dubbed)[/COLOR]'
  1171. elif ('Dubbed' in iOBJ['label_title']): iOBJ['label_studio']=iOBJ['label_studio']+' [COLOR lime](Dubbed)[/COLOR]'
  1172. elif ('English Subbed' in iOBJ['label_title']): iOBJ['label_studio']=iOBJ['label_studio']+' [COLOR lime](English Subbed)[/COLOR]'
  1173. elif ('Eng Subbed' in iOBJ['label_title']): iOBJ['label_studio']=iOBJ['label_studio']+' [COLOR lime](English Subbed)[/COLOR]'
  1174. elif ('Subbed' in iOBJ['label_title']): iOBJ['label_studio']=iOBJ['label_studio']+' [COLOR lime](Subbed)[/COLOR]'
  1175. liz.setInfo( type="Video", infoLabels={ "Title": iOBJ['label_title'], "Studio": iOBJ['label_studio'] } )
  1176. liz.setProperty( "Fanart_Image", iOBJ['image_fanart'] )
  1177. if (debugging==True): print getset('enable-showurl')
  1178. if (getsetbool_('enable-showurl')==True):
  1179. contextMenuItems.append(('[B][COLOR orange]Show[/COLOR][/B] ~ [B]URL[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],0 , urllib.quote_plus(iOBJ['show']), urllib.quote_plus(iOBJ['show']), 0, 'showurl', urllib.quote_plus(iOBJ['url']), iOBJ['image_thumbnail'], iOBJ['image_fanart'])))
  1180. if (getsetbool_('enable-downloading') == True) and (downloadable==True):
  1181. if ('novamov.com' not in iOBJ['url']) and ('videoweed.es' not in iOBJ['url']) and ('dailymotion.com' not in iOBJ['url']):
  1182. contextMenuItems.append(('[B][COLOR purple]Download[/COLOR][/B] ~ [B]File[/B]', 'XBMC.RunPlugin(%s?mode=%s&name=%s&nm=%s&tp=%s&fav=%s&url=%s&scr=%s&fan=%s)' % (sys.argv[0],0 , urllib.quote_plus(iOBJ['show']), urllib.quote_plus(iOBJ['show']), 0, 'download', urllib.quote_plus(iOBJ['url']), iOBJ['image_thumbnail'], iOBJ['image_fanart'])))
  1183. liz.addContextMenuItems(contextMenuItems, replaceItems=True)
  1184. if iOBJ['doSorting']==True:
  1185. xbmcplugin.addSortMethod(int(sys.argv[1]), xbmcplugin.SORT_METHOD_TITLE)
  1186. ok=xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=u,listitem=liz) ## is_folder=True
  1187. return ok
  1188. ### ############################################################################################################
  1189. ### ############################################################################################################
  1190. def getparambool_(idSetting):
  1191. try: o=params[idSetting]
  1192. except: o=None
  1193. if (o==True) or (o=='True') or (o=='true') or (o=='TRUE'): return True
  1194. else: return False
  1195. def getparamstr_(idSetting):
  1196. try: o=params[idSetting]
  1197. except: o=None
  1198. if (o==None): return ''
  1199. else: return o
  1200. def getparamint_(idSetting):
  1201. try: o=params[idSetting]
  1202. except: o=None
  1203. if (o==None): return 0
  1204. else: return o
  1205. ### ############################################################################################################
  1206. def make_item_fill_it( _name='', _isFolder=False, _mode=0, _type2=0, _category='Unknown', _image_thumbnail=ICON0, _image_fanart=fanart0, _url='', _name2='', _label_title='' ):
  1207. if (_name2==''): _name2=_name
  1208. if (_label_title==''): _label_title=_name
  1209. cio=class_itmOBJ()
  1210. if (_name==''): return cio
  1211. cio['url']=_url
  1212. cio['category']=getparamstr_('cat')+' ::: '+_category
  1213. cio['type2']=_type2
  1214. cio['mode']=_mode
  1215. cio['name']=_name
  1216. cio['name2']=_name2
  1217. cio['label_title']=_label_title
  1218. cio['image_thumbnail']=_image_thumbnail
  1219. cio['image_fanart']=_image_fanart
  1220. cio['isFolder']=_isFolder
  1221. return cio
  1222. def make_item( _name='', _isFolder=False, _mode=0, _type2=0, _category='Unknown', _image_thumbnail=ICON0, _image_fanart=fanart0, _url='', _name2='', _label_title='' ):
  1223. cio=make_item_fill_it( _name, _isFolder, _mode, _type2, _category, _image_thumbnail, _image_fanart, _url, _name2, _label_title )
  1224. MyMenu.addDir_MI(cio)
  1225. return cio
  1226. def make_item_cmd( _favcmd='', _name='', _isFolder=False, _mode=0, _type2=0, _category='Unknown', _image_thumbnail=ICON0, _image_fanart=fanart0, _url='', _name2='', _label_title='' ):
  1227. cio=make_item_fill_it( _name, _isFolder, _mode, _type2, _category, _image_thumbnail, _image_fanart, _url, _name2, _label_title )
  1228. cio['favcmd']=_favcmd
  1229. MyMenu.addDir_FC(cio)
  1230. return cio
  1231. def make_item_show( cio ): # _name='', _isFolder=False, _mode=0, _type2=0, _category='Unknown', _image_thumbnail=ICON0, _image_fanart=fanart0, _url='', _name2='', _label_title='' ):
  1232. #cio=make_item_fill_it( _name, _isFolder, _mode, _type2, _category, _image_thumbnail, _image_fanart, _url, _name2, _label_title )
  1233. #cio['Plot']=_
  1234. #cio['Rating']=_
  1235. #cio['Date_Added']=_
  1236. #cio['Date_Released']=_
  1237. #cio['Genres']=_
  1238. #cio['Themes']=_
  1239. #cio['_image_banner']=_
  1240. #cio['Date_Aired']=_
  1241. #cio['']=_
  1242. #cio['']=_
  1243. #cio['']=_
  1244. #cio['']=_
  1245. #cio['']=_
  1246. cio['isFolder']=True
  1247. Labels={ 'Title':cio['label_title'],'Plot':cio['Plot'],'Year':cio['Year'],'Status':cio['Status'],'Rating':cio['Rating'], 'ShowID':cio['id_show'],'Votes':cio['Votes'],'Type':cio['Type'], 'Fanart':cio['image_fanart'], 'Poster':cio['image_thumbnail'], 'Banner':cio['image_banner'], 'Language':cio['Language'], 'Network':cio['Network'], 'Genre':cio['Genres'] }
  1248. #
  1249. #
  1250. #
  1251. MyMenu.addDir_CM2(cio,Labels)
  1252. return cio
  1253. ### ############################################################################################################
  1254. ### ############################################################################################################
  1255. def get_xbmc_os():
  1256. try: xbmc_os = os.environ.get('OS')
  1257. except: xbmc_os = "unknown"
  1258. return xbmc_os
  1259. def get_xbmc_version():
  1260. rev_re = re.compile('r(\d+)')
  1261. try: xbmc_version = xbmc.getInfoLabel('System.BuildVersion')
  1262. except: xbmc_version = 'Unknown'
  1263. return xbmc_version
  1264. def get_xbmc_revision():
  1265. rev_re = re.compile('r(\d+)')
  1266. try: xbmc_version = xbmc.getInfoLabel('System.BuildVersion')
  1267. except: xbmc_version = 'Unknown'
  1268. try:
  1269. xbmc_rev = int(rev_re.search(xbmc_version).group(1))
  1270. print "addoncompat.py: XBMC Revision: %s" % xbmc_rev
  1271. except:
  1272. print "addoncompat.py: XBMC Revision not available - Version String: %s" % xbmc_version
  1273. xbmc_rev = 0
  1274. return xbmc_rev
  1275. def _SaveFile(path, data):
  1276. file = open(path,'w')
  1277. file.write(data)
  1278. file.close()
  1279. def _OpenFile(path):
  1280. if os.path.isfile(path): ## File found.
  1281. file = open(path, 'r')
  1282. contents=file.read()
  1283. file.close()
  1284. return contents
  1285. else: return '' ## File not found.
  1286. def _CreateDirectory(dir_path):
  1287. dir_path = dir_path.strip()
  1288. if not os.path.exists(dir_path): os.makedirs(dir_path)
  1289. def _get_dir(mypath, dirname): #...creates sub-directories if they are not found.
  1290. subpath = os.path.join(mypath, dirname)
  1291. if not os.path.exists(subpath): os.makedirs(subpath)
  1292. return subpath
  1293. #def _cleanfilename(name):
  1294. # valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
  1295. # return ''.join(c for c in name if c in valid_chars)
  1296. #def _cleanFilename(name):
  1297. # valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
  1298. # return ''.join(c for c in name if c in valid_chars)
  1299. def _time2ms(time):
  1300. hour,minute,seconds = time.split(';')[0].split(':')
  1301. frame = int((float(time.split(';')[1])/24)*1000)
  1302. milliseconds = (((int(hour)*60*60)+(int(minute)*60)+int(seconds))*1000)+frame
  1303. return milliseconds
  1304. def _convert_time(milliseconds):
  1305. seconds = int(float(milliseconds)/1000)
  1306. milliseconds -= (seconds*1000)
  1307. hours = seconds / 3600
  1308. seconds -= 3600*hours
  1309. minutes = seconds / 60
  1310. seconds -= 60*minutes
  1311. return "%02d:%02d:%02d,%3d" % (hours, minutes, seconds, milliseconds)
  1312. def check_url_v(_url):
  1313. rs=0
  1314. try:
  1315. r = requests.head(_url)
  1316. #if (debugging==True): print str(r.status_code)
  1317. rs=r.status_code
  1318. except: t=''
  1319. if (rs==404) or (rs=='') or (rs==None): return False
  1320. elif (rs==200) or (rs==302): return True
  1321. else: return False
  1322. ### >>> url = 'http://hup.hu'
  1323. ### >>> r = requests.head(url)
  1324. ### >>> r.status_code
  1325. ### 200 # requests.codes.OK
  1326. ### >>> url = 'http://www.google.com'
  1327. ### >>> r = requests.head(url)
  1328. ### >>> r.status_code
  1329. ### 302 # requests.codes.FOUND
  1330. ### >>> url = 'http://simile.mit.edu/crowbar/nothing_here.html'
  1331. ### >>> r = requests.head(url)
  1332. ### >>> r.status_code
  1333. ### 404 # requests.codes.NOT_FOUND
  1334. def thetvdb_com_episodes3(show_id,season):
  1335. if (debugging==True): print 'thetvdb.com show ID: '+show_id
  1336. link=getURL('http://www.thetvdb.com/?tab=seasonall&id='+show_id)
  1337. print 'thetvdb_com_episodes: '+'http://www.thetvdb.com/?tab=seasonall&id='+show_id
  1338. itable=(link.split('<table width="100%" border="0" cellspacing="0" cellpadding="2" align="center" id="listtable">')[1]).split('</table>')[0]
  1339. if (season=='') or (season.lower()=='all'): iresults=re.compile('<tr><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)-(.+?)-(.+?)</td>(.+?)</tr>').findall(itable)
  1340. else: iresults=re.compile('<tr><td class=".+?"><a href="(.+?)">(['+season+'][\s][x][\s]\d+)</a></td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)-(.+?)-(.+?)</td>(.+?)</tr>').findall(itable)
  1341. ### <tr><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">1 x 2</a></td><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">The Kidnapping of a Company President's Daughter Case</a></td><td class="even">1996-01-15</td><td class="even"><img src="/images/checkmark.png" width=10 height=10> &nbsp;</td></tr>
  1342. #return iresults
  1343. return sorted(iresults, key=lambda item: item[1], reverse=True)
  1344. def thetvdb_com_episodes2(show_id):
  1345. if (debugging==True): print 'thetvdb.com show ID: '+show_id
  1346. link=getURL('http://www.thetvdb.com/?tab=seasonall&id='+show_id)
  1347. print 'thetvdb_com_episodes: '+'http://www.thetvdb.com/?tab=seasonall&id='+show_id
  1348. itable=(link.split('<table width="100%" border="0" cellspacing="0" cellpadding="2" align="center" id="listtable">')[1]).split('</table>')[0]
  1349. iresults=re.compile('<tr><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)-(.+?)-(.+?)</td>(.+?)</tr>').findall(itable)
  1350. ### <tr><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">1 x 2</a></td><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">The Kidnapping of a Company President's Daughter Case</a></td><td class="even">1996-01-15</td><td class="even"><img src="/images/checkmark.png" width=10 height=10> &nbsp;</td></tr>
  1351. return iresults
  1352. def thetvdb_com_episodes(show_id):
  1353. if (debugging==True): print 'thetvdb.com show ID: '+show_id
  1354. link=getURL('http://www.thetvdb.com/?tab=seasonall&id='+show_id)
  1355. itable=(link.split('<table width="100%" border="0" cellspacing="0" cellpadding="2" align="center" id="listtable">')[1]).split('</table>')[0]
  1356. iresults=re.compile('<tr><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)-(.+?)-(.+?)</td><td class=".+?">(<img src=".+?" width=10 height=10>)* &nbsp;</td></tr>', re.IGNORECASE | re.DOTALL).findall(itable)
  1357. #iresults=re.compile('<tr><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)-(.+?)-(.+?)</td><td class=".+?"><img src="(.+?)" width=.+? height=.+?>.+?</td></tr>', re.IGNORECASE | re.DOTALL).findall(itable)
  1358. ### <tr><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">1 x 2</a></td><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">The Kidnapping of a Company President's Daughter Case</a></td><td class="even">1996-01-15</td><td class="even"><img src="/images/checkmark.png" width=10 height=10> &nbsp;</td></tr>
  1359. #print iresults
  1360. return iresults
  1361. #
  1362. #
  1363. #
  1364. def thetvdb_com_episodes1(show_id):
  1365. if (debugging==True): print 'thetvdb.com show ID: '+show_id
  1366. link=getURL('http://www.thetvdb.com/?tab=seasonall&id='+show_id)
  1367. print 'thetvdb_com_episodes: '+'http://www.thetvdb.com/?tab=seasonall&id='+show_id
  1368. itable=(link.split('<table width="100%" border="0" cellspacing="0" cellpadding="2" align="center" id="listtable">')[1]).split('</table>')[0]
  1369. iresults=re.compile('<tr><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)-(.+?)-(.+?)</td><td class=".+?"><img src="(.+?)" width=.+? height=.+?>.+?</td></tr>').findall(itable)
  1370. ### <tr><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">1 x 2</a></td><td class="even"><a href="/?tab=episode&seriesid=72454&seasonid=4166&id=86048&amp;lid=7">The Kidnapping of a Company President's Daughter Case</a></td><td class="even">1996-01-15</td><td class="even"><img src="/images/checkmark.png" width=10 height=10> &nbsp;</td></tr>
  1371. return iresults
  1372. #
  1373. #
  1374. #
  1375. def Episode__get_S_Ep_No(episode_title):
  1376. season_number=''; episode_number=''
  1377. if (' Season ' in episode_title): season_number=(re.compile(' Season (\d+) ').findall(episode_title+' ')[0]).strip()
  1378. elif (' season ' in episode_title): season_number=(re.compile(' season (\d+) ').findall(episode_title+' ')[0]).strip()
  1379. elif (' s ' in episode_title): season_number=(re.compile(' s (\d+) ').findall(episode_title+' ')[0]).strip()
  1380. elif (' S ' in episode_title): season_number=(re.compile(' S (\d+) ').findall(episode_title+' ')[0]).strip()
  1381. else: season_number='1'
  1382. if (' Episode ' in episode_title): episode_number=(re.compile(' Episode (\d+) ').findall(episode_title+' ')[0]).strip()
  1383. elif (' episode ' in episode_title): episode_number=(re.compile(' episode (\d+) ').findall(episode_title+' ')[0]).strip()
  1384. elif (' ep ' in episode_title): episode_number=(re.compile(' ep (\d+) ').findall(episode_title+' ')[0]).strip()
  1385. elif (' Ep ' in episode_title): episode_number=(re.compile(' Ep (\d+) ').findall(episode_title+' ')[0]).strip()
  1386. elif (' EP ' in episode_title): episode_number=(re.compile(' EP (\d+) ').findall(episode_title+' ')[0]).strip()
  1387. elif (' e ' in episode_title): episode_number=(re.compile(' e (\d+) ').findall(episode_title+' ')[0]).strip()
  1388. elif (' E ' in episode_title): episode_number=(re.compile(' E (\d+) ').findall(episode_title+' ')[0]).strip()
  1389. else: episode_number=''
  1390. return (season_number,episode_number)
  1391. def Episode__get_thumb(the_url,show_img):
  1392. deb('the_url',the_url)
  1393. if ('/?tab=episode&' in the_url) and ('&seriesid=' in the_url) and ('&id=' in the_url):
  1394. id_series=(re.compile('&seriesid=(\d+)&').findall(the_url+'&')[0]).strip()
  1395. id_episode=(re.compile('&id=(\d+)&').findall(the_url+'&')[0]).strip()
  1396. episode_thumbnail='http://www.thetvdb.com/banners/episodes/'+id_series+'/'+id_episode+'.jpg'
  1397. deb('Episode__get_thumb','| '+id_series+' | '+id_episode+' | '+episode_thumbnail+' |')
  1398. else:
  1399. episode_thumbnail=show_img; id_series=''; id_episode=''
  1400. return (episode_thumbnail,id_series,id_episode)
  1401. def Episode__get_date(thetvdb_episode):
  1402. return (thetvdb_episode[4].strip()+'-'+thetvdb_episode[5].strip()+'-'+thetvdb_episode[6].strip(),thetvdb_episode[4].strip(),thetvdb_episode[5].strip(),thetvdb_episode[6].strip())
  1403. def thetvdb_com__show_search(show_name,show_id='none'):
  1404. default_return= None
  1405. #if (show_id=='none'):
  1406. if (debugging==True): print 'thetvdb.com show name: '+show_name
  1407. url_search='http://thetvdb.com/index.php?fieldlocation=2&language=7&genre=&year=&network=&zap2it_id=&tvcom_id=&imdb_id=&order=translation&addedBy=&searching=Search&tab=advancedsearch&seriesname='+urllib.quote_plus(show_name)
  1408. #else:
  1409. # if (debugging==True): print 'thetvdb.com show id: '+show_id
  1410. # url_search='http://thetvdb.com/index.php?fieldlocation=2&language=7&genre=&year=&network=&zap2it_id=&tvcom_id=&imdb_id=&order=translation&addedBy=&searching=Search&tab=advancedsearch&seriesname='+urllib.quote_plus(show_name)
  1411. if (debugging==True): print 'thetvdb.com search: '+url_search
  1412. link=getURL(url_search)
  1413. if (link=='none') or (link==''): return default_return
  1414. elif 'No Series found.' in link: return default_return
  1415. else:
  1416. try:
  1417. match=re.compile('<tr><td class=".+?">.+?</td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)</a></td><td class=".+?">(.+?)</td><td class=".+?">(.+?)</td><td class=".+?">.+?</td><td class=".+?">(.+?)</td><td class=".+?">.+?</td></tr>').findall(link)
  1418. return match
  1419. except:
  1420. try:
  1421. match=re.compile('<tr><td class=".+?">.+?</td><td class=".+?"><a href="(.+?)">(.+?)</a></td><td class=".+?">(.+?)</a></td><td class=".+?">(.+?)</td><td class=".+?">(.+?)</td><td class=".+?"></td><td class=".+?">(.+?)</td><td class=".+?">.+?</td></tr>').findall(link)
  1422. return match
  1423. except: return default_return
  1424. def thetvdb_com__show_select(show_name,show_id='none',getFirst=False):
  1425. default_return= None
  1426. rMatches=thetvdb_com__show_search(show_name) ### match_showurl,match_name,match_genres,match_status,match_language,match_network,match_rating
  1427. if (rMatches==None):
  1428. if (debugging==True): print 'thetvdb_com__show_select() >> thetvdb_com__show_search() >> [no resullts found.]'
  1429. if (shoDebugging==True): notification('Searching Shows for MetaData',show_name+': No Shows were found.')
  1430. return default_return
  1431. if (getFirst==True):
  1432. if (option_list==[]):
  1433. if (shoDebugging==True): notification('Searching Shows for MetaData',show_name+': No Results were found.')
  1434. return default_return
  1435. else: return rMatches[0]
  1436. else:
  1437. dialogSelect = xbmcgui.Dialog()
  1438. option_list = []
  1439. for rMatch in rMatches:
  1440. option_list.append(rMatch[1])
  1441. if (option_list==[]):
  1442. if (shoDebugging==True): notification('Searching Shows for MetaData',show_name+': No Results were found.')
  1443. return default_return
  1444. index=dialogSelect.select('Choose', option_list)
  1445. if (debugging==True): print 'choice selected: '+str(index)+'.) '+option_list[index]
  1446. if (shoDebugging==True): notification('choice selected: ',str(index)+'.) '+option_list[index])
  1447. return rMatches[index]
  1448. def metachange__Show_Name(show_name,show_id='none',getFirst=False):
  1449. rSelected=thetvdb_com__show_select(show_name,show_id,getFirst)
  1450. if (rSelected==None): return
  1451. def episode__AirDates(show_name,show_id='none',getFirst=False):
  1452. if (show_id=='none'):
  1453. rSelected=thetvdb_com__show_select(show_name,show_id,getFirst)
  1454. if (rSelected==None):
  1455. if (debugging==True): print 'AirDates >> rSelect==None'
  1456. return
  1457. if ('&id=' in rSelected[0]):
  1458. show_id=(re.compile('&id=(\d+)&').findall(rSelected[0]+'&')[0]).strip()
  1459. show_name=(rSelected[1]).strip()
  1460. elif (';id=' in rSelected[0]):
  1461. show_id=(re.compile(';id=(\d+)&').findall(rSelected[0]+'&')[0]).strip()
  1462. show_name=(rSelected[1]).strip()
  1463. else:
  1464. if (debugging==True): print 'AirDates >> no "&id=" found'
  1465. if (debugging==True): print rSelected[0]
  1466. return
  1467. rEpisodes=thetvdb_com_episodes(show_id) ## 'http://www.thetvdb.com/?tab=seasonall&id='+show_id ##
  1468. if (rEpisodes==[]):
  1469. if (debugging==True): print 'AirDates >> rEpisodes is empty'
  1470. return
  1471. rEpisodes=sorted(rEpisodes, key=lambda item: item[4]+item[5]+item[6], reverse=True)
  1472. dialogSelect = xbmcgui.Dialog(); option_list = []
  1473. for rMatch in rEpisodes:
  1474. dateColor='tan'
  1475. if (int(rMatch[4].strip()) > int(datetime.date.today().strftime("%Y"))) or (int(rMatch[4].strip())==int(datetime.date.today().strftime("%Y"))):
  1476. if (int(rMatch[5].strip()) > int(datetime.date.today().strftime("%m"))): dateColor='cornflowerblue'
  1477. elif (int(rMatch[5].strip()) > int(datetime.date.today().strftime("%m"))) or (int(rMatch[5].strip())==int(datetime.date.today().strftime("%m"))):
  1478. if (int(rMatch[6].strip())==int(datetime.date.today().strftime("%d"))) and (int(rMatch[5].strip())==int(datetime.date.today().strftime("%m"))) and (int(rMatch[4].strip())==int(datetime.date.today().strftime("%Y"))): dateColor='orange'
  1479. elif (int(rMatch[6].strip())==int(datetime.date.today().strftime("%d"))) or (int(rMatch[6].strip()) > int(datetime.date.today().strftime("%d"))): dateColor='cornflowerblue'
  1480. #datetime.date.today().strftime("%B %d, %Y")
  1481. option_list.append('[COLOR red][B]'+rMatch[1]+'[/B][/COLOR] [COLOR purple]([COLOR '+dateColor+']'+rMatch[4]+'[/COLOR]-[COLOR '+dateColor+']'+rMatch[5]+'[/COLOR]-[COLOR '+dateColor+']'+rMatch[6]+'[/COLOR])[/COLOR] [COLOR green][I]'+rMatch[3]+'[/I][/COLOR]')
  1482. if (option_list==[]):
  1483. if (debugging==True): print 'AirDates >> option_list is empty'
  1484. return ##if (shoDebugging==True): notification('Searching Shows for MetaData',show_name+': No Results were found.')
  1485. index=dialogSelect.select('Episodes: '+show_name, option_list)
  1486. #
  1487. #
  1488. def search_for_airdates(r=''):
  1489. if (r==None) or (r=='') or (r=='none') or (r==False): r=showkeyboard('','Search for Show:')
  1490. else: r=filename_filter_out_year(filename_filter_colorcodes(r))
  1491. if (r==False) or (r==None) or (r==''): return
  1492. rr=episode__AirDates(r)
  1493. def askSelection(option_list=[],txtHeader=''):
  1494. if (option_list==[]):
  1495. if (debugging==True): print 'askSelection() >> option_list is empty'
  1496. return None
  1497. dialogSelect = xbmcgui.Dialog();
  1498. index=dialogSelect.select(txtHeader, option_list)
  1499. #if (index== -1):
  1500. # return None
  1501. #if (index==False) or (index==None) or (index=='') or (index== -1):
  1502. # if (debugging==True): print 'askSelection() >> problem retreiving selected item'
  1503. # if (debugging==True): print index
  1504. # if (debugging==True): print str(index)
  1505. # return None
  1506. #else: return index
  1507. return index
  1508. def tfalse(r,d=False): ## Get True / False
  1509. if (r.lower()=='true' ): return True
  1510. elif (r.lower()=='false'): return False
  1511. else: return d
  1512. ## ### This is already in default.py for the plugin.video.solarmovie.so addon / plugin.
  1513. ##def cFL(t,c='white'): ### For Coloring Text ###
  1514. ## return '[COLOR '+c+']'+t+'[/COLOR]'
  1515. def iFL(t): ### For Italic Text ###
  1516. return '[I]'+t+'[/I]'
  1517. def bFL(t): ### For Bold Text ###
  1518. return '[B]'+t+'[/B]'
  1519. def _FL(t,c,e=''): ### For Custom Text Tags ###
  1520. if (e==''): d=''
  1521. else: d=' '+e
  1522. return '['+c.upper()+d+']'+t+'[/'+c.upper()+']'
  1523. def WhereAmI(t): ### for Writing Location Data to log file ###
  1524. if (_debugging==True): print 'Where am I: '+t
  1525. def deb(s,t): ### for Writing Debug Data to log file ###
  1526. if (_debugging==True): print s+': '+t
  1527. def debob(t): ### for Writing Debug Object to log file ###
  1528. if (_debugging==True): print t
  1529. def nolines(t):
  1530. it=t.splitlines()
  1531. t=''
  1532. for L in it:
  1533. t=t+L
  1534. t=((t.replace("\r","")).replace("\n",""))
  1535. return t
  1536. def checkImgUrl(img):
  1537. img=xbmc.translatePath(img)#; deb('Local Image',img)
  1538. if (check_ifUrl_isHTML(img)==True): return img
  1539. else: return ''
  1540. def checkImgLocal(img):
  1541. img=xbmc.translatePath(img)#; deb('Local Image',img)
  1542. if (os.path.isfile(img)): return img
  1543. else: return ''
  1544. ### ############################################################################################################
  1545. ### ############################################################################################################
  1546. def Library_SaveTo_Movies(url,iconimage,name,year):
  1547. library=xbmc.translatePath(_addon.get_profile())
  1548. foldername=xbmc.translatePath(os.path.join(library, 'Movies'))
  1549. if os.path.exists(foldername)==False: os.mkdir(os.path.join(library, 'Movies'))
  1550. strm='%s?mode=%s&section=%s&url=%s&iconimage=%s&title=%s&showtitle=%s&year=%s&showyear=%s'% (sys.argv[0],'PlayLibrary',ps('section.movie'),urllib.quote_plus(url),urllib.quote_plus(iconimage),urllib.quote_plus(name),urllib.quote_plus(name),year,year)
  1551. filename=name+' ('+year+')'
  1552. filename=clean_filename(filename+'.strm')
  1553. file =xbmc.translatePath(os.path.join(foldername,filename))
  1554. ##print file
  1555. a=open(file, "w"); a.write(strm); a.close()
  1556. myNote('Library Movie:',filename)
  1557. def Library_SaveTo_Episode(url,iconimage,name,year,country,season_number,episode_number,episode_title):
  1558. library=xbmc.translatePath(_addon.get_profile())
  1559. foldermain=xbmc.translatePath(os.path.join(library, 'TV'))
  1560. if os.path.exists(foldermain)==False: os.mkdir(foldermain)
  1561. foldername=xbmc.translatePath(os.path.join(foldermain,name+' ('+year+')'))
  1562. if os.path.exists(foldername)==False: os.mkdir(foldername)
  1563. folderseason=xbmc.translatePath(os.path.join(foldername, 'Season '+season_number))
  1564. if os.path.exists(folderseason)==False: os.mkdir(folderseason)
  1565. strm='%s?mode=%s&section=%s&url=%s&iconimage=%s&title=%s&showtitle=%s&year=%s&showyear=%s&country=%s&season=%s&episode=%s&episodetitle=%s'% (sys.argv[0],'PlayLibrary',ps('section.tv'),urllib.quote_plus(url),urllib.quote_plus(iconimage),urllib.quote_plus(name),urllib.quote_plus(name),year,year,country,season_number,episode_number,episode_title)
  1566. #
  1567. #
  1568. filename=name+' ('+year+') S'+season_number+'E'+episode_number
  1569. filename=clean_filename(filename+'.strm')
  1570. file =xbmc.translatePath(os.path.join(folderseason,filename))
  1571. ##print file
  1572. a=open(file, "w"); a.write(strm); a.close()
  1573. myNote('Library TV:',filename)
  1574. def myNote( header='',msg='',delay=5000,image='http://upload.wikimedia.org/wikipedia/commons/thumb/a/a5/US_99_%281961%29.svg/40px-US_99_%281961%29.svg.png'):
  1575. header=cFL(header,ps('cFL_color')); msg=cFL(msg,ps('cFL_color2'))
  1576. _addon.show_small_popup(title=header,msg=msg,delay=delay,image=image)
  1577. ### ############################################################################################################
  1578. ### ############################################################################################################
  1579. def twitter_timeline(person):
  1580. HTML=getURL('http://mobile.twitter.com/'+person) ### HTML=getURL('http://twitter.com/'+person)
  1581. #
  1582. #
  1583. ### ############################################################################################################
  1584. ### ############################################################################################################
  1585. ### ############################################################################################################
  1586. ### ############################################################################################################
  1587. ### ############################################################################################################
  1588. ### ############################################################################################################
  1589. ### ############################################################################################################
  1590. ### ############################################################################################################
  1591. ### ############################################################################################################
  1592. ### ############################################################################################################
  1593. ### ############################################################################################################
  1594. ### ############################################################################################################
  1595. ### ############################################################################################################
  1596. ### ############################################################################################################
  1597. ### ############################################################################################################
  1598. ### ############################################################################################################
  1599. MyMenu=class_MyMenu()
  1600. #notification('Current Site',mainSite)
  1601. ### ############################################################################################################
  1602. ### ############################################################################################################
  1603. ### ############################################################################################################