Advertisement
Guest User

Untitled

a guest
Jan 2nd, 2015
361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.95 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2.  
  3. import os
  4. import sys
  5. import xbmc
  6. import urllib
  7. import xbmcvfs
  8. import xbmcaddon
  9. import xbmcgui
  10. import xbmcplugin
  11. import shutil
  12. import unicodedata
  13. import re
  14. import string
  15. import difflib
  16. import HTMLParser
  17.  
  18. __addon__ = xbmcaddon.Addon()
  19. __author__ = __addon__.getAddonInfo('author')
  20. __scriptid__ = __addon__.getAddonInfo('id')
  21. __scriptname__ = __addon__.getAddonInfo('name')
  22. __version__ = __addon__.getAddonInfo('version')
  23. __language__ = __addon__.getLocalizedString
  24.  
  25. __cwd__ = xbmc.translatePath(__addon__.getAddonInfo('path')).decode("utf-8")
  26. __profile__ = xbmc.translatePath(__addon__.getAddonInfo('profile')).decode("utf-8")
  27. __resource__ = xbmc.translatePath(os.path.join(__cwd__, 'resources', 'lib')).decode("utf-8")
  28. __temp__ = xbmc.translatePath(os.path.join(__profile__, 'temp')).decode("utf-8")
  29.  
  30. if xbmcvfs.exists(__temp__):
  31. shutil.rmtree(__temp__)
  32. xbmcvfs.mkdirs(__temp__)
  33.  
  34. sys.path.append(__resource__)
  35.  
  36. from ArgenteamUtilities import log, geturl
  37.  
  38. main_url_search = "http://www.argenteam.net/search/"
  39. main_url = "http://www.argenteam.net/"
  40.  
  41. # Seasons as strings for searching
  42. seasons = ["Specials", "First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth", "Ninth", "Tenth"]
  43. seasons = seasons + ["Eleventh", "Twelfth", "Thirteenth", "Fourteenth", "Fifteenth", "Sixteenth", "Seventeenth",
  44. "Eighteenth", "Nineteenth", "Twentieth"]
  45. seasons = seasons + ["Twenty-first", "Twenty-second", "Twenty-third", "Twenty-fourth", "Twenty-fifth", "Twenty-sixth",
  46. "Twenty-seventh", "Twenty-eighth", "Twenty-ninth"]
  47.  
  48. '''
  49. <div class="search-item-desc">
  50. <a href="/episode/29322/The.Mentalist.%282008%29.S01E01-Pilot">
  51.  
  52. <div class="search-item-desc">
  53. <a href="/movie/25808/Awake.%282007%29">
  54. '''
  55.  
  56. search_results_pattern = "<div\sclass=\"search-item-desc\">(.+?)<a\shref=\"/(episode|movie)/(.+?)/(.+?)\">(.+?)</a>"
  57.  
  58. subtitle_pattern = "<div\sclass=\"links\">(.+?)<strong>Descargado:</strong>(.+?)ve(ces|z)(.+?)<div>(.+?)<a\shref=\"/subtitles/(.+?)/(.+?)\">(.+?)</a>"
  59.  
  60.  
  61.  
  62. def find_movie(content, title, year):
  63. url_found = None
  64. h = HTMLParser.HTMLParser()
  65. for matches in re.finditer(movie_season_pattern, content, re.IGNORECASE | re.DOTALL):
  66. found_title = matches.group('title')
  67. found_title = h.unescape(found_title)
  68. log(__name__, "Found movie on search page: %s (%s)" % (found_title, matches.group('year')))
  69. if string.find(string.lower(found_title), string.lower(title)) > -1:
  70. if matches.group('year') == year:
  71. log(__name__, "Matching movie found on search page: %s (%s)" % (found_title, matches.group('year')))
  72. url_found = matches.group('link')
  73. break
  74. return url_found
  75.  
  76.  
  77. def find_subtitles(content):
  78. #url_found = None
  79. possible_matches = []
  80. #ll_tvshows = []
  81.  
  82. h = HTMLParser.HTMLParser()
  83. for matches in re.finditer(subtitle_pattern, content, re.IGNORECASE | re.DOTALL | re.UNICODE):
  84. id = matches.group(6)
  85. filename=urllib.unquote_plus(matches.group(7))
  86. downloads = (int(matches.group(2)) / 1000) / 2
  87. log(__name__, "Encontrado subtitulo: %s" % filename)
  88. possible_matches.append({'id':id, 'filename':filename,'downloads':downloads})
  89.  
  90. return possible_matches
  91.  
  92.  
  93. def append_subtitle(items):
  94.  
  95. items.sort(key=lambda x: x['rating'], reverse=True)
  96. index = 0
  97. for item in items:
  98. index += 1
  99. listitem = xbmcgui.ListItem(label=item['lang'],
  100. label2=item['filename'],
  101. iconImage=item['rating'],
  102. thumbnailImage=item['image'])
  103.  
  104. #listitem.setProperty("sync", 'true' if item["sync"] else 'false')
  105. #listitem.setProperty("hearing_imp", 'true' if item["hearing_imp"] else 'false')
  106.  
  107. ## below arguments are optional, it can be used to pass any info needed in download function
  108. ## anything after "action=download&" will be sent to addon once user clicks listed subtitle to downlaod
  109. url = "plugin://%s/?action=download&actionsortorder=%s&link=%s&filename=%s&id=%s" % (__scriptid__,
  110. str(index).zfill(2),
  111. item['link'],
  112. item['filename'],
  113. item['id'])
  114.  
  115. ## add it to list, this can be done as many times as needed for all subtitles found
  116. xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False)
  117.  
  118. def search_movie(title, year, languages, filename):
  119. title = string.strip(title)
  120.  
  121. log(__name__, "Search movie = %s" % title)
  122. search_string = "%s (%s)" % (title, year)
  123. search_pack(search_string)
  124.  
  125. def search_tvshow(tvshow, season, episode, title, languages, filename):
  126. tvshow = string.strip(tvshow)
  127.  
  128. #Prevent that the "US" acronym interfere with the search in the site
  129. tvshow = tvshow.replace("(US)","")
  130.  
  131. search_string = "%s S%#02dE%#02d %s" % (tvshow, int(season), int(episode), title)
  132.  
  133. log(__name__, "Search tvshow = %s" % search_string)
  134. search_pack(search_string)
  135.  
  136. def search_pack(search_string):
  137. url = main_url_search + urllib.quote_plus(search_string)
  138. content, response_url = geturl(url)
  139.  
  140. #Check if gives more than tv show or movie pack
  141. pack_urls = []
  142. for matches in re.finditer(search_results_pattern, content, re.IGNORECASE | re.DOTALL | re.MULTILINE | re.UNICODE):
  143. tipo = matches.group(2)
  144. id = matches.group(3)
  145. link = matches.group(4)
  146.  
  147. url_subtitle = "http://www.argenteam.net/" + tipo +"/"+ id +"/"+link
  148. print url_subtitle
  149. pack_urls.append(url_subtitle)
  150.  
  151. subs = []
  152. if len(pack_urls) > 0:
  153. for url_pack in pack_urls:
  154. pack_content, response_url = geturl(url_pack)
  155. subs.extend(search_common(pack_content))
  156. else:
  157. subs.extend(search_common(content))
  158.  
  159. append_subtitle(subs)
  160.  
  161. def search_common(content):
  162. if content is not None:
  163. log(__name__, "Resultados encontrados...")
  164. object_subtitles = find_subtitles(content)
  165. items = []
  166. if object_subtitles is not None:
  167. log(__name__, "Buscando subtitulos...")
  168.  
  169. for sub in object_subtitles:
  170. item = {}
  171. item['lang'] = "Spanish"
  172. item['filename'] = sub['filename']
  173. item['rating'] = str(sub['downloads'])
  174. item['image'] = 'es'
  175. item['id'] = sub['id']
  176. item['link'] = main_url + "subtitles/" + sub['id'] + "/" + sub['filename']
  177. items.append(item)
  178.  
  179. return items
  180.  
  181. def search_manual(searchstr, languages, filename):
  182. search_pack(prepare_search_string(searchstr))
  183.  
  184. def search_filename(filename, languages):
  185. title, year = xbmc.getCleanMovieTitle(filename)
  186. log(__name__, "clean title: \"%s\" (%s)" % (title, year))
  187. try:
  188. yearval = int(year)
  189. except ValueError:
  190. yearval = 0
  191. if title and yearval > 1900:
  192. search_movie(title, year, item['3let_language'], filename)
  193. else:
  194. match = re.search(r'\WS(?P<season>\d\d)E(?P<episode>\d\d)', title, flags=re.IGNORECASE)
  195. if match is not None:
  196. tvshow = string.strip(title[:match.start('season')-1])
  197. season = string.lstrip(match.group('season'), '0')
  198. episode = string.lstrip(match.group('episode'), '0')
  199. search_tvshow(tvshow, season, episode, '', item['3let_language'], filename)
  200. else:
  201. search_manual(filename, item['3let_language'], filename)
  202.  
  203.  
  204. def search(item):
  205. filename = os.path.splitext(os.path.basename(item['file_original_path']))[0]
  206. log(__name__, "Search_argenteam='%s', filename='%s', addon_version=%s" % (item, filename, __version__))
  207.  
  208. if item['mansearch']:
  209. search_manual(item['mansearchstr'], item['3let_language'], filename)
  210. elif item['tvshow']:
  211. search_tvshow(item['tvshow'], item['season'], item['episode'], item['title'], item['3let_language'], filename)
  212. elif item['title'] and item['year']:
  213. search_movie(item['title'], item['year'], item['3let_language'], filename)
  214. else:
  215. search_filename(filename, item['3let_language'])
  216.  
  217. def prepare_search_string(s):
  218. s = string.strip(s)
  219. #s = urllib.quote_plus(s)
  220. #s = re.sub(r'\s', '-', s)
  221. return s
  222.  
  223. def download(id, url, filename, search_string=""):
  224. subtitle_list = []
  225. exts = [".srt", ".sub", ".txt", ".smi", ".ssa", ".ass"]
  226. ## Cleanup temp dir, we recomend you download/unzip your subs in temp folder and
  227. ## pass that to XBMC to copy and activate
  228.  
  229. filename = os.path.join(__temp__, filename + ".zip")
  230.  
  231. sub = urllib.urlopen(url).read()
  232. with open(filename, "wb") as subFile:
  233. subFile.write(sub)
  234. subFile.close()
  235.  
  236. xbmc.sleep(500)
  237. xbmc.executebuiltin(('XBMC.Extract("%s","%s")' % (filename, __temp__,)).encode('utf-8'), True)
  238.  
  239. for file in xbmcvfs.listdir(__temp__)[1]:
  240. file = os.path.join(__temp__, file)
  241. if os.path.splitext(file)[1] in exts:
  242. if search_string and string.find(string.lower(file), string.lower(search_string)) == -1:
  243. continue
  244. log(__name__, "=== returning subtitle file %s" % file)
  245. subtitle_list.append(file)
  246.  
  247. return subtitle_list
  248.  
  249.  
  250. def normalizeString(str):
  251. return unicodedata.normalize(
  252. 'NFKD', unicode(unicode(str, 'utf-8'))
  253. ).encode('ascii', 'ignore')
  254.  
  255.  
  256. def get_params():
  257. param = {}
  258. paramstring = sys.argv[2]
  259. if len(paramstring) >= 2:
  260. params = paramstring
  261. cleanedparams = params.replace('?', '')
  262. if (params[len(params) - 1] == '/'):
  263. params = params[0:len(params) - 2]
  264. pairsofparams = cleanedparams.split('&')
  265. param = {}
  266. for i in range(len(pairsofparams)):
  267. splitparams = pairsofparams[i].split('=')
  268. if (len(splitparams)) == 2:
  269. param[splitparams[0]] = splitparams[1]
  270.  
  271. return param
  272.  
  273.  
  274. params = get_params()
  275.  
  276. if params['action'] == 'search' or params['action'] == 'manualsearch':
  277. item = {}
  278. item['temp'] = False
  279. item['rar'] = False
  280. item['mansearch'] = False
  281. item['year'] = xbmc.getInfoLabel("VideoPlayer.Year") # Year
  282. item['season'] = str(xbmc.getInfoLabel("VideoPlayer.Season")) # Season
  283. item['episode'] = str(xbmc.getInfoLabel("VideoPlayer.Episode")) # Episode
  284. item['tvshow'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.TVshowtitle")) # Show
  285. item['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.OriginalTitle")) # try to get original title
  286. item['file_original_path'] = urllib.unquote(xbmc.Player().getPlayingFile().decode('utf-8')) # Full path
  287. item['3let_language'] = []
  288.  
  289. if 'searchstring' in params:
  290. item['mansearch'] = True
  291. item['mansearchstr'] = params['searchstring']
  292. print params['searchstring']
  293.  
  294. for lang in urllib.unquote(params['languages']).decode('utf-8').split(","):
  295. item['3let_language'].append(xbmc.convertLanguage(lang, xbmc.ISO_639_2))
  296.  
  297. if item['title'] == "":
  298. item['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.Title")) # no original title, get just Title
  299.  
  300. if item['episode'].lower().find("s") > -1: # Check if season is "Special"
  301. item['season'] = "0" #
  302. item['episode'] = item['episode'][-1:]
  303.  
  304. if item['file_original_path'].find("http") > -1:
  305. item['temp'] = True
  306.  
  307. elif item['file_original_path'].find("rar://") > -1:
  308. item['rar'] = True
  309. item['file_original_path'] = os.path.dirname(item['file_original_path'][6:])
  310.  
  311. elif item['file_original_path'].find("stack://") > -1:
  312. stackPath = item['file_original_path'].split(" , ")
  313. item['file_original_path'] = stackPath[0][8:]
  314.  
  315. search(item)
  316.  
  317. elif params['action'] == 'download':
  318. ## we pickup all our arguments sent from def Search()
  319. if 'find' in params:
  320. subs = download(params["link"], params["find"])
  321. else:
  322. subs = download(params["id"],params["link"], params["filename"])
  323. ## we can return more than one subtitle for multi CD versions, for now we are still working out how to handle that
  324. ## in XBMC core
  325. for sub in subs:
  326. listitem = xbmcgui.ListItem(label=sub)
  327. xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sub, listitem=listitem, isFolder=False)
  328.  
  329. xbmcplugin.endOfDirectory(int(sys.argv[1])) # send end of directory to XBMC
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement