Advertisement
Guest User

Legendasdivx kodi addon

a guest
Dec 27th, 2021
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 27.69 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. # Service LegendasDivx.com version 1.0.5
  3. # Code based on Undertext (FRODO) service
  4. # Coded by HiGhLaNdR@OLDSCHOOL
  5. # Ported to Gotham by HiGhLaNdR@OLDSCHOOL
  6. # Help by VaRaTRoN
  7. # Bugs & Features to highlander@teknorage.com
  8. # http://www.teknorage.com
  9. # License: GPL v2
  10.  
  11. import os
  12. from os.path import join as pjoin
  13. import re
  14. import fnmatch
  15. import shutil
  16. import sys
  17. import string
  18. import time
  19. import unicodedata
  20. import urllib.request, urllib.parse, urllib.error
  21. import xbmc
  22. import xbmcaddon
  23. import xbmcgui
  24. import xbmcplugin
  25. import xbmcvfs
  26. import http.cookiejar
  27. import uuid
  28. import socket
  29. from urllib.parse import unquote, quote_plus
  30.  
  31. _addon = xbmcaddon.Addon()
  32. _author     = _addon.getAddonInfo('author')
  33. _scriptid   = _addon.getAddonInfo('id')
  34. _scriptname = _addon.getAddonInfo('name')
  35. _version    = _addon.getAddonInfo('version')
  36. _language   = _addon.getLocalizedString
  37.  
  38. _cwd        = xbmc.translatePath(_addon.getAddonInfo('path'))
  39. _profile    = xbmc.translatePath(_addon.getAddonInfo('profile'))
  40. _resource   = xbmc.translatePath(os.path.join(_cwd, 'resources', 'lib' ))
  41. _temp       = xbmc.translatePath(os.path.join(_profile, 'temp'))
  42.  
  43. if os.path.isdir(_temp):shutil.rmtree(_temp)
  44. xbmcvfs.mkdirs(_temp)
  45. if not os.path.isdir(_temp):xbmcvfs.mkdir(_temp)
  46.  
  47. sys.path.append (_resource)
  48.  
  49. _descon = _addon.getSetting( 'DESC' )
  50. _search = _addon.getSetting( 'SEARCH' )
  51. debug = _addon.getSetting( 'DEBUG' )
  52.  
  53. main_url = "https://www.legendasdivx.pt/"
  54. debug_pretext = "LegendasDivx"
  55. #SEARCH_PAGE_URL = main_url + "modules.php?name=Downloads&file=jz&d_op=search_next&order=&form_cat=28&page=%(page)s&query=%(query)s"
  56.  
  57. INTERNAL_LINK_URL = "plugin://%(scriptid)s/?action=download&id=%(id)s&filename=%(filename)s"
  58. SUB_EXTS = ['srt', 'sub', 'txt', 'ass', 'ssa', 'smi']
  59. HTTP_USER_AGENT = "User-Agent=Kodi 19 Matrix"
  60.  
  61. #====================================================================================================================
  62. # Regular expression patterns
  63. #====================================================================================================================
  64.  
  65. """
  66. <div class="sub_box">
  67. <div class="sub_header">
  68. <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
  69.  
  70. </div>
  71. <table class="sub_main color1" cellspacing="0">
  72. <tr>
  73. <th class="color2">Idioma:</th>
  74. <td><img width="18" height="12" src="modules/Downloads/img/portugal.gif" /></td>
  75. <th>CDs:</th>
  76. <td>1&nbsp;</td>
  77. <th>Frame Rate:</th>
  78. <td>23.976&nbsp;</td>
  79. <td rowspan="2" class="td_right color2">
  80. <a href="?name=Downloads&d_op=ratedownload&lid=128943">
  81. <img border="0" src="modules/Downloads/images/rank9.gif"><br>Classifique (3 votos)
  82.  
  83. </a>
  84. </td>
  85. </tr>
  86. <tr>
  87. <th class="color2">Hits:</th>
  88. <td>1842</td>
  89. <th>Pedidos:</th>
  90. <td>77&nbsp;</td>
  91. <th>Origem:</th>
  92. <td>DVD Rip&nbsp;</td>
  93. </tr>
  94.  
  95. <tr>
  96. <th class="color2">Descrição:</th>
  97. <td colspan="5" class="td_desc brd_up">Não são minhas.<br />
  98. <br />
  99. Release: The.Dark.Knight.2008.720p.BluRay.DTS.x264-ESiR</td>
  100. """
  101.  
  102. subtitle_pattern = "<div\sclass=\"sub_box\">.+?<div\sclass=\"sub_header\">.+?<b>(.+?)</b>\s\((\d\d\d\d)\)\s.+?name=User_Info&username=(.+?)'><b>.+?</div>.+?<table\sclass=\"sub_main\scolor1\"\scellspacing=\"0\">.+?<tr>.+?<th>CDs:</th>.+?<td>(.+?)</td>.+?<a\shref=\"\?name=Downloads&d_op=ratedownload&lid=(.+?)\">.+?<th\sclass=\"color2\">Hits:</th>.+?<td>(.+?)</td>.+?<td>(.+?)</td>.+?<td\scolspan=\"5\"\sclass=\"td_desc\sbrd_up\">(.*?)</td>.+?<td\sclass"
  103. release_pattern = "([^\W][\w\.]{1,}\w{1,}[\.]{1,1}[^\.|^\ |^\.org|^\.com|^\.net][^\Ws|^\.org|^\.com|^\.net][\w{1,}\.|\-|\(\d\d\d\d\)|\[\d\d\d\d\]]{3,}[^\Ws|^\.org|^\.com|^\.net][\w{3,}\-|\.{1,1}]\w{2,})"
  104. release_pattern1 = "([^\W][\w\ |\]|[]{4,}[^\Ws][x264|xvid|ac3]{1,}-[\w\[\]]{1,})"
  105. year_pattern = "(19|20)\d{2}$"
  106. # group(1) = Name, group(2) = Year, group(3) = Uploader, group (4) = Number Files, group(5) = ID, group(6) = Hits, group(7) = Requests, group(8) = Description
  107. #==========
  108. # Functions
  109. #==========
  110.  
  111. def _log(module, msg):
  112.     s = u"### [%s] - %s" % (module, msg)
  113.     xbmc.log(s, level=xbmc.LOGDEBUG)
  114.  
  115. def log(msg):
  116.     if debug == 'true': _log(_scriptname, msg)
  117.  
  118. def recursive_glob(treeroot, pattern):
  119.     results = []
  120.     for base, dirs, files in os.walk(treeroot):
  121.         for extension in pattern:
  122.             for filename in fnmatch.filter(files, '*.' + extension): results.append(os.path.join(base, filename))
  123.     return results
  124.  
  125. def xbmc_extract(SRC, DEST):
  126.     dd_ext, ff_ext = xbmcvfs.listdir(SRC)
  127.     for ff in ff_ext:
  128.         ext = os.path.splitext(ff)[1][1:].lower()
  129.         if ext in SUB_EXTS:
  130.             src_file = pjoin(SRC,ff).replace('\\','/')
  131.             dst_file = pjoin(xbmc.translatePath(DEST),ff)
  132.             success = xbmcvfs.copy(src_file,dst_file)
  133.             if not success:
  134.                 log("Error extracting: '%s' to '%s'" % (src_file,dst_file))
  135.             else:
  136.                 log("Extracting: '%s' to '%s'" % (src_file,dst_file))
  137.         else:
  138.             log("NO FILES YET...")
  139.     for dd in dd_ext:
  140.         dd_mk = pjoin(DEST,dd).replace('\\','/')
  141.         success_mk = xbmcvfs.mkdir(dd_mk)
  142.         if not success_mk:
  143.             log("Error creating directory: '%s'" % dd_mk)
  144.         else:
  145.             log("Created directory: '%s'" % dd_mk)
  146.         now_SRC = pjoin(SRC,dd,'').replace('\\','/')
  147.         now_DEST = pjoin(DEST,dd)
  148.         success_dd = xbmc_extract(now_SRC,now_DEST)
  149.         if not success_dd:
  150.             log("Error extracting inside dir: '%s' to '%s'" % (now_SRC,now_DEST))
  151.         else:
  152.             log("Extracting (back into the ff loop: '%s' to '%s'" % (now_SRC,now_DEST))
  153.  
  154. def login():
  155.     username = _addon.getSetting( 'LDuser' )
  156.     password = _addon.getSetting( 'LDpass' )
  157.     login_postdata = urllib.parse.urlencode({'username' : username, 'password' : password, 'login' : 'Login', 'sid' : ''}).encode("utf-8")
  158.     cj = http.cookiejar.CookieJar()
  159.     my_opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
  160.  
  161.     urllib.request.install_opener(my_opener)
  162.     request = urllib.request.Request(main_url + 'forum/ucp.php?mode=login', login_postdata)
  163.  
  164.  
  165.  
  166.     response = urllib.request.urlopen(request, None, 6.5).read().decode('ISO-8859-1')    
  167.     return my_opener
  168.  
  169. def urlpost(query, lang, page):
  170.     my_opener=login()
  171.     postdata = urllib.parse.urlencode({'query' : query, 'form_cat' : lang}).encode("utf-8")
  172.  
  173.     my_opener.addheaders = [('Referer', main_url + 'modules.php?name=Downloads&file=jz&d_op=search&op=_jz00&page='+ str(page))]
  174.     urllib.request.install_opener(my_opener)
  175.     request = urllib.request.Request(main_url + 'modules.php?name=Downloads&file=jz&d_op=search&op=_jz00&page='+ str(page), postdata)
  176.     log("POST url page: %s" % page)
  177.     log("POST url data: %s" % postdata)
  178.     try:
  179.         response = urllib.request.urlopen(request, None, 6.5).read().decode('ISO-8859-1')
  180.     except urllib.error.URLError as e:
  181.         response = ''
  182.         xbmc.executebuiltin(('Notification(%s,%s,%d)' % (_scriptname , _language(32025).encode('utf8'),5000)))
  183.         log("Oops, site down?")
  184.     except socket.timeout:
  185.         response = ''
  186.         xbmc.executebuiltin(('Notification(%s,%s,%d)' % (_scriptname , _language(32026).encode('utf8'),5000)))
  187.         log("Timed out!")
  188.     return response
  189.        
  190. def getallsubs(searchstring, languageshort, languagelong, file_original_path, searchstring_notclean):
  191.     subtitles_list = []
  192.     log(u"getallsubs: Search String = '%s'" % searchstring)
  193.     log(u"getallsubs: Search String Not Clean = '%s'" % searchstring_notclean)
  194.     page = 1
  195.     if languageshort == "pt": content = urlpost(searchstring, "28", page)
  196.     elif languageshort == "pb": content = urlpost(searchstring, "29", page)
  197.     elif languageshort == "es": content = urlpost(searchstring, "30", page)
  198.     elif languageshort == "en": content = urlpost(searchstring, "31", page)
  199.     log(u"getallsubs: LanguageShort = '%s'" % languageshort)
  200.     while re.search(subtitle_pattern, content, re.IGNORECASE | re.DOTALL | re.MULTILINE) and page < 6:
  201.         for matches in re.finditer(subtitle_pattern, content, re.IGNORECASE | re.DOTALL | re.X):
  202.             uploader = matches.group(3)
  203.             hits = matches.group(6)
  204.             if len(hits) > 10 : hits = hits.split(' ', 1)[0]
  205.             id = matches.group(5)
  206.             id = str.split(id, '"')
  207.             id = id[0]
  208.             movieyear = matches.group(2)
  209.             no_files = matches.group(4)
  210.             downloads = int(hits) / 200
  211.             if (downloads > 5): downloads=5
  212.             filename = str.strip(matches.group(1))
  213.             desc_ori = str.strip(matches.group(8))
  214.             desc_ori = re.sub('www.legendasdivx.com','',desc_ori)
  215.             log(u"getallsubs: Original Description = '%s'" % desc_ori)
  216.             #Remove new lines on the commentaries
  217.             filename = re.sub('\n',' ',filename)
  218.             _filenameon = "true"
  219.             if _descon == "false":
  220.                 desc = re.findall(release_pattern, desc_ori, re.IGNORECASE | re.VERBOSE | re.DOTALL | re.UNICODE | re.MULTILINE)
  221.                 desc = " / ".join(desc)
  222.                 if desc != "": _filenameon = "false"
  223.                 if desc == "":
  224.                     desc = re.findall(release_pattern1, desc_ori, re.IGNORECASE | re.VERBOSE | re.DOTALL | re.UNICODE | re.MULTILINE)
  225.                     desc = " / ".join(desc)
  226.                     if desc != "": _filenameon = "false"
  227.                     if desc == "": desc = desc_ori; _filenameon = "true"
  228.                     else: desc = desc; _filenameon = "false"
  229.             else: desc = desc_ori; _filenameon = "true"
  230.             desc = re.sub('<br />',' ',desc)
  231.             desc = re.sub('<br>',' ',desc)
  232.             desc = re.sub('\n',' ',desc)
  233.             desc = re.sub(':.','',desc)
  234.             #Remove HTML tags on the commentaries
  235.             filename = re.sub('\n',' ',filename)
  236.             desc = re.sub(r'<[^<]+?>|[~]','', desc)
  237.             log(u"getallsubs: Final Description = '%s'" % desc)
  238.             #Find filename on the comentaries to show sync label using filename or dirname (making it global for further usage)
  239.             global filesearch
  240.             filesearch = os.path.abspath(file_original_path)
  241.             log(u"getallsubs: Filesearch String = '%s'" % filesearch)
  242.             filesearch = os.path.split(filesearch)
  243.             dirsearch = filesearch[0].split(os.sep)
  244.             log(u"getallsubs: dirsearch = '%s'" % dirsearch)
  245.             dirsearch_check = str.split(dirsearch[-1], '.')
  246.             log(u"getallsubs: dirsearch_check = '%s'" % dirsearch_check)
  247.             #### PARENT FOLDER TWEAK DEFINED IN THE ADD-ON SETTINGS (AUTO | ALWAYS ON (DEACTIVATED) | OFF)
  248.             _parentfolder = _addon.getSetting( 'PARENT' )
  249.             if _parentfolder == '0':
  250.                 if re.search(release_pattern, dirsearch[-1], re.IGNORECASE): _parentfolder = '1'
  251.                 else: _parentfolder = '2'
  252.             if _parentfolder == '1':
  253.                 if re.search(dirsearch[-1], desc, re.IGNORECASE): sync = True
  254.                 else: sync = False
  255.             if _parentfolder == '2':
  256.                 if (searchstring_notclean != ""):
  257.                     sync = False
  258.  
  259.                     if str.lower(searchstring_notclean) in str.lower(desc): sync = True
  260.                 else:
  261.                     if (str.lower(dirsearch_check[-1]) == "rar") or (str.lower(dirsearch_check[-1]) == "cd1") or (str.lower(dirsearch_check[-1]) == "cd2"):
  262.                         sync = False
  263.                         if len(dirsearch) > 1 and dirsearch[1] != '':
  264.                             if re.search(filesearch[1][:len(filesearch[1])-4], desc, re.IGNORECASE) or re.search(dirsearch[-2], desc, re.IGNORECASE): sync = True
  265.                         else:
  266.                             if re.search(filesearch[1][:len(filesearch[1])-4], desc, re.IGNORECASE): sync = True
  267.                     else:
  268.                         sync = False
  269.                         if len(dirsearch) > 1 and dirsearch[1] != '':
  270.                             if re.search(filesearch[1][:len(filesearch[1])-4], desc) or re.search(dirsearch[-1], desc, re.IGNORECASE): sync = True
  271.                         else:
  272.                             if re.search(filesearch[1][:len(filesearch[1])-4], desc, re.IGNORECASE): sync = True
  273.             if _filenameon == "false": filename = "From: " + uploader + " - "  + desc + "  " + "hits: " + hits
  274.             else: filename = "From: " + uploader + " - "  + filename + " " + "(" + movieyear + ")" + "  " + "hits: " + hits + " - " + desc
  275.             subtitles_list.append({'rating': str(downloads), 'filename': filename, 'uploader': uploader, 'desc': desc, 'sync': sync, 'hits' : hits, 'id': id, 'language_short': languageshort, 'language_name': languagelong})
  276.             log(u"getallsubs: SUBS LIST = '%s'" % subtitles_list)
  277.         page = page + 1
  278.        
  279.         if languageshort == "pt": content = urlpost(searchstring, "28", page)
  280.         elif languageshort == "pb": content = urlpost(searchstring, "29", page)
  281.         elif languageshort == "es": content = urlpost(searchstring, "30", page)
  282.         elif languageshort == "en": content = urlpost(searchstring, "31", page)
  283.  
  284. #   Bubble sort, to put syncs on top
  285.     for n in range(0,len(subtitles_list)):
  286.         for i in range(1, len(subtitles_list)):
  287.             temp = subtitles_list[i]
  288.             if subtitles_list[i]["sync"] > subtitles_list[i-1]["sync"]:
  289.                 subtitles_list[i] = subtitles_list[i-1]
  290.                 subtitles_list[i-1] = temp
  291.     return subtitles_list
  292.  
  293. def append_subtitle(item):
  294.    
  295.     listitem = xbmcgui.ListItem(
  296.                    label=item['language_name'],
  297.                    label2=item['filename']
  298.                )
  299.     listitem.setArt( { "icon": str(int(round(float(item["rating"])))), "thumb" : item["language_short"] } )
  300.     listitem.setProperty("sync", 'true' if item["sync"] else 'false')
  301.     listitem.setProperty("hearing_imp", 'true' if item.get("hearing_imp", False) else 'false')
  302.  
  303.     ## below arguments are optional, it can be used to pass any info needed in download function
  304.     ## anything after "action=download&" will be sent to addon once user clicks listed subtitle to downlaod
  305.     args = dict(item)
  306.     args['scriptid'] = _scriptid
  307.     url = INTERNAL_LINK_URL % args
  308.     ## add it to list, this can be done as many times as needed for all subtitles found
  309.     xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False)
  310.  
  311. class Main:
  312.  
  313.     def Search(item):
  314.         """Called when searching for subtitles from KODI."""
  315.         #### Do what's needed to get the list of subtitles from service site
  316.         #### use item["some_property"] that was set earlier
  317.         #### once done, set xbmcgui.ListItem() below and pass it to xbmcplugin.addDirectoryItem()
  318.         #### CHECKING FOR ANYTHING IN THE USERNAME AND PASSWORD, IF NULL IT STOPS THE SCRIPT WITH A WARNING
  319.         username = _addon.getSetting( 'LDuser' )
  320.         password = _addon.getSetting( 'LDpass' )
  321.         if username == '' or password == '':
  322.             xbmcplugin.endOfDirectory(int(sys.argv[1]))
  323.             if username == '' and password != '': xbmc.executebuiltin(('Notification(%s,%s,%d)' % (_scriptname , _language(32016).encode('utf-8'),5000)))
  324.             if username != '' and password == '': xbmc.executebuiltin(('Notification(%s,%s,%d)' % (_scriptname , _language(32017).encode('utf-8'),5000)))
  325.             if username == '' and password == '': xbmc.executebuiltin(('Notification(%s,%s,%d)' % (_scriptname , _language(32018).encode('utf-8'),5000)))
  326.         #### PARENT FOLDER TWEAK DEFINED IN THE ADD-ON SETTINGS (AUTO | ALWAYS ON (DEACTIVATED) | OFF)
  327.         file_original_path = item['file_original_path']
  328.         _parentfolder = _addon.getSetting( 'PARENT' )
  329.         if _parentfolder == '0':
  330.             filename = os.path.abspath(file_original_path)
  331.             dirsearch = filename.split(os.sep)
  332.             log(u"getallsubs: dirsearch string _parentfolder is 0 = %s" % (dirsearch,))
  333.             if re.search(release_pattern, dirsearch[-2], re.IGNORECASE): _parentfolder = '1'
  334.             else: _parentfolder = '2'
  335.         if _parentfolder == '1':
  336.             filename = os.path.abspath(file_original_path)
  337.             dirsearch = filename.split(os.sep)
  338.             filename = dirsearch[-2]
  339.             log(u"getallsubs: filename string _parentfolder is 1 = %s" % (filename,))
  340.         if _parentfolder == '2':  
  341.             filename = os.path.splitext(os.path.basename(file_original_path))[0]
  342.             log(u"getallsubs: filename string _parentfolder is 2 = %s" % (filename,))
  343.      
  344.         filename = xbmc.getCleanMovieTitle(filename)[0] + " " + xbmc.getCleanMovieTitle(filename)[1]
  345.         log(u"Search: FILENAME = %s" % (filename,))
  346.         searchstring_notclean = os.path.splitext(os.path.basename(file_original_path))[0]
  347.         searchstring = ""
  348.         global israr
  349.         israr = os.path.abspath(file_original_path)
  350.         israr = os.path.split(israr)
  351.         israr = israr[0].split(os.sep)
  352.         israr = str.split(israr[-1], '.')
  353.         israr = str.lower(israr[-1])
  354.  
  355.         title = xbmc.getCleanMovieTitle(item['title'])[0]
  356.         year = item['year']
  357.         ## REMOVING THE YEAR FROM THE TV SHOW FOR BETTER MATCH ##
  358.         tvshow = item['tvshow']
  359.         tvshow = tvshow.split('(')
  360.         tvshow = tvshow[0]
  361.         ##########################################################
  362.         season = item['season']
  363.         episode = item['episode']
  364.         log(u"Search: Tvshow string = %s" % (tvshow,))
  365.         log(u"Search: Title string = %s" % (title,))
  366.         subtitles_list = []
  367.        
  368.         if item['mansearch']:
  369.             # searchstring = '"' + item['mansearchstr'] + '"'
  370.             searchstring = item['mansearchstr']
  371.             log(u"Search: Manual String = %s" % (searchstring,))
  372.         else:
  373.             if tvshow != '':
  374.                 searchstring = "%s S%#02dE%#02d" % (tvshow, int(season), int(episode))
  375.                 log(u"Search: Title TV LIBRARY String = %s" % (searchstring,))
  376.             elif title != '' and tvshow == '':
  377.                 # searchstring = '"' + title + ' ' + year + '"'
  378.                 searchstring = title + ' ' + year
  379.                 log(u"Search: Title MOVIE LIBRARY String = %s" % (searchstring,))
  380.             else:
  381.                 if 'rar' in israr and searchstring is not None:
  382.                     log(u"Search: RAR Filename String = %s" % (searchstring,))
  383.                     if 'cd1' in str.lower(title) or 'cd2' in str.lower(title) or 'cd3' in str.lower(title):
  384.                         dirsearch = os.path.abspath(file_original_path)
  385.                         dirsearch = os.path.split(dirsearch)
  386.                         dirsearch = dirsearch[0].split(os.sep)
  387.                         if len(dirsearch) > 1:
  388.                             searchstring_notclean = dirsearch[-3]
  389.                             searchstring = xbmc.getCleanMovieTitle(dirsearch[-3])
  390.                             searchstring = searchstring[0]
  391.                             log(u"Search: RAR MULTI CD String = %s" % (searchstring,))
  392.                         else: searchstring = title
  393.                     else:
  394.                         searchstring = filename
  395.                         log(u"Search: RAR NO MULTI CD String = %s" % (searchstring,))
  396.                 elif 'cd1' in str.lower(title) or 'cd2' in str.lower(title) or 'cd3' in str.lower(title):
  397.                     dirsearch = os.path.abspath(file_original_path)
  398.                     dirsearch = os.path.split(dirsearch)
  399.                     dirsearch = dirsearch[0].split(os.sep)
  400.                     if len(dirsearch) > 1:
  401.                         searchstring_notclean = dirsearch[-2]
  402.                         searchstring = xbmc.getCleanMovieTitle(dirsearch[-2])
  403.                         searchstring = searchstring[0]
  404.                         log(u"Search: MULTI CD String = %s" % (searchstring,))
  405.                     else:
  406.                         #We are at the root of the drive!!! so there's no dir to lookup only file#
  407.                         title = os.path.split(file_original_path)
  408.                         searchstring = title[-1]
  409.                 else:
  410.                     ########## TODO: EXTRACT THE YEAR FROM THE FILENAME AND ADD IT TO THE SEARCH ###########
  411.                     if _search == '0':
  412.                         if re.search("(.+?s[0-9][0-9]e[0-9][0-9])", filename, re.IGNORECASE):
  413.                             searchstring = re.search("(.+?s[0-9][0-9]e[0-9][0-9])", filename, re.IGNORECASE)
  414.                             searchstring = searchstring.group(0)
  415.                             log(u"Search: Filename is TV String (search is 0) = %s" % (searchstring,))
  416.                         else:
  417.                             searchstring = '"' + filename + '"'
  418.                             log(u"Search: Filename is Not TV String (search is 0) = %s" % (searchstring,))
  419.                     else:
  420.                         if re.search("(.+?s[0-9][0-9]e[0-9][0-9])", title, re.IGNORECASE):
  421.                             searchstring = re.search("(.+?s[0-9][0-9]e[0-9][0-9])", title, re.IGNORECASE)
  422.                             searchstring = searchstring.group(0)
  423.                             log(u"Search: Title is TV String (search is 1) = %s" % (searchstring,))
  424.                         else:
  425.                             searchstring = title
  426.                             log(u"Search: Title is Not TV String (search is 1) = %s" % (searchstring,))
  427.  
  428.         PT_ON = _addon.getSetting( 'PT' )
  429.         PTBR_ON = _addon.getSetting( 'PTBR' )
  430.         ES_ON = _addon.getSetting( 'ES' )
  431.         EN_ON = _addon.getSetting( 'EN' )
  432.        
  433.         if 'por' in item['languages'] and PT_ON == 'true':
  434.             subtitles_list = getallsubs(searchstring, "pt", "Portuguese", file_original_path, searchstring_notclean)
  435.             for sub in subtitles_list: append_subtitle(sub)
  436.         if 'por' in item['languages'] and PTBR_ON == 'true':
  437.             subtitles_list = getallsubs(searchstring, "pb", "Brazilian", file_original_path, searchstring_notclean)
  438.             for sub in subtitles_list: append_subtitle(sub)
  439.         if 'spa' in item['languages'] and ES_ON == 'true':
  440.             subtitles_list = getallsubs(searchstring, "es", "Spanish", file_original_path, searchstring_notclean)
  441.             for sub in subtitles_list: append_subtitle(sub)
  442.         if 'eng' in item['languages'] and EN_ON == 'true':
  443.             subtitles_list = getallsubs(searchstring, "en", "English", file_original_path, searchstring_notclean)
  444.             for sub in subtitles_list: append_subtitle(sub)
  445.         if 'eng' not in item['languages'] and 'spa' not in item['languages'] and 'por' not in item['languages'] and 'por' not in item['languages']:
  446.             xbmc.executebuiltin((u'Notification(%s,%s,%d)' % (_scriptname , 'Only Portuguese | Portuguese Brazilian | English | Spanish.',5000)))
  447.  
  448.     def Download(id, filename):
  449.         """Called when subtitle download request from KODI."""
  450.         # Cleanup temp dir, we recomend you download/unzip your subs in temp folder and
  451.         # pass that to XBMC to copy and activate
  452.         if os.path.isdir(_temp):shutil.rmtree(_temp)
  453.         xbmcvfs.mkdirs(_temp)
  454.         if not os.path.isdir(_temp):xbmcvfs.mkdir(_temp)
  455.         unpacked = 'ldivx-' + str(uuid.uuid4()).replace("-","")[0:6]
  456.         xbmcvfs.mkdirs(pjoin(_temp,unpacked,''))
  457.         _newtemp = os.path.join(_temp, xbmc.translatePath(unpacked).replace('\\','/'))
  458.  
  459.         subtitles_list = []
  460.         my_opener = login()
  461.         content = my_opener.open(main_url + 'modules.php?name=Downloads&d_op=getit&lid=' + id + '&username=' + _addon.getSetting( 'LDuser' ))
  462.         content = content.read()
  463.         #### If user is not registered or User\Pass is misspelled it will generate an error message and break the script execution!
  464.         if 'url=sair.php?referer=login' in content.decode('ISO-8859-1'):
  465.             xbmc.executebuiltin(('Notification(%s,%s,%d)' % (_scriptname , _language(32019).encode('utf8'),5000)))
  466.             xbmcplugin.endOfDirectory(int(sys.argv[1]))
  467.         if content.decode('ISO-8859-1') is not None:
  468.             header = content[:4].decode('ISO-8859-1')
  469.             if header == 'Rar!':
  470.                 tmp_file = str(uuid.uuid4())+".rar"
  471.                 local_tmp_file = pjoin(_temp, tmp_file)
  472.                 packed = True
  473.             elif header == 'PK':
  474.                 local_tmp_file = pjoin(_temp, str(uuid.uuid4())+".zip")
  475.                 packed = True
  476.             else:
  477.                 # never found/downloaded an unpacked subtitles file, but just to be sure ...
  478.                 # assume unpacked sub file is an '.srt'
  479.                 local_tmp_file = pjoin(_temp, "ldivx.srt")
  480.                 subs_file = local_tmp_file
  481.                 packed = False
  482.             log(u"Trying to save subtitles to '%s'" % (local_tmp_file,))
  483.             try:
  484.                 with open(local_tmp_file, "wb") as local_file_handle:
  485.  
  486.                     local_file_handle.write(content)
  487.                 local_file_handle.close()
  488.                 xbmc.sleep(500)
  489.             except:
  490.                 log(u"Failed to save subtitles to '%s'" % (local_tmp_file,))
  491.             if packed:
  492.                 try:
  493.                     compressed_file = 'rar://' + quote_plus(local_tmp_file) + '/'
  494.                     log(u"Will try to extract...")
  495.                     xbmc_extract(compressed_file,_newtemp)
  496.                 except:
  497.                     xbmc.executebuiltin("XBMC.Extract(%s, %s)" % (compressed_file, _newtemp), True)
  498.                 ## IF EXTRACTION FAILS, WHICH HAPPENS SOMETIMES ... BUG?? ... WE WILL BROWSE THE RAR FILE FOR MANUAL EXTRACTION ##
  499.                 searchsubs = recursive_glob(_newtemp, SUB_EXTS)
  500.                 searchsubscount = len(searchsubs)
  501.                 if searchsubscount == 0:
  502.                     dialog = xbmcgui.Dialog()
  503.                     subs_file = dialog.browse(1, _language(32024).encode('utf8'), 'files', '', False, True, _temp + '/')
  504.                     subtitles_list.append(subs_file)
  505.                 ## ELSE WE WILL GO WITH THE NORMAL PROCEDURE ##
  506.                 else:
  507.                     os.remove(local_tmp_file)
  508.                     log(u"count: '%s'" % (searchsubscount,))
  509.                     for file in searchsubs:
  510.                         # There could be more subtitle files in _temp, so make
  511.                         # sure we get the newly created subtitle file
  512.                         if searchsubscount == 1:
  513.                             # unpacked file is a newly created subtitle file
  514.                             log(u"Unpacked subtitles file '%s'" % (file,))
  515.                             try:
  516.                                 subs_file = pjoin(_newtemp, file)
  517.                             except:
  518.                                 log(u"Failed to load subtitle file '%s'" % (file,))
  519.                             subtitles_list.append(subs_file)
  520.                             break
  521.                         else:
  522.                         # If there are more than one subtitle in the temp dir, launch a browse dialog
  523.                         # so user can choose.
  524.                             dialog = xbmcgui.Dialog()
  525.                             subs_file = dialog.browse(1, _language(32024).encode('utf8'), 'files', '', False, True, _newtemp + '/')
  526.                             subtitles_list.append(subs_file)
  527.                             break
  528.             else: subtitles_list.append(subs_file)
  529.         return subtitles_list
  530.  
  531.     def get_params():
  532.         param = []
  533.         paramstring = sys.argv[2]
  534.         if len(paramstring) >= 2:
  535.             params = paramstring
  536.             cleanedparams = params.replace('?', '')
  537.             if params.endswith('/'): params = params[:-2] # XXX: Should be [:-1] ?
  538.             pairsofparams = cleanedparams.split('&')
  539.             param = {}
  540.             for pair in pairsofparams:
  541.                 splitparams = {}
  542.                 splitparams = pair.split('=')
  543.                 if len(splitparams) == 2: param[splitparams[0]] = splitparams[1]
  544.         return param
  545.  
  546.     # Get parameters from XBMC and launch actions
  547.     params = get_params()
  548.  
  549.     if params['action'] == 'search' or params['action'] == 'manualsearch':
  550.         item = {}
  551.         item['temp']               = False
  552.         item['rar']                = False
  553.         item['year']               = xbmc.getInfoLabel("VideoPlayer.Year")                           # Year
  554.         item['season']             = str(xbmc.getInfoLabel("VideoPlayer.Season"))                    # Season
  555.         item['episode']            = str(xbmc.getInfoLabel("VideoPlayer.Episode"))                   # Episode
  556.         item['tvshow']             = str(xbmc.getInfoLabel("VideoPlayer.TVshowtitle"))   # Show
  557.         item['title']              = str(xbmc.getInfoLabel("VideoPlayer.OriginalTitle")) # try to get original title
  558.         item['file_original_path'] = urllib.parse.unquote(xbmc.Player().getPlayingFile())  # Full path of a playing file
  559.         item['mansearch'] = False
  560.         item['languages'] = []
  561.  
  562.         if 'searchstring' in params:
  563.             item['mansearch'] = True
  564.             item['mansearchstr'] = urllib.parse.unquote(params['searchstring'])
  565.  
  566.         for lang in urllib.parse.unquote(params['languages']).split(','):
  567.             item['languages'].append(xbmc.convertLanguage(lang, xbmc.ISO_639_2))
  568.  
  569.  
  570.         if "s" in item['episode'].lower():
  571.             # Check if season is "Special"
  572.             item['season'] = "0"
  573.             item['episode'] = item['episode'][-1:]
  574.  
  575.         if "http" in item['file_original_path']: item['temp'] = True
  576.  
  577.         elif "rar://" in item['file_original_path']:
  578.             item['rar'] = True
  579.             item['file_original_path'] = os.path.dirname(item['file_original_path'][6:])
  580.  
  581.         elif "stack://" in item['file_original_path']:
  582.             stackPath = item['file_original_path'].split(" , ")
  583.             item['file_original_path'] = stackPath[0][8:]
  584.  
  585.         Search(item)
  586.  
  587.     elif params['action'] == 'download':
  588.         # we pickup all our arguments sent from def Search()
  589.         subs = Download(params["id"], params["filename"])
  590.         # we can return more than one subtitle for multi CD versions, for now we
  591.         # are still working out how to handle that in XBMC core
  592.         for sub in subs:
  593.             listitem = xbmcgui.ListItem(label=sub)
  594.             xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sub, listitem=listitem, isFolder=False)
  595.  
  596.     # Send end of directory to XBMC
  597.     xbmcplugin.endOfDirectory(int(sys.argv[1]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement