Advertisement
Guest User

LegendasDivx script XBMC

a guest
Oct 1st, 2012
261
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 22.17 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. # Service LegendasDivx.com version 0.2.4
  3. # Code based on Undertext service
  4. # Coded by HiGhLaNdR@OLDSCHOOL
  5. # Help by VaRaTRoN
  6. # Bugs & Features to highlander@teknorage.com
  7. # http://www.teknorage.com
  8. # License: GPL v2
  9. #
  10. # NEW on Service LegendasDivx.com v0.2.4:
  11. # Added uuid for better file handling, no more hangups.
  12. #
  13. # NEW on Service LegendasDivx.com v0.2.3:
  14. # Fixed typo on the version.
  15. # Added built-in notifications.
  16. #
  17. # NEW on Service LegendasDivx.com v0.2.2:
  18. # Fixed pathnames using (os.sep). For sure :)
  19. #
  20. # NEW on Service LegendasDivx.com v0.2.1:
  21. # Fixed bug when the file is played from a root path, no parent dir search\sync when that happens.
  22. # Fixed pathnames to work with all OS (Win, Unix, etc).
  23. # Added pattern to search several subtitle extensions.
  24. #
  25. # NEW on Service LegendasDivx.com v0.2.0:
  26. # Better "star" rating, remember that the start rating is calculated using the number of hits/downloads.
  27. # Fixed a bug in the SYNC subtitles, it wouldn't assume that any were sync (in the code), a dialog box would open in multi packs.
  28. #
  29. # NEW on Service LegendasDivx.com v0.1.9:
  30. # When no sync subtitle is found and the pack has more then 1 sub, it will open a dialog box for browsing the substitles inside the multi pack.
  31. #
  32. # NEW on Service LegendasDivx.com v0.1.8:
  33. # Uncompress rar'ed subtitles inside a rar file... yeh weird site...
  34. #
  35. # NEW on Service LegendasDivx.com v0.1.7:
  36. # BUG found in multi packs is now fixed.
  37. # Added more accuracy to the selection of subtitle to load. Now checks the release dirname against the subtitles downloaded.
  38. # When no sync is found and if the substitle name is not equal to the release dirname or release filename it will load one random subtitle from the package.
  39. #
  40. # NEW on Service LegendasDivx.com v0.1.6:
  41. # Movies or TV eps with 2cds or more will now work.
  42. # Sync subs is now much more accurate.
  43. #
  44. # Initial Release of Service LegendasDivx.com - v0.1.5:
  45. # TV Season packs now downloads and chooses the best one available in the pack
  46. # Movie packs with several releases now works too, tries to choose the sync sub using filename or dirname
  47. # Search description for SYNC subtitles using filename or dirname
  48. #
  49. # KNOWN BUGS (TODO for next versions):
  50. # Regex isn't perfect so a few results might have html tags still, not many but ...
  51. # Filtering languages, shows only European Portuguese flag.
  52.  
  53. # LegendasDivx.com subtitles, based on a mod of Undertext subtitles
  54. import os, sys, re, xbmc, xbmcgui, string, time, urllib, urllib2, cookielib, shutil, fnmatch, uuid
  55. from utilities import log
  56. _ = sys.modules[ "__main__" ].__language__
  57. __scriptname__ = sys.modules[ "__main__" ].__scriptname__
  58. __addon__ = sys.modules[ "__main__" ].__addon__
  59. __cwd__        = sys.modules[ "__main__" ].__cwd__
  60.  
  61. main_url = "http://www.legendasdivx.com/"
  62. debug_pretext = "LegendasDivx"
  63. subext = ['srt', 'aas', 'ssa', 'sub', 'smi']
  64. packext = ['rar', 'zip']
  65.  
  66. #====================================================================================================================
  67. # Regular expression patterns
  68. #====================================================================================================================
  69.  
  70. """
  71. <div class="sub_box">
  72. <div class="sub_header">
  73. <b>The Dark Knight</b> (2008) &nbsp; - &nbsp; Enviada por: <a href='modules.php?name=User_Info&username=tck17'><b>tck17</b></a> &nbsp; em 2010-02-03 02:44:09
  74.  
  75. </div>
  76. <table class="sub_main color1" cellspacing="0">
  77. <tr>
  78. <th class="color2">Idioma:</th>
  79. <td><img width="18" height="12" src="modules/Downloads/img/portugal.gif" /></td>
  80. <th>CDs:</th>
  81. <td>1&nbsp;</td>
  82. <th>Frame Rate:</th>
  83. <td>23.976&nbsp;</td>
  84. <td rowspan="2" class="td_right color2">
  85. <a href="?name=Downloads&d_op=ratedownload&lid=128943">
  86. <img border="0" src="modules/Downloads/images/rank9.gif"><br>Classifique (3 votos)
  87.  
  88. </a>
  89. </td>
  90. </tr>
  91. <tr>
  92. <th class="color2">Hits:</th>
  93. <td>1842</td>
  94. <th>Pedidos:</th>
  95. <td>77&nbsp;</td>
  96. <th>Origem:</th>
  97. <td>DVD Rip&nbsp;</td>
  98. </tr>
  99.  
  100. <tr>
  101. <th class="color2">Descrição:</th>
  102. <td colspan="5" class="td_desc brd_up">Não são minhas.<br />
  103. <br />
  104. Release: The.Dark.Knight.2008.720p.BluRay.DTS.x264-ESiR</td>
  105. """
  106. #subtitle_pattern = "<div\sclass=\"sub_box\">[\r\n\t]{2}<div\sclass=\"sub_header\">[\r\n\t]{2}<b>(.+?)</b>\s\((\d\d\d\d)\)\s.+?[\r\n\t ]+?[\r\n\t]</div>[\r\n\t]{2}<table\sclass=\"sub_main\scolor1\"\scellspacing=\"0\">[\r\n\t]{2}<tr>[\r\n\t]{2}.+?[\r\n\t]{2}.+?img/(.+?)gif\".+?[\r\n\t]{2}<th>CDs:</th>[\r\n\t ]{2}<td>(.+?)&nbsp;</td>[\r\n\t]{2}.+?[\r\n\t]{2}.+?[\r\n\t]{2}.+?[\r\n\t]{2}<a\shref=\"\?name=Downloads&d_op=ratedownload&lid=(.+?)\">[\r\n\t]{2}.+?[\r\n\t]{2}.+?[\r\n\t]{2}.+?[\r\n\t]{2}.+?[\r\n\t]{2}.+?[\r\n\t]{2}<th\sclass=\"color2\">Hits:</th>[\r\n\t]{2}<td>(.+?)</td>[\r\n\t ]{2}.+?[\r\n\t]{2}<td>(.+?)</td>[\r\n\t ]{2}.+?[\r\n\t ]{2}.+?[\r\n\t ]{2}.+?[\r\n\t ]{2}.+?.{2,5}[\r\n\t ]{2}.+?[\r\n\t ]{2}<td\scolspan=\"5\"\sclass=\"td_desc\sbrd_up\">((\n|.)*)</td>"
  107. # group(1) = Name, group(2) = Year, group(3) = Language, group(4)= Number Files, group(5) = ID, group(6) = Hits, group(7) = Requests, group(8) = Description
  108.  
  109. subtitle_pattern = "<div\sclass=\"sub_box\">[\r\n\t]{2}<div\sclass=\"sub_header\">[\r\n\t]{2}<b>(.+?)</b>\s\((\d\d\d\d)\)\s.+?[\r\n\t ]+?[\r\n\t]</div>[\r\n\t]{2}<table\sclass=\"sub_main\scolor1\"\scellspacing=\"0\">[\r\n\t]{2}<tr>[\r\n\t]{2}.+?[\r\n\t]{2}.+?[\r\n\t]{2}<th>CDs:</th>[\r\n\t ]{2}<td>(.+?)</td>[\r\n\t]{2}.+?[\r\n\t]{2}.+?[\r\n\t]{2}.+?[\r\n\t]{2}<a\shref=\"\?name=Downloads&d_op=ratedownload&lid=(.+?)\">[\r\n\t]{2}.+?[\r\n\t]{2}.+?[\r\n\t]{2}.+?[\r\n\t]{2}.+?[\r\n\t]{2}.+?[\r\n\t]{2}<th\sclass=\"color2\">Hits:</th>[\r\n\t]{2}<td>(.+?)</td>[\r\n\t ]{2}.+?[\r\n\t]{2}<td>(.+?)</td>[\r\n\t ]{2}.+?[\r\n\t ]{2}.+?[\r\n\t ]{2}.+?[\r\n\t ]{2}.+?.{2,5}[\r\n\t ]{2}.+?[\r\n\t ]{2}<td\scolspan=\"5\"\sclass=\"td_desc\sbrd_up\">((\n|.)*)</td>"
  110. # group(1) = Name, group(2) = Year, group(3) = Number Files, group(4) = ID, group(5) = Hits, group(6) = Requests, group(7) = Description
  111. #====================================================================================================================
  112. # Functions
  113. #====================================================================================================================
  114. def msg(text, timeout):
  115.     icon =  os.path.join(__cwd__,"icon.png")
  116.     xbmc.executebuiltin("XBMC.Notification(%s,%s,%s,%s)" % (__scriptname__,text,timeout,icon))
  117.  
  118.  
  119. def getallsubs(searchstring, languageshort, languagelong, file_original_path, subtitles_list, searchstring_notclean):
  120.  
  121.     page = 1
  122.     if languagelong == "Portuguese":
  123.         url = main_url + "modules.php?name=Downloads&file=jz&d_op=search_next&order=&form_cat=28&page=" + str(page) + "&query=" + urllib.quote_plus(searchstring)
  124.     if languagelong == "PortugueseBrazil":
  125.         url = main_url + "modules.php?name=Downloads&file=jz&d_op=search_next&order=&form_cat=29&page=" + str(page) + "&query=" + urllib.quote_plus(searchstring)      
  126.  
  127.     content = geturl(url)
  128.     log( __name__ ,"%s Getting '%s' subs ..." % (debug_pretext, languageshort))
  129.     msg("Searching Title... Please wait!", 6000)
  130.     while re.search(subtitle_pattern, content, re.IGNORECASE | re.DOTALL | re.MULTILINE | re.UNICODE | re.VERBOSE) and page < 6:
  131.         for matches in re.finditer(subtitle_pattern, content, re.IGNORECASE | re.DOTALL | re.MULTILINE | re.UNICODE | re.VERBOSE):
  132.             hits = matches.group(5)
  133.             id = matches.group(4)
  134.             movieyear = matches.group(2)
  135.             no_files = matches.group(3)
  136.             downloads = int(matches.group(5)) / 300
  137.             if (downloads > 10):
  138.                 downloads=10
  139.             filename = string.strip(matches.group(1))
  140.             desc = string.strip(matches.group(7))
  141.             #Remove new lines on the commentaries
  142.             filename = re.sub('\n',' ',filename)
  143.             desc = re.sub('\n',' ',desc)
  144.             #Remove HTML tags on the commentaries
  145.             filename = re.sub(r'<[^<]+?>','', filename)
  146.             desc = re.sub(r'<[^<]+?>|[~]','', desc)
  147.             filename = re.sub(r'<[^<]+?>','', filename)
  148.             desc = re.sub(r'<[^<]+?>|[~]','', desc)
  149.             desc = re.sub(':.','', desc)
  150.             filename = re.sub(':.','', filename)
  151.             #Find filename on the comentaries to show sync label using filename or dirname (making it global for further usage)
  152.             global filesearch
  153.             filesearch = os.path.abspath(file_original_path)
  154.             #For DEBUG only uncomment next line
  155.             #log( __name__ ,"%s abspath: '%s'" % (debug_pretext, filesearch))
  156.             filesearch = os.path.split(filesearch)
  157.             #For DEBUG only uncomment next line
  158.             #log( __name__ ,"%s path.split: '%s'" % (debug_pretext, filesearch))
  159.             dirsearch = filesearch[0].split(os.sep)
  160.             #For DEBUG only uncomment next line
  161.             #log( __name__ ,"%s dirsearch: '%s'" % (debug_pretext, dirsearch))
  162.             dirsearch_check = string.split(dirsearch[-1], '.')
  163.             #For DEBUG only uncomment next line
  164.             #log( __name__ ,"%s dirsearch_check: '%s'" % (debug_pretext, dirsearch_check))
  165.             if (searchstring_notclean != ""):
  166.                 sync = False
  167.                 if re.search(searchstring_notclean, desc):
  168.                     sync = True
  169.             else:
  170.                 if (string.lower(dirsearch_check[-1]) == "rar") or (string.lower(dirsearch_check[-1]) == "cd1") or (string.lower(dirsearch_check[-1]) == "cd2"):
  171.                     sync = False
  172.                     if len(dirsearch) > 1 and dirsearch[1] != '':
  173.                         if re.search(filesearch[1][:len(filesearch[1])-4], desc) or re.search(dirsearch[-2], desc):
  174.                             sync = True
  175.                     else:
  176.                         if re.search(filesearch[1][:len(filesearch[1])-4], desc):
  177.                             sync = True
  178.                 else:
  179.                     sync = False
  180.                     if len(dirsearch) > 1 and dirsearch[1] != '':
  181.                         if re.search(filesearch[1][:len(filesearch[1])-4], desc) or re.search(dirsearch[-1], desc):
  182.                             sync = True
  183.                     else:
  184.                         if re.search(filesearch[1][:len(filesearch[1])-4], desc):
  185.                             sync = True
  186.             #filename = filename + " " + "(" + movieyear + ")" + "  " + hits + "Hits" + " - " + desc
  187.             filename = desc
  188.             subtitles_list.append({'rating': str(downloads), 'no_files': no_files, 'filename': filename, 'desc': desc, 'sync': sync, 'hits' : hits, 'id': id, 'language_flag': 'flags/' + 'pb' + '.gif', 'language_name': languagelong})
  189.         page = page + 1
  190.         if languageshort == "pt":
  191.             url = main_url + "modules.php?name=Downloads&file=jz&d_op=search_next&order=&form_cat=28&page=" + str(page) + "&query=" + urllib.quote_plus(searchstring)
  192.         if languageshort == "pb":
  193.             url = main_url + "modules.php?name=Downloads&file=jz&d_op=search_next&order=&form_cat=29&page=" + str(page) + "&query=" + urllib.quote_plus(searchstring)  
  194.         #url = main_url + "modules.php?name=Downloads&file=jz&d_op=search_next&order=&form_cat=29&page=" + str(page) + "&query=" + urllib.quote_plus(searchstring)
  195.         content = geturl(url)
  196.  
  197.     if subtitles_list != []:
  198.         msg("Finished Searching. Choose One!", 3000)
  199.     else:
  200.         msg("No Results! Try Parent Dir Or Manual!", 4000)
  201.        
  202. #   Bubble sort, to put syncs on top
  203.     for n in range(0,len(subtitles_list)):
  204.         for i in range(1, len(subtitles_list)):
  205.             temp = subtitles_list[i]
  206.             if subtitles_list[i]["sync"] > subtitles_list[i-1]["sync"]:
  207.                 subtitles_list[i] = subtitles_list[i-1]
  208.                 subtitles_list[i-1] = temp
  209.  
  210.  
  211.  
  212.  
  213.  
  214. def geturl(url):
  215.     class MyOpener(urllib.FancyURLopener):
  216.         version = ''
  217.     my_urlopener = MyOpener()
  218.     log( __name__ ,"%s Getting url: %s" % (debug_pretext, url))
  219.     try:
  220.         response = my_urlopener.open(url)
  221.         content    = response.read()
  222.     except:
  223.         log( __name__ ,"%s Failed to get url:%s" % (debug_pretext, url))
  224.         content    = None
  225.     return content
  226.  
  227. def search_subtitles( file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack ): #standard input
  228.     subtitles_list = []
  229.     msg = ""
  230.     searchstring_notclean = ""
  231.     searchstring = ""
  232.     global israr
  233.     israr = os.path.abspath(file_original_path)
  234.     israr = os.path.split(israr)
  235.     israr = israr[0].split(os.sep)
  236.     israr = string.split(israr[-1], '.')
  237.     israr = string.lower(israr[-1])
  238.    
  239.     if len(tvshow) == 0:
  240.         if 'rar' in israr and searchstring is not None:
  241.             if 'cd1' in string.lower(title) or 'cd2' in string.lower(title) or 'cd3' in string.lower(title):
  242.                 dirsearch = os.path.abspath(file_original_path)
  243.                 dirsearch = os.path.split(dirsearch)
  244.                 dirsearch = dirsearch[0].split(os.sep)
  245.                 if len(dirsearch) > 1:
  246.                     searchstring_notclean = dirsearch[-3]
  247.                     searchstring = xbmc.getCleanMovieTitle(dirsearch[-3])
  248.                     searchstring = searchstring[0]
  249.                 else:
  250.                     searchstring = title
  251.             else:
  252.                 searchstring = title
  253.         elif 'cd1' in string.lower(title) or 'cd2' in string.lower(title) or 'cd3' in string.lower(title):
  254.             dirsearch = os.path.abspath(file_original_path)
  255.             dirsearch = os.path.split(dirsearch)
  256.             dirsearch = dirsearch[0].split(os.sep)
  257.             if len(dirsearch) > 1:
  258.                 searchstring_notclean = dirsearch[-2]
  259.                 searchstring = xbmc.getCleanMovieTitle(dirsearch[-2])
  260.                 searchstring = searchstring[0]
  261.             else:
  262.                 #We are at the root of the drive!!! so there's no dir to lookup only file#
  263.                 title = os.path.split(file_original_path)
  264.                 searchstring = title[-1]
  265.         else:
  266.             if title == "":
  267.                 title = os.path.split(file_original_path)
  268.                 searchstring = title[-1]
  269.             else:
  270.                 searchstring = title
  271.            
  272.     if len(tvshow) > 0:
  273.         searchstring = "%s S%#02dE%#02d" % (tvshow, int(season), int(episode))
  274.     log( __name__ ,"%s Search string = %s" % (debug_pretext, searchstring))
  275.  
  276.     portuguese = 0
  277.     portuguese_brazil = 0
  278.     if string.lower(lang1) == "portuguese": portuguese = 1
  279.     elif string.lower(lang1) == "portuguesebrazil": portuguese_brazil = 1
  280.  
  281.    
  282.     if portuguese == 1:
  283.     getallsubs(searchstring, "pt", "Portuguese", file_original_path, subtitles_list, searchstring_notclean)
  284.     if portuguese_brazil == 1:
  285.     getallsubs(searchstring, "pb", "PortugueseBrazil", file_original_path, subtitles_list, searchstring_notclean)
  286.  
  287.     if portuguese == 0:
  288.         msg = "Won't work, LegendasDivx is only for Portuguese subtitles!"
  289.    
  290.     return subtitles_list, "", msg #standard output
  291.    
  292. def recursive_glob(treeroot, pattern):
  293.     results = []
  294.     for base, dirs, files in os.walk(treeroot):
  295.         for extension in pattern:
  296.             for filename in fnmatch.filter(files, '*.' + extension):
  297.                 results.append(os.path.join(base, filename))
  298.     return results
  299.  
  300. def download_subtitles (subtitles_list, pos, zip_subs, tmp_sub_dir, sub_folder, session_id): #standard input
  301.  
  302.     msg("Downloading... Please Wait!", 6000)
  303.     id = subtitles_list[pos][ "id" ]
  304.     sync = subtitles_list[pos][ "sync" ]
  305.     log( __name__ ,"%s Fetching id using url %s" % (debug_pretext, id))
  306.     #Grabbing login and pass from xbmc settings
  307.     username = __addon__.getSetting( "LDivxuser" )
  308.     password = __addon__.getSetting( "LDivxpass" )
  309.     cj = cookielib.CookieJar()
  310.     opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  311.     opener.addheaders.append(('User-agent', 'Mozilla/4.0'))
  312.     opener.addheaders.append(('Referer', 'http://www.legendasdivx.com/modules.php?name=Your_Account&op=userinfo&bypass=1&username=highlander'))
  313.     login_data = urllib.urlencode({'username' : username, 'user_password' : password, 'op' : 'login'})
  314.     #This is where you are logged in
  315.     resp = opener.open('http://www.legendasdivx.com/modules.php?name=Your_Account', login_data)
  316.     #For DEBUG only uncomment next line
  317.     #log( __name__ ,"%s resposta '%s' subs ..." % (debug_pretext, resp))
  318.     #Now you can go to member only pages
  319.     resp1 = opener.open('http://www.legendasdivx.com/modules.php?name=Your_Account&op=userinfo&bypass=1&username=highlander')
  320.     d = resp1.read()
  321.     #Now you download the subtitles
  322.     language = subtitles_list[pos][ "language_name" ]
  323.     if string.lower(language) == "portuguese":
  324.         content = opener.open('http://www.legendasdivx.com/modules.php?name=Downloads&d_op=getit&lid=' + id + '&username=highlander')
  325.  
  326.     if content is not None:
  327.         header = content.info()['Content-Disposition'].split('filename')[1].split('.')[-1].strip("\"")
  328.         if header == 'rar':
  329.             log( __name__ ,"%s file: content is RAR" % (debug_pretext)) #EGO
  330.             local_tmp_file = os.path.join(tmp_sub_dir, str(uuid.uuid1()) + ".rar")
  331.             log( __name__ ,"%s file: local_tmp_file %s" % (debug_pretext, local_tmp_file)) #EGO
  332.             packed = True
  333.         elif header == 'zip':
  334.             local_tmp_file = os.path.join(tmp_sub_dir, str(uuid.uuid1()) + ".zip")
  335.             packed = True
  336.         else: # never found/downloaded an unpacked subtitles file, but just to be sure ...
  337.             local_tmp_file = os.path.join(tmp_sub_dir, str(uuid.uuid1()) + ".srt") # assume unpacked sub file is an '.srt'
  338.             subs_file = local_tmp_file
  339.             packed = False
  340.         log( __name__ ,"%s Saving subtitles to '%s'" % (debug_pretext, local_tmp_file))
  341.         try:
  342.             log( __name__ ,"%s file: write in %s" % (debug_pretext, local_tmp_file)) #EGO
  343.             local_file_handle = open(local_tmp_file, "wb")
  344.             shutil.copyfileobj(content.fp, local_file_handle)
  345.             local_file_handle.close()
  346.         except:
  347.             log( __name__ ,"%s Failed to save subtitles to '%s'" % (debug_pretext, local_tmp_file))
  348.         if packed:
  349.             files = os.listdir(tmp_sub_dir)
  350.             init_filecount = len(files)
  351.             log( __name__ ,"%s file: number init_filecount %s" % (debug_pretext, init_filecount)) #EGO
  352.             filecount = init_filecount
  353.             max_mtime = 0
  354.             # determine the newest file from tmp_sub_dir
  355.             for file in files:
  356.                 if (string.split(file,'.')[-1] in ['srt','sub','txt']):
  357.                     mtime = os.stat(os.path.join(tmp_sub_dir, file)).st_mtime
  358.                     if mtime > max_mtime:
  359.                         max_mtime =  mtime
  360.             init_max_mtime = max_mtime
  361.             time.sleep(2)  # wait 2 seconds so that the unpacked files are at least 1 second newer
  362.             msg("Extracting... Please Wait!", 6000)
  363.             xbmc.executebuiltin("XBMC.Extract(" + local_tmp_file + "," + tmp_sub_dir +")")
  364.             waittime  = 0
  365.             while (filecount == init_filecount) and (waittime < 20) and (init_max_mtime == max_mtime): # nothing yet extracted
  366.                 time.sleep(1)  # wait 1 second to let the builtin function 'XBMC.extract' unpack
  367.                 files = os.listdir(tmp_sub_dir)
  368.                 log( __name__ ,"%s DIRLIST '%s'" % (debug_pretext, files))
  369.                 filecount = len(files)
  370.                 # determine if there is a newer file created in tmp_sub_dir (marks that the extraction had completed)
  371.                 for file in files:
  372.                     if (string.split(file,'.')[-1] in ['srt','sub','txt']):
  373.                         mtime = os.stat(os.path.join(tmp_sub_dir, file)).st_mtime
  374.                         if (mtime > max_mtime):
  375.                             max_mtime =  mtime
  376.                 waittime  = waittime + 1
  377.             if waittime == 20:
  378.                 log( __name__ ,"%s Failed to unpack subtitles in '%s'" % (debug_pretext, tmp_sub_dir))
  379.             else:
  380.                 msg("Done Extracting!", 3000)
  381.                 log( __name__ ,"%s Unpacked files in '%s'" % (debug_pretext, tmp_sub_dir))
  382.                 searchrars = recursive_glob(tmp_sub_dir, packext)
  383.                 searchrarcount = len(searchrars)
  384.                 if searchrarcount > 1:
  385.                     for filerar in searchrars:
  386.                         if filerar != os.path.join(tmp_sub_dir,'ldivx.rar') and filerar != os.path.join(tmp_sub_dir,'ldivx.zip'):
  387.                             xbmc.executebuiltin("XBMC.Extract(" + filerar + "," + tmp_sub_dir +")")
  388.                 time.sleep(1)
  389.                 searchsubs = recursive_glob(tmp_sub_dir, subext)
  390.                 searchsubscount = len(searchsubs)
  391.                 for filesub in searchsubs:
  392.                     nopath = string.split(filesub, tmp_sub_dir)[-1]
  393.                     justfile = nopath.split(os.sep)[-1]
  394.                     #For DEBUG only uncomment next line
  395.                     #log( __name__ ,"%s DEBUG-nopath: '%s'" % (debug_pretext, nopath))
  396.                     #log( __name__ ,"%s DEBUG-justfile: '%s'" % (debug_pretext, justfile))
  397.                     releasefilename = filesearch[1][:len(filesearch[1])-4]
  398.                     releasedirname = filesearch[0].split(os.sep)
  399.                     if 'rar' in israr:
  400.                         releasedirname = releasedirname[-2]
  401.                     else:
  402.                         releasedirname = releasedirname[-1]
  403.                     #For DEBUG only uncomment next line
  404.                     #log( __name__ ,"%s DEBUG-releasefilename: '%s'" % (debug_pretext, releasefilename))
  405.                     #log( __name__ ,"%s DEBUG-releasedirname: '%s'" % (debug_pretext, releasedirname))
  406.                     subsfilename = justfile[:len(justfile)-4]
  407.                     #For DEBUG only uncomment next line
  408.                     #log( __name__ ,"%s DEBUG-subsfilename: '%s'" % (debug_pretext, subsfilename))
  409.                     #log( __name__ ,"%s DEBUG-subscount: '%s'" % (debug_pretext, searchsubscount))
  410.                     #Check for multi CD Releases
  411.                     multicds_pattern = "\+?(cd\d)\+?"
  412.                     multicdsubs = re.search(multicds_pattern, subsfilename, re.IGNORECASE | re.DOTALL | re.MULTILINE | re.UNICODE | re.VERBOSE)
  413.                     multicdsrls = re.search(multicds_pattern, releasefilename, re.IGNORECASE | re.DOTALL | re.MULTILINE | re.UNICODE | re.VERBOSE)
  414.                     #Start choosing the right subtitle(s)
  415.                     if searchsubscount == 1 and sync == True:
  416.                         subs_file = filesub
  417.                         #For DEBUG only uncomment next line
  418.                         #log( __name__ ,"%s DEBUG-inside subscount: '%s'" % (debug_pretext, searchsubscount))
  419.                         break
  420.                     elif string.lower(subsfilename) == string.lower(releasefilename) and sync == True:
  421.                         subs_file = filesub
  422.                         #For DEBUG only uncomment next line
  423.                         #log( __name__ ,"%s DEBUG-subsfile-morethen1: '%s'" % (debug_pretext, subs_file))
  424.                         break
  425.                     elif string.lower(subsfilename) == string.lower(releasedirname) and sync == True:
  426.                         subs_file = filesub
  427.                         #For DEBUG only uncomment next line
  428.                         #log( __name__ ,"%s DEBUG-subsfile-morethen1-dirname: '%s'" % (debug_pretext, subs_file))
  429.                         break
  430.                     elif (multicdsubs != None) and (multicdsrls != None) and sync == True:
  431.                         multicdsubs = string.lower(multicdsubs.group(1))
  432.                         multicdsrls = string.lower(multicdsrls.group(1))
  433.                         #For DEBUG only uncomment next line
  434.                         #log( __name__ ,"%s DEBUG-multicdsubs: '%s'" % (debug_pretext, multicdsubs))
  435.                         #log( __name__ ,"%s DEBUG-multicdsrls: '%s'" % (debug_pretext, multicdsrls))
  436.                         if multicdsrls == multicdsubs:
  437.                             subs_file = filesub
  438.                             break
  439.                 else:
  440.                     #If none is found just open a dialog box for browsing the temporary subtitle folder
  441.                     sub_ext = "srt,aas,ssa,sub,smi"
  442.                     sub_tmp = []
  443.                     for root, dirs, files in os.walk(tmp_sub_dir, topdown=False):
  444.                         for file in files:
  445.                             dirfile = os.path.join(root, file)
  446.                             ext = os.path.splitext(dirfile)[1][1:].lower()
  447.                             if ext in sub_ext:
  448.                                 sub_tmp.append(dirfile)
  449.                             elif os.path.isfile(dirfile):
  450.                                 os.remove(dirfile)
  451.                    
  452.                     # If there are more than one subtitle in the temp dir, launch a browse dialog
  453.                     # so user can choose. If only one subtitle is found, parse it to the addon.
  454.                     if len(sub_tmp) > 1:
  455.                         dialog = xbmcgui.Dialog()
  456.                         subs_file = dialog.browse(1, 'XBMC', 'files', '', False, False, tmp_sub_dir+"/")
  457.                         if subs_file == tmp_sub_dir+"/": subs_file = ""
  458.                     elif sub_tmp:
  459.                         subs_file = sub_tmp[0]
  460.        
  461.         msg("Playing Title!", 3000)
  462.  
  463.         return False, language, subs_file #standard output
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement