コード例 #1
0
def search_subtitles( file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack ): #standard input
	subtitles_list = []
	msg = ""
	searchstring_notclean = ""
	searchstring = ""
	global israr
	israr = os.path.abspath(file_original_path)
	israr = os.path.split(israr)
	israr = israr[0].split(os.sep)
	israr = string.split(israr[-1], '.')
	israr = string.lower(israr[-1])
	
	if len(tvshow) == 0:
		if 'rar' in israr and searchstring is not None:
			if 'cd1' in string.lower(title) or 'cd2' in string.lower(title) or 'cd3' in string.lower(title):
				dirsearch = os.path.abspath(file_original_path)
				dirsearch = os.path.split(dirsearch)
				dirsearch = dirsearch[0].split(os.sep)
				if len(dirsearch) > 1:
					searchstring_notclean = dirsearch[-3]
					searchstring = xbmc.getCleanMovieTitle(dirsearch[-3])
					searchstring = searchstring[0]
				else:
					searchstring = title
			else:
				searchstring = title
		elif 'cd1' in string.lower(title) or 'cd2' in string.lower(title) or 'cd3' in string.lower(title):
			dirsearch = os.path.abspath(file_original_path)
			dirsearch = os.path.split(dirsearch)
			dirsearch = dirsearch[0].split(os.sep)
			if len(dirsearch) > 1:
				searchstring_notclean = dirsearch[-2]
				searchstring = xbmc.getCleanMovieTitle(dirsearch[-2])
				searchstring = searchstring[0]
			else:
				#We are at the root of the drive!!! so there's no dir to lookup only file#
				title = os.path.split(file_original_path)
				searchstring = title[-1]
		else:
			if title == "":
				title = os.path.split(file_original_path)
				searchstring = title[-1]
			else:
				searchstring = title
			
	if len(tvshow) > 0:
		searchstring = "%s S%#02dE%#02d" % (tvshow, int(season), int(episode))
	log( __name__ ,"%s Search string = %s" % (debug_pretext, searchstring))

	hasLang = languageTranslate(lang1,0,2) + " " + languageTranslate(lang2,0,2) + " " + languageTranslate(lang3,0,2)
	
	if re.search('pt', hasLang) or re.search('en', hasLang) or re.search('es', hasLang) or re.search('pb', hasLang):
		msgnote(debug_pretext,__language__(30153), 6000)
		getallsubs(searchstring, languageTranslate(lang1,0,2), lang1, file_original_path, subtitles_list, searchstring_notclean)
		getallsubs(searchstring, languageTranslate(lang2,0,2), lang2, file_original_path, subtitles_list, searchstring_notclean)
		getallsubs(searchstring, languageTranslate(lang3,0,2), lang3, file_original_path, subtitles_list, searchstring_notclean)
	else:
		msg = "Won't work, LegendasDivx.com is only for PT, PTBR, ES or EN subtitles."

	return subtitles_list, "", msg #standard output
コード例 #2
0
def search_subtitles( file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack ): #standard input
	subtitles_list = []
	msg = ""
	searchstring_notclean = ""
	searchstring = ""
	global israr
	israr = os.path.abspath(file_original_path)
	israr = os.path.split(israr)
	israr = israr[0].split(os.sep)
	israr = string.split(israr[-1], '.')
	israr = string.lower(israr[-1])
	
	if len(tvshow) == 0:
		if 'rar' in israr and searchstring is not None:
			if 'cd1' in string.lower(title) or 'cd2' in string.lower(title) or 'cd3' in string.lower(title):
				dirsearch = os.path.abspath(file_original_path)
				dirsearch = os.path.split(dirsearch)
				dirsearch = dirsearch[0].split(os.sep)
				if len(dirsearch) > 1:
					searchstring_notclean = dirsearch[-3]
					searchstring = xbmc.getCleanMovieTitle(dirsearch[-3])
					searchstring = searchstring[0]
				else:
					searchstring = title
			else:
				searchstring = title
		elif 'cd1' in string.lower(title) or 'cd2' in string.lower(title) or 'cd3' in string.lower(title):
			dirsearch = os.path.abspath(file_original_path)
			dirsearch = os.path.split(dirsearch)
			dirsearch = dirsearch[0].split(os.sep)
			if len(dirsearch) > 1:
				searchstring_notclean = dirsearch[-2]
				searchstring = xbmc.getCleanMovieTitle(dirsearch[-2])
				searchstring = searchstring[0]
			else:
				#We are at the root of the drive!!! so there's no dir to lookup only file#
				title = os.path.split(file_original_path)
				searchstring = title[-1]
		else:
			if title == "":
				title = os.path.split(file_original_path)
				searchstring = title[-1]
			else:
				searchstring = title
			
	if len(tvshow) > 0:
		searchstring = "%s S%#02dE%#02d" % (tvshow, int(season), int(episode))
	log( __name__ ,"%s Search string = %s" % (debug_pretext, searchstring))

	portuguese = 0
	if string.lower(lang1) == "portuguese": portuguese = 1
	elif string.lower(lang2) == "portuguese": portuguese = 2
	elif string.lower(lang3) == "portuguese": portuguese = 3

	getallsubs(searchstring, "pt", "Portuguese", file_original_path, subtitles_list, searchstring_notclean)

	if portuguese == 0:
		msg = "Won't work, LegendasDivx is only for Portuguese subtitles!"
	
	return subtitles_list, "", msg #standard output
コード例 #3
0
ファイル: gui.py プロジェクト: trucer/script.xbmc.subtitles
    def keyboard(self, parent):
        dir, self.year = xbmc.getCleanMovieTitle(
            os.path.split(os.path.split(self.file_original_path)[0])[1])
        if self.rar:
            tmp_dir = os.path.split(
                os.path.split(os.path.split(self.file_original_path)[0])[0])[1]
            dir, self.year = xbmc.getCleanMovieTitle(tmp_dir)
        if not parent:
            kb = xbmc.Keyboard("%s ()" % (dir, ), _(751), False)
            text = self.file_name
            kb.doModal()
            if (kb.isConfirmed()):
                text, self.year = xbmc.getCleanMovieTitle(kb.getText())
            self.title = text
        else:
            self.title = dir

        log(
            __name__, "Manual/Keyboard Entry: Title:[%s], Year: [%s]" % (
                self.title,
                self.year,
            ))
        if self.year != "":
            self.file_name = "%s (%s)" % (
                self.file_name,
                str(self.year),
            )
        else:
            self.file_name = self.title
        self.tvshow = ""
        self.next = list(self.service_list)
        self.Search_Subtitles()
コード例 #4
0
def search_subtitles( file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack ): #standard input
	subtitles_list = []
	msg = ""
	searchstring_notclean = ""
	searchstring = ""
	global israr
	israr = os.path.abspath(file_original_path)
	israr = os.path.split(israr)
	israr = israr[0].split(os.sep)
	israr = string.split(israr[-1], '.')
	israr = string.lower(israr[-1])
	
	if len(tvshow) == 0:
		if 'rar' in israr and searchstring is not None:
			if 'cd1' in string.lower(title) or 'cd2' in string.lower(title) or 'cd3' in string.lower(title):
				dirsearch = os.path.abspath(file_original_path)
				dirsearch = os.path.split(dirsearch)
				dirsearch = dirsearch[0].split(os.sep)
				if len(dirsearch) > 1:
					searchstring_notclean = dirsearch[-3]
					searchstring = xbmc.getCleanMovieTitle(dirsearch[-3])
					searchstring = searchstring[0]
				else:
					searchstring = title
			else:
				searchstring = title
		elif 'cd1' in string.lower(title) or 'cd2' in string.lower(title) or 'cd3' in string.lower(title):
			dirsearch = os.path.abspath(file_original_path)
			dirsearch = os.path.split(dirsearch)
			dirsearch = dirsearch[0].split(os.sep)
			if len(dirsearch) > 1:
				searchstring_notclean = dirsearch[-2]
				searchstring = xbmc.getCleanMovieTitle(dirsearch[-2])
				searchstring = searchstring[0]
			else:
				#We are at the root of the drive!!! so there's no dir to lookup only file#
				title = os.path.split(file_original_path)
				searchstring = title[-1]
		else:
			if title == "":
				title = os.path.split(file_original_path)
				searchstring = title[-1]
			else:
				searchstring = title
			
	if len(tvshow) > 0:
		searchstring = "%s S%#02dE%#02d" % (tvshow, int(season), int(episode))
	log( __name__ ,"%s Search string = %s" % (debug_pretext, searchstring))

	portuguese = 0
	if string.lower(lang1) == "portuguese": portuguese = 1
	elif string.lower(lang2) == "portuguese": portuguese = 2
	elif string.lower(lang3) == "portuguese": portuguese = 3

	getallsubs(searchstring, "pt", "Portuguese", file_original_path, subtitles_list, searchstring_notclean)

	if portuguese == 0:
		msg = "Won't work, LegendasDivx is only for Portuguese subtitles!"
	
	return subtitles_list, "", msg #standard output
コード例 #5
0
  def searchsubtitles( self, item):
    if ( self.osdb_token ) :
      searchlist  = []
      if item['mansearch']:
        OS_search_string = urllib.unquote(item['mansearchstr'])
      elif len(item['tvshow']) > 0:
        OS_search_string = ("%s S%.2dE%.2d" % (item['tvshow'],
                                                int(item['season']),
                                                int(item['episode']),)
                                              ).replace(" ","+")      
      else:
        if str(item['year']) == "":
          item['title'], item['year'] = xbmc.getCleanMovieTitle( item['title'] )
    
        OS_search_string = item['title'].replace(" ","+")
    
      log( __name__ , "Search String [ %s ]" % (OS_search_string,)) 
      if not item['temp']:
        try:
          size, hash = hashFile(item['file_original_path'], item['rar'])
          log( __name__ ,"OpenSubtitles module hash [%s] and size [%s]" % (hash, size,))
          if item['1let_language']:
            searchlist.append({'sublanguageid' :",".join(item['1let_language']), 'moviehash'    :hash, 'moviebytesize':str(size)})		  
          else:
            searchlist.append({'sublanguageid' :",".join(item['3let_language']), 'moviehash'    :hash, 'moviebytesize':str(size) })
        except:
          pass 
		  
      if item['1let_language']:
        searchlist.append({'sublanguageid':",".join(item['1let_language']), 'query'       :OS_search_string })
      else:
        searchlist.append({'sublanguageid':",".join(item['3let_language']), 'query'       :OS_search_string })
      search = self.server.SearchSubtitles( self.osdb_token, searchlist )
      if search["data"]:
        return search["data"] 
コード例 #6
0
ファイル: service.py プロジェクト: teosan5/0
def searchsubtitles(item):
    if len(item['tvshow']) > 0:
        search_string = item['tvshow'].replace(" ", "+")      
    else:
        if str(item['year']) == "":
            item['title'], item['year'] = xbmc.getCleanMovieTitle(item['title'])
        
        search_string = (re.sub('S(\d{1,2})E(\d{1,2})', '', item['title'])).replace(" ", "+")
        search_string = (re.sub('(\+\d{1,4})', '', search_string))
    if item['mansearch']:
        s_string = urllib.unquote(item['mansearchstr'])
        search_string = s_string.replace(" ", "+")
    #log( __name__ , "Search String [ %s ]" % (search_string,))
    link1 = '%sname/json/%s' % (BASE_URL, search_string)
    match = json.loads(get_data(link1))
    if 'error' in match:
        return None
    match = sorted(match, key=itemgetter('edited'), reverse=True)
    #with open('/storage/.kodi/temp/files.py', 'wb') as f: f.write(repr(match[0]))
    if not "error" in match[0]:
        result = []
        for info in match:
            if info['language'] == 'ro':
                nume = info['title'] + ': ' + info['translater'] + ' - ' + info['edited']
                traducator = info['translater']
                legatura = info['download']
                result.append({'SeriesSeason': '0', 'SeriesEpisode': '0', 'LanguageName': 'Romanian', 'episode': '0', 'SubFileName': nume, 'SubRating': '0', 'ZipDownloadLink': legatura, 'ISO639': 'ro', 'SubFormat': 'srt', 'MatchedBy': 'fulltext', 'SubHearingImpaired': '0', 'Traducator': (' ' + traducator)})
        return result
    else:
        return None
コード例 #7
0
  def searchsubtitles( self, item):
    if ( self.osdb_token ) :
      searchlist  = []
      if len(item['tvshow']) > 0:
        OS_search_string = ("%s S%.2dE%.2d" % (item['tvshow'],
                                                int(item['season']),
                                                int(item['episode']),)
                                              ).replace(" ","+")      
      else:
        if str(item['year']) == "":
          item['title'], item['year'] = xbmc.getCleanMovieTitle( item['title'] )
    
        OS_search_string = item['title'].replace(" ","+")
    
      log( __name__ , "Search String [ %s ]" % (OS_search_string,)) 
      if not item['temp']:
        try:
          size, hash = hashFile(item['file_original_path'], item['rar'])
          log( __name__ ,"OpenSubtitles module hash [%s] and size [%s]" % (hash, size,))
          searchlist.append({'sublanguageid' :",".join(item['3let_language']),
                              'moviehash'    :hash,
                              'moviebytesize':str(size)
                              })
        except:
          pass    

      searchlist.append({'sublanguageid':",".join(item['3let_language']),
                          'query'       :OS_search_string
                        })
      search = self.server.SearchSubtitles( self.osdb_token, searchlist )
      if search["data"]:
        return search["data"] 
コード例 #8
0
def search_subtitles(file_original_path, title, tvshow, year, season, episode,
                     set_temp, rar, lang1, lang2, lang3,
                     stack):  #standard input
    ok = False
    msg = ""
    hash_search = False
    osdb_server = OSDBServer()
    subtitles_list = []
    if len(tvshow) > 0:  # TvShow

        OS_search_string = ("%s S%.2dE%.2d" % (
            tvshow,
            int(season),
            int(episode),
        )).replace(" ", "+")
    else:  # Movie or not in Library

        if str(year) == "":  # Not in Library
            title, year = xbmc.getCleanMovieTitle(title)
        else:  # Movie in Library
            year = year
            title = title
        OS_search_string = title.replace(" ", "+")

    log(__name__, "Search String [ %s ]" % (OS_search_string, ))

    if set_temp:
        hash_search = False
        file_size = "000000000"
        hashTry = "000000000000"
    else:
        try:
            try:
                file_size, hashTry = xbmc.subHashAndFileSize(
                    file_original_path)
                log(__name__, "xbmc module hash and size")
            except:
                hashTry = timeout(set_filehash,
                                  args=(file_original_path, rar),
                                  timeout_duration=5)
                file_size = str(os.path.getsize(file_original_path))
            hash_search = True
        except:
            file_size = ""
            hashTry = ""
            hash_search = False

    log(__name__, "File Size [%s]" % file_size)
    log(__name__, "File Hash [%s]" % hashTry)

    log(
        __name__, "Search by hash and name %s" %
        (os.path.basename(file_original_path), ))

    subtitles_list, msg = osdb_server.searchsubtitles(OS_search_string, lang1,
                                                      lang2, lang3,
                                                      hash_search, hashTry,
                                                      file_size)

    return subtitles_list, "", msg  #standard output
コード例 #9
0
def search_filename(filename, languages):
    title, year = xbmc.getCleanMovieTitle(filename)
    log(__name__, "clean title: \"%s\" (%s)" % (title, year))
    try:
        yearval = int(year)
    except ValueError:
        yearval = 0
    if title and yearval > 1900:
        search_string = title + "+" + year
        search_argenteam_api(search_string)
    else:
        match = re.search(
            r'\WS(?P<season>\d\d)E(?P<episode>\d\d)',
            title,
            flags=re.IGNORECASE
        )
        if match is not None:
            tvshow = string.strip(title[:match.start('season')-1])
            season = string.lstrip(match.group('season'), '0')
            episode = string.lstrip(match.group('episode'), '0')
            search_string = "%s S%#02dE%#02d" % (
                tvshow,
                int(season),
                int(episode)
            )
            search_argenteam_api(search_string)
        else:
            search_argenteam_api(filename)
コード例 #10
0
def search_subtitles( file_original_path, title, tvshow, year, season, episode, set_temp, rar, language1, language2, language3, stack ): #standard input
    subtitles_list = []
    msg = ""

    log(__name__, "Search GomTV with a file name, "+file_original_path)
    movieFullPath = xbmc.Player().getPlayingFile()
    video_hash = hashFileMD5( movieFullPath, buff_size=1024*1024 )
    if video_hash is None:
        msg = _(755)
        return subtitles_list, "", msg  #standard output
    webService = GomTvWebService()
    if len(tvshow) > 0:                                            # TvShow
        OS_search_string = ("%s S%.2dE%.2d" % (tvshow,
                                           int(season),
                                           int(episode),)
                                          ).replace(" ","+")      
    else:                                                          # Movie or not in Library
        if str(year) == "":                                          # Not in Library
            title, year = xbmc.getCleanMovieTitle( title )
        else:                                                        # Movie in Library
            year  = year
            title = title
        OS_search_string = title.replace(" ","+")
    subtitles_list = webService.SearchSubtitlesFromTitle( OS_search_string ,video_hash)
    log(__name__, "Found %d subtitles in GomTV" %len(subtitles_list))

    return subtitles_list, "", msg  #standard output
コード例 #11
0
def search_subtitles(file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack): #standard input
    subtitles_list = []
    msg = ""

    if not (string.lower(lang1) or string.lower(lang2) or string.lower(lang3)) == "greek":
        msg = "Won't work, subtitles.gr is only for Greek subtitles."
        return subtitles_list, "", msg #standard output

    try:
        log( __name__ ,"%s Clean title = %s" % (debug_pretext, title))
        premiered = year
        title, year = xbmc.getCleanMovieTitle( title )
    except:
        pass

    if len(tvshow) == 0: # Movie
        searchstring = "%s (%s)" % (title, premiered)
    elif len(tvshow) > 0 and title == tvshow: # Movie not in Library
        searchstring = "%s (%#02d%#02d)" % (tvshow, int(season), int(episode))
    elif len(tvshow) > 0: # TVShow
        searchstring = "%s S%#02dE%#02d" % (tvshow, int(season), int(episode))
    else:
        searchstring = title

    log( __name__ ,"%s Search string = %s" % (debug_pretext, searchstring))
    get_subtitles_list(searchstring, "el", "Greek", subtitles_list)
    return subtitles_list, "", msg #standard output
コード例 #12
0
  def searchsubtitles( self, item):
    if ( self.osdb_token ) :
      searchlist  = []
      if item['mansearch']:
        searchlist = [{'sublanguageid':",".join(item['3let_language']),
                       'query'        :urllib.unquote(item['mansearchstr'])
                      }]
        search = self.server.SearchSubtitles( self.osdb_token, searchlist )
        if search["data"]:
          return search["data"]
        else:
          return None

      if len(item['tvshow']) > 0:
        OS_search_string = ("%s S%.2dE%.2d" % (item['tvshow'],
                                                int(item['season']),
                                                int(item['episode']),)
                                              ).replace(" ","+")      
      else:
        if str(item['year']) == "" and xbmc.Player().isPlaying():
          item['title'], item['year'] = xbmc.getCleanMovieTitle( item['title'] )
    
        OS_search_string = item['title'].replace(" ","+")
    

      log( __name__ , "Search String [ %s ]" % (OS_search_string,))

      if not item['temp']:
        try:
          size, hash = hashFile(item['file_original_path'], item['rar'])
          log( __name__ ,"OpenSubtitles module hash [%s] and size [%s]" % (hash, size,))
          searchlist.append({'sublanguageid' :",".join(item['3let_language']),
                              'moviehash'    :hash,
                              'moviebytesize':str(size)
                            })
        except:
          pass
            
        if xbmc.Player().isPlaying():
            imdb = str(xbmc.Player().getVideoInfoTag().getIMDBNumber().replace('tt',''))
        else:
            imdb = str(xbmc.getInfoLabel("ListItem.IMDBNumber").replace('tt',''))
        
        if ((not item['tvshow']) and imdb != ""):
          searchlist.append({'sublanguageid' :",".join(item['3let_language']),
                             'imdbid'        :imdb
                            })

        searchlist.append({'sublanguageid':",".join(item['3let_language']),
                          'query'        :OS_search_string
                         }) 
      
      else:
        searchlist = [{'sublanguageid':",".join(item['3let_language']),
                       'query'        :OS_search_string
                      }]

      search = self.server.SearchSubtitles( self.osdb_token, searchlist )
      if search["data"]:
        return search["data"] 
コード例 #13
0
def search_manual(searchstr, languages, filename):
    title, year = xbmc.getCleanMovieTitle(searchstr)
    log(__name__, "Search movie = %s" % title)
    url = main_url + "/subtitles/searching?q=" + urllib.quote_plus(
        title) + '&r=true'
    content, resp = geturl(url)
    if content is not None:

        log(__name__, "Multiple movies found, searching for the right one ...")
        subspage_url = find_movie(content, title, year)
        if subspage_url is not None:
            log(__name__, "Movie found in list, getting subs ...")
            url = main_url + subspage_url
            getallsubs(url, languages, filename)
        else:
            log(__name__, "Movie not found in list: %s" % title)
            if string.find(string.lower(title), "&") > -1:
                title = string.replace(title, "&", "and")
                log(__name__,
                    "Trying searching with replacing '&' to 'and': %s" % title)
                subspage_url = find_movie(content, title, year)
                if subspage_url is not None:
                    log(__name__, "Movie found in list, getting subs ...")
                    url = main_url + subspage_url
                    getallsubs(url, languages, filename)
                else:
                    log(__name__, "Movie not found in list: %s" % title)
            else:
                mess(u'Lỗi khi tìm với Subscene, thử với OpenSubtitles')
                OSSearch(item)
コード例 #14
0
def search_filename(filename, languages):
    title, year = xbmc.getCleanMovieTitle(filename)
    title = re.sub('&#.* ', '', title.replace("&", "and")).strip()
    title = ' '.join(s for s in title.split())
    log(__name__, "clean title: \"%s\" (%s)" % (title, year))
    try:
        yearval = int(year)
    except ValueError:
        yearval = 0
    if re.search('[S|s]\d\d', filename):
        newtitle = ' '.join(s for s in title.split()
                            if not re.search('[S|s]\d\d', s))
        newtitle = '%s %s Season' % (newtitle, seasonsc[re.search(
            '[S|s](\d\d)', filename).group(1)])
    match = re.search(r'\WS(?P<season>\d\d)E(?P<episode>\d\d)',
                      filename,
                      flags=re.IGNORECASE)
    if match is not None:
        tvshow = string.strip(title[:match.start('season') - 1])
        season = string.lstrip(match.group('season'), '0')
        episode = string.lstrip(match.group('episode'), '0')
        search_tvshow(tvshow, season, episode, languages, filename)
    elif title and yearval > 1900:
        search_movie(title, year, languages, filename)
    else:
        search_manual(filename, languages, filename)
コード例 #15
0
def search_filename(filename, languages):
    title, year = xbmc.getCleanMovieTitle(filename)
    log(__name__, "clean title: \"%s\" (%s)" % (title, year))
    try:
        yearval = int(year)
    except ValueError:
        yearval = 0
    if title and yearval > 1900:
        search_string = title + "+" + year
        search_argenteam_api(search_string)
    else:
        match = re.search(
            r'\WS(?P<season>\d\d)E(?P<episode>\d\d)',
            title,
            flags=re.IGNORECASE
        )
        if match is not None:
            tvshow = title[:match.start('season') - 1].strip()
            season = match.group('season').lstrip('0')
            episode = match.group('episode').lstrip('0')
            search_string = "%s S%#02dE%#02d" % (
                tvshow,
                int(season),
                int(episode)
            )
            search_argenteam_api(search_string)
        else:
            search_argenteam_api(filename)
コード例 #16
0
def setup_tvshow_data(item):
    tvshow = normalize_string(xbmc.getInfoLabel("VideoPlayer.TVshowtitle"))
    if tvshow:
        item['tvshow'] = tvshow
        item['season'] = str(xbmc.getInfoLabel("VideoPlayer.Season"))
        item['episode'] = str(xbmc.getInfoLabel("VideoPlayer.Episode"))
    else:
        infos = xbmc.getCleanMovieTitle(item['file_original_path'], True)

        if not 'year' in item or not item['year']:
            item['year'] = infos[1]

        title_pattern = r'^(?P<title>.+)S(?P<season>\d+)E(?P<episode>\d+)$'
        title_match = re.search(title_pattern, infos[0], re.IGNORECASE)

        if title_match:
            item['tvshow'] = title_match.group('title').strip()
            item['season'] = title_match.group('season')
            item['episode'] = title_match.group('episode')
        else:
            item['tvshow'] = infos[0]

            filename_pattern = r'^(.*)S(?P<season>\d+)E(?P<episode>\d+)(.*)$'
            filename_match = re.search(filename_pattern, item['filename'], re.IGNORECASE)

            if filename_match:
                item['season'] = filename_match.group('season')
                item['episode'] = filename_match.group('episode')

    return item
コード例 #17
0
def search_subtitles(file_original_path, title, tvshow, year, season, episode,
                     set_temp, rar, lang1, lang2, lang3,
                     stack):  #standard input
    subtitles_list = []
    msg = ""

    if not (string.lower(lang1) or string.lower(lang2)
            or string.lower(lang3)) == "greek":
        msg = "Won't work, subs4free is only for Greek subtitles."
        return subtitles_list, "", msg  #standard output

    try:
        log(__name__, "%s Clean title = %s" % (debug_pretext, title))
        premiered = year
        title, year = xbmc.getCleanMovieTitle(title)
    except:
        pass

    content = 1
    if len(tvshow) == 0:  # Movie
        searchstring = "%s (%s)" % (title, premiered)
    elif len(tvshow) > 0 and title == tvshow:  # Movie not in Library
        searchstring = "%s (%#02d%#02d)" % (tvshow, int(season), int(episode))
    elif len(tvshow) > 0:  # TVShow
        searchstring = "%s S%#02dE%#02d" % (tvshow, int(season), int(episode))
        content = 2
    else:
        searchstring = title

    log(__name__, "%s Search string = %s" % (debug_pretext, searchstring))
    if content == 1:
        get_movie_subtitles_list(searchstring, "el", "Greek", subtitles_list)
    else:
        get_tvshow_subtitles_list(searchstring, "el", "Greek", subtitles_list)
    return subtitles_list, "", msg  #standard output
コード例 #18
0
def Search(item):
    convertASS = (__addon__.getSetting("convertASS") == "true")

    xbmc.log("Search GomTV with a file name, " +
             item['file_original_path'].encode('cp949', 'ignore'),
             level=xbmc.LOGDEBUG)
    video_hash = hashFileMD5(item['file_original_path'], buff_size=1024 * 1024)
    if video_hash is None:
        xbmc.log(u"Fail to access movie flie, " +
                 item['file_original_path'].encode('cp949', 'ignore'),
                 level=xbmc.LOGERROR)
        return

    #q_url = "http://gom.gomtv.com/jmdb/search.html?key=%s" %video_hash
    video_hash = item['title'].encode('cp949', 'ignore').replace(' ', '+')
    q_url = "https://www.gomlab.com/subtitle/?preface=kr&keyword=%s" % video_hash
    subtitles_list = SearchSubtitles(q_url)

    if not subtitles_list:
        xbmc.log("No result with hash, " + video_hash, level=xbmc.LOGNOTICE)
        if item['tvshow']:
            search_string = ("%s S%.2dE%.2d" %
                             (item['tvshow'], int(item['season']),
                              int(item['episode']))).replace(" ", "+")
        else:
            if str(item['year']) == "":
                item['title'], item['year'] = xbmc.getCleanMovieTitle(
                    item['title'])
            # use English title if available
            query = ENG_TITLE_PTN.match(item['title'])
            srch_title = query.group(2).strip() if query else item['title']
            search_string = srch_title.replace(" ", "+")

        #q_url = "http://gom.gomtv.com/main/index.html?ch=subtitles&pt=l&menu=subtitles&lang=0&sValue=%s" %search_string
        q_url = "https://www.gomlab.com/subtitle/?preface=kr&keyword=%s" % search_string
        subtitles_list = SearchSubtitles(q_url)

    xbmc.log("Found %d subtitles in GomTV" % len(subtitles_list),
             level=xbmc.LOGINFO)
    for sub in subtitles_list:
        listitem = xbmcgui.ListItem(
            label=sub['language_name'],
            label2=sub['filename'],
            iconImage=sub['rating'],
            thumbnailImage=sub['language_flag'],
        )
        listitem.setProperty("sync", 'true' if sub["sync"] else 'false')
        listitem.setProperty(
            "hearing_imp",
            'true' if sub.get("hearing_imp", False) else 'false')

        url = "plugin://%s/?action=download&link=%s&ID=%s&filename=%s&format=%s" % (
            __scriptid__, urllib.quote(sub["link"]), sub["ID"],
            sub["filename"], 'ass' if convertASS else sub["format"])
        #url = "plugin://%s/?action=download&link=%s" % (__scriptid__,urllib.quote(sub["link"]))
        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                    url=url,
                                    listitem=listitem,
                                    isFolder=False)
コード例 #19
0
    def search(self, item):

        if item['mansearch']:
            title = item['mansearchstr']
        elif item['tvshow']:
            title = "%s S%02dE%02d" % (self.normalize_input_title(
                item['tvshow']), int(item['season']), int(item['episode'])
                                       )  # Searching TV Show
        else:  # Searching movie
            title = item['title'] if item['year'] else xbmc.getCleanMovieTitle(
                item['title'])[0]
            title = self.normalize_input_title(title)

        log(__name__, "Search pattern: " + title)

        found_subtitles = self.search_subtitle(title)
        log(__name__, "Parsed subtitles: %s" % found_subtitles)

        lang_filetred_found_subtitles = self.filter_subtitles_by_language(
            item['3let_language'], found_subtitles)
        log(__name__, ["Language filter", lang_filetred_found_subtitles])
        if not lang_filetred_found_subtitles:
            return results_with_stats(None, self.addon, title, item)

        file_size = get_file_size(item['file_original_path'], item['rar'])
        if not (file_size == -1):
            file_size = round(float(file_size) / (1024 * 1024), 2)
        log(__name__, "File size: %s" % file_size)

        max_down_count = self.detect_max_download_stats(
            lang_filetred_found_subtitles)

        result_subtitles = []
        for found_subtitle in lang_filetred_found_subtitles:
            print_out_filename = (
                found_subtitle['version'],
                found_subtitle['title'])[found_subtitle['version'] == ''
                                         or found_subtitle['version'] == None]
            if not found_subtitle['author'] == None:
                print_out_filename += " by " + found_subtitle['author']
            result_subtitles.append({
                'filename':
                HTMLParser.HTMLParser().unescape(print_out_filename),
                'id':
                found_subtitle['id'],
                'lang':
                found_subtitle['lang'],
                'rating':
                str(found_subtitle['down_count'] * 5 /
                    max_down_count) if max_down_count > 0 else "0",
                'sync': (found_subtitle['size'] == file_size
                         and file_size > 0),
                'lang_flag':
                xbmc.convertLanguage(found_subtitle['lang'], xbmc.ISO_639_1),
            })

        log(__name__, ["Search result", result_subtitles])

        return results_with_stats(result_subtitles, self.addon, title, item)
コード例 #20
0
def search_filename(filename, languages):
  title, year = xbmc.getCleanMovieTitle(filename)
  log(__name__, "clean title: \"%s\" (%s)" % (title, year))
  try:
    yearval = int(year)
  except ValueError:
    yearval = 0
  if title and yearval > 1900:
    query_Film(title, year, item['3let_language'], filename)
コード例 #21
0
def getDataforTrakt(params, data=None):
    if not data: data = {}
    try: params=json.loads(params)
    except: pass
    paramss = params.get('info')
    infos = paramss
    season = infos.get('Season')
    episode = infos.get('Episode')
    showtitle = infos.get('TVshowtitle') if infos.get('TVshowtitle') else (infos.get('TVShowtitle') if infos.get('TVShowtitle') else infos.get('TVShowTitle'))
    year = infos.get('Year')
    title = infos.get('Title')
    try:
        if title and not showtitle and not season and not episode and not year:
            if re.search('–|-|~', title):
                all_name = re.split(r'–|-|:|~', title,1)
                title = all_name[0]
                title2 = all_name[1]
            else: title2 = ''
            title, year = xbmc.getCleanMovieTitle(title)
            title2, year2 = xbmc.getCleanMovieTitle(title2)
            title = title if title else title2
            year = year if year else year2
        if year:
            try: year = int(year)
            except: pass
        if season and episode and showtitle:
            data['show'] = {"title": showtitle, "year": year}
            season = int(season)
            episode = int(episode)
            data['episode'] = {"season": season, "number": episode}
        elif year and not season and not showtitle:
            data['movie'] = {"title": title, "year": year}
        elif showtitle:
            title, season, episode = regex_tvshow(showtitle)
            if season and episode:
                data['show'] = {"title": showtitle, "year": '%s' % year if year else ''}
                data['episode'] = {"season": season, "number": episode}
        elif title and not showtitle and not season and not episode:
            if year: data['movie'] = {"title": title, 'year': year}
            else: data['movie'] = {"title": title}
    except: pass
    return data
コード例 #22
0
def _find_existing(basedir, name, uniqueslug=None, mediayear=None, files=False):
    for item in get_cached_listdir(basedir)[1 if files else 0]:
        cleantitle, diryear = xbmc.getCleanMovieTitle(item) if mediayear else (item, '')
        if diryear and int(diryear) != mediayear:
            continue
        if files:
            item = item.rsplit('-', 1)[0]
        for title in utils.iter_possible_cleannames(name, uniqueslug):
            if title in (cleantitle, item):
                return item
    return None
コード例 #23
0
def search_movie(title, year, languages, filename):
    title = string.strip(title)

    log(__name__, "Search movie = %s" % title)
    res = search_manual(title, languages, filename)
    for result in res:
        rtitle, ryear = xbmc.getCleanMovieTitle(result['filename'])
        rtitle, ryear = rtitle.strip().lower(), ryear.strip().lower()
        log(__name__, "Got cleaned movie result of %s (%s) '%s'" % (rtitle, ryear, result['filename']))
        if (rtitle, ryear) == (title, year):
            yield result
コード例 #24
0
def search_subtitles( file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack ): #standard input
    msg = ""
    subtitles_list = []
    search_url = "http://api.titlovi.com/xml_get_api.ashx?x-dev_api_id=%s&keyword=%s&uiculture=en"
    languages = [lang1, lang2, lang3]

    if len(tvshow) > 0:                                              # TvShow
        search_string = ("%s S%.2dE%.2d" % (tvshow,
                                            int(season), 
                                            int(episode),)
                                            ).replace(" ","+")      
    else:                                                            # Movie or not in Library
        if str(year) == "":                                          # Not in Library
            title, year = xbmc.getCleanMovieTitle( title )
        else:                                                        # Movie in Library
            year  = year
            title = title
        search_string = title.replace(" ","+")
    log( __name__ , "Search String [ %s ]" % (search_string,))
    subtitles = minidom.parseString(
                        geturl(search_url % (
                               base64.b64decode(KEY)[::-1], search_string))
                               ).getElementsByTagName("subtitle")
    if subtitles:
      url_base = "http://en.titlovi.com/downloads/default.ashx?type=1&mediaid=%s"
      for subtitle in subtitles:
        lang = subtitle.getElementsByTagName("language")[0].firstChild.data
        if lang == "rs": lang = "sr"
        if lang == "ba": lang = "bs"
        if lang == "si": lang = "sl"
        lang_full = languageTranslate(lang, 2,0)
        if lang_full in languages:
            sub_id = subtitle.getElementsByTagName("url")[0].firstChild.data
            movie = subtitle.getElementsByTagName("safeTitle")[0].firstChild.data
            if subtitle.getElementsByTagName("release")[0].firstChild:
                filename = "%s - %s" % (movie, subtitle.getElementsByTagName("release")[0].firstChild.data)
            else:
                filename = movie  
            rating = int(float(subtitle.getElementsByTagName("score")[0].firstChild.data)*2)
            flag_image = "flags/%s.gif" % lang
            link = url_base % sub_id.split("-")[-1].replace("/","")            
            subtitles_list.append({'filename'     :filename,
                                   'link'         :link,
                                   'language_name':lang_full,
                                   'language_id'  :lang,
                                   'language_flag':flag_image,
                                   'movie'        :movie,
                                   'rating'       :str(rating),
                                   'sync'         :False
                                   })

    subtitles_list = sorted(subtitles_list, compare_columns)
    return subtitles_list, "", msg #standard output
コード例 #25
0
ファイル: gui.py プロジェクト: Saviq/script.xbmc.subtitles
  def keyboard(self, parent):
    dir, self.year = xbmc.getCleanMovieTitle(os.path.split(os.path.split(self.file_original_path)[0])[1])
    if self.rar:
      tmp_dir = os.path.split(os.path.split(os.path.split(self.file_original_path)[0])[0])[1]
      dir, self.year = xbmc.getCleanMovieTitle( tmp_dir )
    if not parent:
      kb = xbmc.Keyboard("%s ()" % (dir,), _( 751 ), False)
      text = self.file_name
      kb.doModal()
      if (kb.isConfirmed()): text, self.year = xbmc.getCleanMovieTitle(kb.getText())
      self.title = text
    else:
      self.title = dir   

    log( __name__ ,"Manual/Keyboard Entry: Title:[%s], Year: [%s]" % (self.title, self.year,))
    if self.year != "" :
      self.file_name = "%s (%s)" % (self.file_name, str(self.year),)
    else:
      self.file_name = self.title   
    self.tvshow = ""
    self.Search_Subtitles()
コード例 #26
0
  def searchsubtitles(self, item):
    #print ("searchsubtitles 1")

    if item['mansearch']:
      searchParams = {'m' : urllib.unquote(item['mansearchstr']), 
	                            'l' : '0', 
								'c' : '', 
								'y' : '0', 
								'a' : '',
								'd' : '',
								'u' : '',
								'g' : '',
								't' : 'Submit'}
      print ("manual search: %s" % searchParams)
    elif len(item['tvshow']) > 0:
      searchParams = {'m' : ("%s %.2dx%.2d" % (item['tvshow'],
                                                int(item['season']),
                                                int(item['episode']))), 
								'l' : '0', 
								'c' : '', 
								'y' : '0', 
								'a' : '',
								'd' : '',
								'u' : '',
								'g' : '',
								't' : 'Submit'}
      print ("tvshow search: %s" % searchParams)
    else:
      if str(item['year']) == "":
        item['title'], item['year'] = xbmc.getCleanMovieTitle(item['title'])
	  
      if str(item['year']) == "":
        item['year'] = '0'

      searchParams = {'m' : item['title'], 
								'l' : '0', 
								'c' : '', 
								'y' : '0', 
								'a' : '',
								'd' : '',
								'u' : '',
								'g' : '',
								't' : 'Submit'}
      print ("title search: %s" % searchParams)

    log( __name__ , "Search Parameters [ %s ]" % (str(searchParams))) 

    result = self.handleSearch(searchParams)
    return result
コード例 #27
0
ファイル: service.py プロジェクト: myvideolibrary/mvl-play
def search_subtitles(file_original_path, title, tvshow, year, season, episode,
                     set_temp, rar, lang1, lang2, lang3,
                     stack):  #standard input
    ok = False
    msg = ""
    hash_search = False
    subtitles_list = []
    if len(tvshow) > 0:  # TvShow
        OS_search_string = ("%s S%.2dE%.2d" % (
            tvshow,
            int(season),
            int(episode),
        )).replace(" ", "+")
    else:  # Movie or not in Library
        if str(year) == "":  # Not in Library
            title, year = xbmc.getCleanMovieTitle(title)
        else:  # Movie in Library
            year = year
            title = title
        OS_search_string = title.replace(" ", "+")
    log(__name__, "Search String [ %s ]" % (OS_search_string, ))

    if set_temp:
        hash_search = False
        file_size = "000000000"
        SubHash = "000000000000"
    else:
        try:
            file_size, SubHash = hashFile(file_original_path, rar)
            log(__name__, "xbmc module hash and size")
            hash_search = True
        except:
            file_size = ""
            SubHash = ""
            hash_search = False

    if file_size != "" and SubHash != "":
        log(__name__, "File Size [%s]" % file_size)
        log(__name__, "File Hash [%s]" % SubHash)

    log(
        __name__, "Search by hash and name %s" %
        (os.path.basename(file_original_path), ))
    subtitles_list, msg = OSDBServer().searchsubtitles(OS_search_string, lang1,
                                                       lang2, lang3,
                                                       hash_search, SubHash,
                                                       file_size)

    return subtitles_list, "", msg  #standard output
コード例 #28
0
ファイル: gui.py プロジェクト: slmosl/script.xbmc.subtitles
  def keyboard(self, parent):
    dir, self.year = xbmc.getCleanMovieTitle(self.file_original_path, self.parsearch)
    if not parent:
      if self.man_search_str != "":
        srchstr = self.man_search_str
      else:
        srchstr = "%s (%s)" % (dir,self.year)
      kb = xbmc.Keyboard(srchstr, _( 751 ), False)
      text = self.file_name
      kb.doModal()
      if (kb.isConfirmed()): text, self.year = xbmc.getCleanMovieTitle(kb.getText())
      self.title = text
      self.man_search_str = text
    else:
      self.title = dir

    log( __name__ ,"Manual/Keyboard Entry: Title:[%s], Year: [%s]" % (self.title, self.year))
    if self.year != "" :
      self.file_name = "%s (%s)" % (self.file_name, str(self.year))
    else:
      self.file_name = self.title
    self.tvshow = ""
    self.next = list(self.service_list)
    self.Search_Subtitles()
コード例 #29
0
  def keyboard(self, parent):
    dir, self.year = xbmc.getCleanMovieTitle(self.file_original_path, self.parsearch)
    if not parent:
      if self.man_search_str != "":
        srchstr = self.man_search_str
      else:
        srchstr = "%s (%s)" % (dir,self.year,)  
      kb = xbmc.Keyboard(srchstr, _( 751 ), False)
      text = self.file_name
      kb.doModal()
      if (kb.isConfirmed()): text, self.year = xbmc.getCleanMovieTitle(kb.getText())
      self.title = text
      self.man_search_str = text
    else:
      self.title = dir   

    log( __name__ ,"Manual/Keyboard Entry: Title:[%s], Year: [%s]" % (self.title, self.year,))
    if self.year != "" :
      self.file_name = "%s (%s)" % (self.file_name, str(self.year),)
    else:
      self.file_name = self.title   
    self.tvshow = ""
    self.next = list(self.service_list)
    self.Search_Subtitles() 
コード例 #30
0
ファイル: SubtitleHelper.py プロジェクト: roeiba/xbmc
def build_search_string(item):
    if item['mansearch']:
        search_string = urllib.unquote(item['mansearchstr'])
    elif len(item['tvshow']) > 0:
        search_string = ("%s S%.2dE%.2d" % (item['tvshow'],
                                                int(item['season']),
                                                int(item['episode']),)
                                              ).replace(" ","+")      
    else:
        if str(item['year']) == "":
          item['title'], item['year'] = xbmc.getCleanMovieTitle( item['title'] )
    
        search_string = item['title'].replace(" ","+")
    
    log( __name__ , "Search String [ %s ]" % (search_string,)) 
    return search_string
コード例 #31
0
ファイル: service.py プロジェクト: noba3/KoTos
def clean_movie_title(item, use_dir):
    debuglog("getCleanMovieTitle:  %s" % use_dir)
    infos = xbmc.getCleanMovieTitle(item['file_original_path'], use_dir)

    if not 'year' in item or not item['year']:
        item['year'] = infos[1]

    title_pattern = r'^(?P<title>.+)S(?P<season>\d+)E(?P<episode>\d+).*$'
    title_match = re.search(title_pattern, infos[0], re.IGNORECASE)

    if title_match:
        item['tvshow'] = title_match.group('title').strip()
        item['season'] = title_match.group('season')
        item['episode'] = title_match.group('episode')

    return infos, (title_match is not None)
コード例 #32
0
ファイル: service.py プロジェクト: noba3/KoTos
def clean_movie_title(item, use_dir):
    debuglog("getCleanMovieTitle:  %s" % use_dir)
    infos = xbmc.getCleanMovieTitle(item['file_original_path'], use_dir)

    if not 'year' in item or not item['year']:
        item['year'] = infos[1]

    title_pattern = r'^(?P<title>.+)S(?P<season>\d+)E(?P<episode>\d+).*$'
    title_match = re.search(title_pattern, infos[0], re.IGNORECASE)

    if title_match:
        item['tvshow'] = title_match.group('title').strip()
        item['season'] = title_match.group('season')
        item['episode'] = title_match.group('episode')

    return infos, (title_match is not None)
コード例 #33
0
ファイル: service.py プロジェクト: fuex80/xbmc-korean
def Search( item ):
    convertASS = (__addon__.getSetting("convertASS") == "true")

    xbmc.log("Search GomTV with a file name, "+item['file_original_path'].encode('cp949', 'ignore'), level=xbmc.LOGDEBUG)
    video_hash = hashFileMD5( item['file_original_path'], buff_size=1024*1024 )
    if video_hash is None:
        xbmc.log(u"Fail to access movie flie, "+item['file_original_path'].encode('cp949', 'ignore'), level=xbmc.LOGERROR)
        return

    q_url = "http://gom.gomtv.com/jmdb/search.html?key=%s" %video_hash
    subtitles_list = SearchSubtitles( q_url )

    if not subtitles_list:
        xbmc.log("No result with hash, "+video_hash, level=xbmc.LOGNOTICE)
        if item['tvshow']:
            search_string = ("%s S%.2dE%.2d" %
                (item['tvshow'], int(item['season']), int(item['episode']))).replace(" ","+")
        else:
            if str(item['year']) == "":
                item['title'], item['year'] = xbmc.getCleanMovieTitle( item['title'] )
            # use English title if available
            query = ENG_TITLE_PTN.match(item['title'])
            srch_title = query.group(2).strip() if query else item['title']
            search_string = srch_title.replace(" ","+")

        q_url = "http://gom.gomtv.com/main/index.html?ch=subtitles&pt=l&menu=subtitles&lang=0&sValue=%s" %search_string
        subtitles_list = SearchSubtitles( q_url )

    xbmc.log("Found %d subtitles in GomTV" %len(subtitles_list), level=xbmc.LOGINFO)
    for sub in subtitles_list:
        listitem = xbmcgui.ListItem(
                        label=sub['language_name'],
                        label2=sub['filename'],
                        iconImage=sub['rating'],
                        thumbnailImage=sub['language_flag'],
                    )
        listitem.setProperty("sync", 'true' if sub["sync"] else 'false')
        listitem.setProperty("hearing_imp", 'true' if sub.get("hearing_imp", False) else 'false')

        url = "plugin://%s/?action=download&link=%s&ID=%s&filename=%s&format=%s" % (__scriptid__,
                            urllib.quote(sub["link"]),
                            sub["ID"],
                            sub["filename"],
                            'ass' if convertASS else sub["format"]
                            )
        xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False)
コード例 #34
0
ファイル: service.py プロジェクト: 070499/repo-scripts
def search_subtitles( file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack ): #standard input
    ok = False
    msg = ""
    hash_search = False
    osdb_server = OSDBServer()
    subtitles_list = []  
    if len(tvshow) > 0:                                              # TvShow

        OS_search_string = ("%s S%.2dE%.2d" % (tvshow, int(season), int(episode),)).replace(" ","+")      
    else:                                                            # Movie or not in Library

        if str(year) == "":                                          # Not in Library
                title, year = xbmc.getCleanMovieTitle( title )
        else:                                                        # Movie in Library
                year  = year
                title = title
        OS_search_string = title.replace(" ","+")
    
    log( __name__ , "Search String [ %s ]" % (OS_search_string,))     
    
    if set_temp : 
        hash_search = False
        file_size = "000000000"
        hashTry = "000000000000"
    else:
        try:
          try:
            file_size, hashTry   = xbmc.subHashAndFileSize(file_original_path)
            log( __name__ ,"xbmc module hash and size")
          except:  
            hashTry = timeout(set_filehash, args=(file_original_path, rar), timeout_duration=5)
            file_size = str(os.path.getsize( file_original_path ))
          hash_search = True
        except: 
          file_size = ""
          hashTry = ""
          hash_search = False 
    
    log( __name__ ,"File Size [%s]" % file_size)
    log( __name__ ,"File Hash [%s]" % hashTry)
    
    log( __name__ ,"Search by hash and name %s" % (os.path.basename( file_original_path ),))

    subtitles_list, msg = osdb_server.searchsubtitles( OS_search_string, lang1, lang2, lang3, hash_search, hashTry, file_size  )
        
    return subtitles_list, "", msg #standard output
コード例 #35
0
ファイル: service.py プロジェクト: azumimuo/family-xbmc-addon
def search_filename(filename, languages):
    title, year = xbmc.getCleanMovieTitle(filename)
    log(__name__, "clean title: \"%s\" (%s)" % (title, year))
    try:
        yearval = int(year)
    except ValueError:
        yearval = 0
    match = re.search(r'\WS(?P<season>\d\d)E(?P<episode>\d\d)', filename, flags=re.IGNORECASE)
    if match is not None:
        tvshow = string.strip(title[:match.start('season') - 1])
        season = string.lstrip(match.group('season'), '0')
        episode = string.lstrip(match.group('episode'), '0')
        search_tvshow(tvshow, season, episode, languages, filename)
    elif title and yearval > 1900:
        search_movie(title, year, languages, filename)
    else:
        search_manual(filename, languages, filename)
コード例 #36
0
def search_filename(filename, languages):
    title, year = xbmc.getCleanMovieTitle(filename)
    log(__name__, "clean title: \"%s\" (%s)" % (title, year))
    try:
        yearval = int(year)
    except ValueError:
        yearval = 0
    match = re.search(r'\WS(?P<season>\d\d)E(?P<episode>\d\d)', filename, flags=re.IGNORECASE)
    if match is not None:
        tvshow = string.strip(title[:match.start('season') - 1])
        season = string.lstrip(match.group('season'), '0')
        episode = string.lstrip(match.group('episode'), '0')
        search_tvshow(tvshow, season, episode, languages, filename)
    elif title and yearval > 1900:
        search_movie(title, year, languages, filename)
    else:
        search_manual(filename, languages, filename)
コード例 #37
0
def search_filename(filename, languages):
    title, year = xbmc.getCleanMovieTitle(filename)
    log(__name__, 'clean title: "%s" (%s)' % (title, year))
    try:
        yearval = int(year)
    except ValueError:
        yearval = 0
    if title and yearval > 1900:
        query_Film(title, year, item["3let_language"], filename)
    else:
        match = re.search(r"\WS(?P<season>\d\d)E(?P<episode>\d\d)", title, flags=re.IGNORECASE)
        if match is not None:
            tvshow = string.strip(title[: match.start("season") - 1])
            season = string.lstrip(match.group("season"), "0")
            episode = string.lstrip(match.group("episode"), "0")
            query_TvShow(tvshow, season, episode, item["3let_language"], filename)
        else:
            search_manual(filename, item["3let_language"], filename)
コード例 #38
0
ファイル: main.py プロジェクト: teosan5/0
def whattoplay(originalname, url, imdb_id, year):
    if getSetting("playwhat") == 'Torrenter':
        tor_title, tor_year = xbmc.getCleanMovieTitle(originalname)
        xbmc.executebuiltin(
            'xbmc.RunPlugin(plugin://plugin.video.torrenter/?action=searchWindow&mode=search&query=%s)'
            % (tor_title))
    else:
        if url <> 'external':
            try:
                url = xbmc.getInfoLabel('ListItem.Trailer').split(
                    'videoid=')[1]
            except:
                url = ''
        if AddonsResolver == False: youtube.playtrailer(url, originalname)
        else:
            if getSetting("playwhat") == 'Trailer':
                youtube.playtrailer(url, originalname)
            else:
                play.play_stream(originalname, url, imdb_id, year)
コード例 #39
0
def Search(item):
    it = []
    _item = dict(item)
    it.append(item)
    _item['title'], _item['year'] = xbmc.getCleanMovieTitle(item['title'])
    it.append(_item)

    sub_data = read_sub(*it)
    #### Do whats needed to get the list of subtitles from service site
    #### use item["some_property"] that was set earlier
    #### once done, set xbmcgui.ListItem() below and pass it to xbmcplugin.addDirectoryItem()
    if sub_data != None:
        log_my(sub_data)
        for it in sub_data:
            listitem = xbmcgui.ListItem(
                label=it['id'],  # language name for the found subtitle
                label2=get_info(it),  # file name for the found subtitle
                iconImage=str(int(round(float(
                    it['rating'])))),  # rating for the subtitle, string 0-5
                thumbnailImage=
                "bg"  # language flag, ISO_639_1 language + gif extention, e.g - "en.gif"
            )

            listitem.setProperty("sync", '{0}'.format("false").lower(
            ))  # set to "true" if subtitle is matched by hash,
            # indicates that sub is 100 Comaptible

            listitem.setProperty("hearing_imp", '{0}'.format("false").lower(
            ))  # set to "true" if subtitle is for hearing impared

            ## below arguments are optional, it can be used to pass any info needed in download function
            ## anything after "action=download&" will be sent to addon once user clicks listed subtitle to downlaod
            url = "plugin://%s/?action=download&link=%s&ID=%s&filename=%s" % (
                __scriptid__, it['url'], it['id'], "filename of the subtitle")
            ## add it to list, this can be done as many times as needed for all subtitles found
            xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),
                                        url=url,
                                        listitem=listitem,
                                        isFolder=False)

        Notify('Server', 'ok')
    else:
        Notify('Server', 'error')
コード例 #40
0
def search_filename(filename, allowfallback):
	log('Search tv show using the file name')
	title, year = xbmc.getCleanMovieTitle(filename)
	log("clean title: \"%s\" (%s)" % (title, year))
	match = re.search(r'\WS(?P<season>\d{1,3})[ ._-]*E(?P<episode>\d{1,3})', title, flags = re.IGNORECASE)
	if match is not None:
		tvshow = string.strip(title[:match.start('season')-1]).lower()
		season = string.lstrip(match.group('season'), '0')
		episode = match.group('episode')
		search_tvshow(tvshow, season, episode, -1, filename, allowfallback)
	else:
		match = re.search(r'\W(?P<season>\d{1,3})x(?P<episode>\d{1,3})', title, flags = re.IGNORECASE)
		if match is not None:
			tvshow = string.strip(title[:match.start('season')-1])
			season = string.lstrip(match.group('season'), '0')
			episode = string.lstrip(match.group('episode'), '0')
			search_tvshow(tvshow, season, episode, -1, filename, allowfallback)
		else:
			log('Unable to retrieve a tv show name and episode from file name')
コード例 #41
0
def search_filename(filename, allowfallback):
	log('Search tv show using the file name')
	title, year = xbmc.getCleanMovieTitle(filename)
	log("clean title: \"%s\" (%s)" % (title, year))
	match = re.search(r'\WS(?P<season>\d{1,3})[ ._-]*E(?P<episode>\d{1,3})', title, flags = re.IGNORECASE)
	if match is not None:
		tvshow = string.strip(title[:match.start('season')-1]).lower()
		season = string.lstrip(match.group('season'), '0')
		episode = match.group('episode')
		search_tvshow(tvshow, season, episode, -1, filename, allowfallback)
	else:
		match = re.search(r'\W(?P<season>\d{1,3})x(?P<episode>\d{1,3})', title, flags = re.IGNORECASE)
		if match is not None:
			tvshow = string.strip(title[:match.start('season')-1])
			season = string.lstrip(match.group('season'), '0')
			episode = string.lstrip(match.group('episode'), '0')
			search_tvshow(tvshow, season, episode, -1, filename, allowfallback)
		else:
			log('Unable to retrieve a tv show name and episode from file name')
コード例 #42
0
	def search(self,item):

		if item['mansearch']:
			title = item['mansearchstr']
		elif item['tvshow']:
			title = "%s S%02dE%02d" % (self.normalize_input_title(item['tvshow']), int(item['season']), int(item['episode'])) # Searching TV Show
		else: # Searching movie
			title = item['title'] if item['year'] else xbmc.getCleanMovieTitle(item['title'])[0]
			title = self.normalize_input_title(title)

		log(__name__, "Search pattern: " + title)

		found_subtitles = self.search_subtitle(title)
		log(__name__, "Parsed subtitles: %s" % found_subtitles )

		lang_filetred_found_subtitles = self.filter_subtitles_by_language(item['3let_language'], found_subtitles)
		log(__name__, ["Language filter", lang_filetred_found_subtitles])
		if not lang_filetred_found_subtitles: return results_with_stats(None, self.addon, title, item)

		file_size = get_file_size(item['file_original_path'], item['rar'])
		if not (file_size == -1): file_size = round(float(file_size)/(1024*1024),2)
		log(__name__, "File size: %s" % file_size)

		max_down_count = self.detect_max_download_stats(lang_filetred_found_subtitles)

		result_subtitles = []
		for found_subtitle in lang_filetred_found_subtitles:
			print_out_filename = (found_subtitle['version'], found_subtitle['title'])[found_subtitle['version'] == '' or found_subtitle['version'] == None]
			if not found_subtitle['author'] == None: print_out_filename += " by " + found_subtitle['author']
			result_subtitles.append({
				'filename': HTMLParser.HTMLParser().unescape(print_out_filename),
				'id': found_subtitle['id'],
				'lang': found_subtitle['lang'],
				'rating': str(found_subtitle['down_count']*5/max_down_count) if max_down_count > 0 else "0",
				'sync': (found_subtitle['size'] == file_size and file_size > 0),
				'lang_flag': xbmc.convertLanguage(found_subtitle['lang'],xbmc.ISO_639_1),
			})

		log(__name__,["Search result", result_subtitles])

		return results_with_stats(result_subtitles, self.addon, title, item)
コード例 #43
0
def search(item):
    res = []
    filename = os.path.splitext(os.path.basename(item['file_original_path']))[0]
    log(__name__, "Search_thaisubtitle='%s', filename='%s', addon_version=%s" % (item, filename, __version__))

    if item['mansearch']:
        res = search_manual(item['mansearchstr'], item['3let_language'], filename)
        return append_subtitles(res)
    elif item['tvshow']:
        res = search_tvshow(item['tvshow'], item['season'], item['episode'], item['3let_language'], filename)
        if res:
            return append_subtitles(res)
    elif item['title'] and item['year']:
        res = search_manual(item['title'], item['3let_language'], filename, )
        if res:
            return append_subtitles(res)

    title, year = xbmc.getCleanMovieTitle(filename)
    log(__name__, "clean title: \"%s\" (%s)" % (title, year))
    try:
        yearval = int(year)
    except ValueError:
        yearval = 0
    if title and yearval > 1900:
        res = search_movie(title, year, item['3let_language'], filename)
        if res:
            return append_subtitles(res)
    match = re.search(r'\WS(?P<season>\d\d)E(?P<episode>\d\d)', title, flags=re.IGNORECASE)
    if match is not None:
        tvshow = string.strip(title[:match.start('season')-1])
        season = string.lstrip(match.group('season'), '0')
        episode = string.lstrip(match.group('episode'), '0')
        res = search_tvshow(tvshow, season, episode, item['3let_language'], filename)
        if res:
            return append_subtitles(res)
    # last fall back
    if len(filename) < 30:
        res = search_manual(filename, item['3let_language'], filename)
    if res:
        return append_subtitles(res)
    return []
コード例 #44
0
def search_movie(title, year, languages, filename):
    title = prepare_search_string(title)
    log(__name__, "Search movie = %s" % title)
    log(__name__, "Search movie filename = %s" % filename)
    url = main_url + "/subtitles/searching?q=" + urllib.quote_plus(
        title) + '&r=true'
    content, resp = geturl(url)

    if content is not None:
        found = False
        log(__name__, "Multiple movies found, searching for the right one ...")
        subspage_url = find_movie(content, title, year)
        if subspage_url is not None:
            log(__name__, "Movie found in list, getting subs ...")
            url = main_url + subspage_url
            getallsubs(url, languages, filename)
            found = True
        else:
            log(__name__, "Movie not found in list: %s" % title)
            if string.find(string.lower(title), "&") > -1:
                title = string.replace(title, "&", "and")
                log(__name__,
                    "Trying searching with replacing '&' to 'and': %s" % title)
                subspage_url = find_movie(content, title, year)
                if subspage_url is not None:
                    log(__name__, "Movie found in list, getting subs ...")
                    url = main_url + subspage_url
                    getallsubs(url, languages, filename)
                    found = True
                else:
                    log(__name__, "Movie not found in list: %s" % title)
            if not found:
                log(__name__, "Trying searching with filename: %s" % filename)
                title, year = xbmc.getCleanMovieTitle(filename)
                subspage_url = find_movie(content, title, year)
                if subspage_url is not None:
                    log(__name__, "Movie found in list, getting subs ...")
                    url = main_url + subspage_url
                    getallsubs(url, languages, filename)
                else:
                    log(__name__, "Movie not found in list: %s" % title)
コード例 #45
0
ファイル: service.py プロジェクト: CaTzil/XBMC-1
def search_subtitles( file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack ): #standard input
  ok = False
  msg = ""
  hash_search = False
  subtitles_list = []  
  if len(tvshow) > 0:                                            # TvShow
    OS_search_string = ("%s S%.2dE%.2d" % (tvshow,
                                           int(season),
                                           int(episode),)
                                          ).replace(" ","+")      
  else:                                                          # Movie or not in Library
    if str(year) == "":                                          # Not in Library
      title, year = xbmc.getCleanMovieTitle( title )
    else:                                                        # Movie in Library
      year  = year
      title = title
    OS_search_string = title.replace(" ","+")
  log( __name__ , "Search String [ %s ]" % (OS_search_string,))     
 
  if set_temp : 
    hash_search = False
    file_size   = "000000000"
    SubHash     = "000000000000"
  else:
    try:
      file_size, SubHash = hashFile(file_original_path, rar)
      log( __name__ ,"xbmc module hash and size")
      hash_search = True
    except:  
      file_size   = ""
      SubHash     = ""
      hash_search = False
  
  if file_size != "" and SubHash != "":
    log( __name__ ,"File Size [%s]" % file_size )
    log( __name__ ,"File Hash [%s]" % SubHash)
  
  log( __name__ ,"Search by hash and name %s" % (os.path.basename( file_original_path ),))
  subtitles_list, msg = OSDBServer().searchsubtitles( OS_search_string, lang1, lang2, lang3, hash_search, SubHash, file_size  )
      
  return subtitles_list, "", msg #standard output
コード例 #46
0
ファイル: service.py プロジェクト: teosan5/0
def searchsubtitles(item):
    if len(item['tvshow']) > 0:
        search_string = item['tvshow'].replace(" ", "+")      
    else:
        if str(item['year']) == "":
            item['title'], item['year'] = xbmc.getCleanMovieTitle(item['title'])
    
        search_string = (re.sub('S(\d{1,2})E(\d{1,2})', '', item['title'])).replace(" ", "+")

    if item['mansearch']:
        s_string = urllib.unquote(item['mansearchstr'])
        search_string = s_string.replace(" ", "+")
    s = requests.Session()
    ua = 'Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1'
    headers = {'User-Agent': ua}
    search_link = 'http://www.subtitrari-noi.ro/index.php?action=caut&titlu=' + search_string + '&tip=Nume+Film&Cautare=Cautare'
    search_code = s.get(search_link, headers=headers)
    regex = '''<table width=".+?class="sub" id="sub"(.+?)</table>'''
    regex_art = '''.+?">(.+?)<span.+?Traducator:.+?">(.+?)</.+?<a href="(.+?)".+?Comentariu:(.+?)</td>'''
    match = []
    for art in re.compile(regex, re.IGNORECASE | re.MULTILINE | re.DOTALL).findall(search_code.text):
        if art:
            result = re.compile(regex_art, re.IGNORECASE | re.DOTALL).findall(art)
            (nume, traducator, legatura, descriere) = result[0]
            legatura = BASE_URL + legatura
            match.append((nume,
                         traducator,
                         legatura,
                         descriere,
                         ))
    clean_search = []
    if len(match) > 0:
        for item_search in match:
            s_title = re.sub('\s+', ' ', cleanhtml(item_search[0])) + ' ' + re.sub('\s+', ' ', cleanhtml(item_search[3])) + ' Traducator: ' + re.sub('\s+', ' ', cleanhtml(item_search[1]))
            clean_search.append({'SeriesSeason': '0', 'SeriesEpisode': '0', 'LanguageName': 'Romanian', 'episode': '0', 'SubFileName': s_title, 'SubRating': '0', 'ZipDownloadLink': item_search[2], 'ISO639': 'ro', 'SubFormat': 'srt', 'MatchedBy': 'fulltext', 'SubHearingImpaired': '0', 'Traducator': re.sub('\s+', ' ', cleanhtml(item_search[1])), 'referer': search_string})
        if clean_search:
            return clean_search 
    else:
        return None  
コード例 #47
0
def main():
    if xbmc.getCondVisibility("Pvr.HasTVChannels"):
        Label = xbmc.getInfoLabel("ListItem.Title")
    else:
        Label = xbmc.getInfoLabel("ListItem.Label")

    Label, year = xbmc.getCleanMovieTitle(Label)

    url = (
        "plugin://plugin.video.torrenter/?action=searchWindow&mode=search&query=%s"
        % (Label))
    if xbmc.getCondVisibility("Container.Content(movies)"):
        xbmc.executebuiltin('xbmc.RunPlugin(%s)' % (url))
    elif xbmc.getCondVisibility("Container.Content(tvshows)"):
        xbmc.executebuiltin('xbmc.RunPlugin(%s)' % (url))
    elif xbmc.getCondVisibility("Container.Content(seasons)"):
        xbmc.executebuiltin('xbmc.RunPlugin(%s)' % (url))
    elif xbmc.getCondVisibility(
            "Container.Content(actors) | Container.Content(directors)"):
        xbmc.executebuiltin('xbmc.RunPlugin(%s)' % (url))
    elif xbmc.getCondVisibility("Pvr.HasTVChannels"):
        xbmc.executebuiltin('xbmc.RunPlugin(%s)' % (url))
コード例 #48
0
ファイル: service.py プロジェクト: teosan5/0
def searchsubtitles(item):
    lists = ''
    item_orig = item['title']
    if len(item['tvshow']) > 0:
        search_string = item['tvshow'].replace(" ", "+")     
    else:
        if str(item['year']) == "":
            item['title'], item['year'] = xbmc.getCleanMovieTitle(item['title'])
    
        search_string = (re.sub('S(\d{1,2})E(\d{1,2})', '', item['title']))
        episodes = re.compile('S(\d{1,2})E(\d{1,2})', re.IGNORECASE).findall(item['title'])
        if episodes:
            item['season'] = episodes[0][0]
            item['episode'] = episodes[0][1]
        else:
            episodes = re.compile('(\d)(\d{1,2})', re.IGNORECASE).findall(item['title'])
            if episodes:
                search_string = (re.sub('(\d)(\d{1,2})', '', item['title']))
                item['season'] = episodes[0][0]
                item['episode'] = episodes[0][1]
            
    if item['mansearch']:
        s_string = urllib.unquote(item['mansearchstr'])
        search_string = s_string
        episodes = re.compile('S(\d{1,2})E(\d{1,2})', re.IGNORECASE).findall(search_string)
        if episodes:
            sezon = episodes[0][0]
            episod = episodes[0][1]
            search_string = (re.sub('S(\d{1,2})E(\d{1,2})', '', search_string, flags=re.I))
            lists = search_links(search_string, sezon=sezon, episod=episod)
        else:
            lists = search_links(search_string)
        return lists
    lists = search_links(search_string, item['year'], item['season'], item['episode'], item_orig)
    if not lists:
        if not item['file_original_path'].startswith('http') and xbmcvfs.exists(item['file_original_path']):
            head = os.path.basename(os.path.dirname(item['file_original_path']))
            lists = search_links(search_string, item['year'], item['season'], item['episode'], (re.compile(r'\[.*?\]').sub('', head)))
    return lists
コード例 #49
0
def Search(item):
  it = []
  _item = dict(item)
  it.append(item)
  _item['title'], _item['year'] = xbmc.getCleanMovieTitle( item['title'] )
  it.append(_item)

  sub_data = read_sub(*it)
  #### Do whats needed to get the list of subtitles from service site
  #### use item["some_property"] that was set earlier
  #### once done, set xbmcgui.ListItem() below and pass it to xbmcplugin.addDirectoryItem()
  if sub_data != None:
    log_my(sub_data)
    for it in sub_data:
      listitem = xbmcgui.ListItem(label="Bulgarian",               # language name for the found subtitle
                                label2=get_info(it),               # file name for the found subtitle
                                iconImage=str(int(round(float(it['rating'])))), # rating for the subtitle, string 0-5
                                thumbnailImage="bg"          # language flag, ISO_639_1 language + gif extention, e.g - "en.gif"
                                )

      listitem.setProperty( "sync",        '{0}'.format("false").lower() )  # set to "true" if subtitle is matched by hash,
                                                                         # indicates that sub is 100 Comaptible

      listitem.setProperty( "hearing_imp", '{0}'.format("false").lower() ) # set to "true" if subtitle is for hearing impared


      ## below arguments are optional, it can be used to pass any info needed in download function
      ## anything after "action=download&" will be sent to addon once user clicks listed subtitle to downlaod
      url = "plugin://%s/?action=download&link=%s&ID=%s&filename=%s" % (__scriptid__,
                                                                      it['url'],
                                                                      it['id'],
                                                                      "filename of the subtitle")
      ## add it to list, this can be done as many times as needed for all subtitles found
      xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=listitem,isFolder=False)

    Notify('Server', 'ok')
  else:
    Notify('Server', 'error')
コード例 #50
0
ファイル: OSUtilities.py プロジェクト: kirstenangel/kodi
    def searchsubtitles(self, item):
        if len(item['tvshow']) > 0:
            OS_search_string = item['tvshow'].replace(" ", "+")      
        else:
            if str(item['year']) == "":
                item['title'], item['year'] = xbmc.getCleanMovieTitle(item['title'])
    
            OS_search_string = (re.sub('S(\d{1,2})E(\d{1,2})', '', item['title'])).replace(" ", "+")

        if item['mansearch']:
            s_string = urllib.unquote(item['mansearchstr'])
            OS_search_string = s_string.replace(" ", "+")
        s = requests.Session()
        ua = 'Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1) Gecko/20121011 Firefox/16.0.1'
        headers = {'User-Agent': ua}
        search_link = 'http://www.titrari.ro/index.php?page=cautare&z1=0&z2=' + OS_search_string + '&z3=1&z4=1'
        search_code = s.get(search_link, headers=headers)
        regex = '''<a style=color:black href=index.php\?page=cautareavansata(.+?)</td></tr></table></td></tr><tr><td'''
        regex_art = '''>(.+?)</a></h1>.*?cautaretraducator.+?>(.+?)</a>.+?<a href=get.php\?id=(.+?)>.+?<td class=comment.+?>(.*?)$'''
        match = []
        for art in re.compile(regex, re.IGNORECASE | re.MULTILINE | re.DOTALL).findall(search_code.text):
            if art:
                result = re.compile(regex_art, re.IGNORECASE | re.DOTALL).findall(art)
                (nume, traducator, legatura, descriere) = result[0]
                match.append((nume,
                             traducator,
                             legatura,
                             descriere,
                             ))
        clean_search = []
        if len(match) > 0:
            for item_search in match:
                s_title = re.sub('\s+', ' ', cleanhtml(item_search[0])) + ' Traducator: ' + re.sub('\s+', ' ', cleanhtml(item_search[1])) + ' ' + re.sub('\s+', ' ', cleanhtml(item_search[3]))
                clean_search.append({'SeriesSeason': '0', 'SeriesEpisode': '0', 'LanguageName': 'Romanian', 'episode': '0', 'SubFileName': s_title, 'SubRating': '0', 'ZipDownloadLink': item_search[2], 'ISO639': 'ro', 'SubFormat': 'srt', 'MatchedBy': 'fulltext', 'SubHearingImpaired': '0', 'Traducator': re.sub('\s+', ' ', cleanhtml(item_search[1])), 'referer': OS_search_string})
            if clean_search:
                return clean_search 
        else:
            return None
コード例 #51
0
ファイル: service.py プロジェクト: teosan5/0
def Search(item):
    filename = os.path.splitext(os.path.basename(item['file_original_path']))[0]
    #log(__name__, "Search_filename='%s', addon_version=%s" % (filename, __version__))

    if item['mansearch']:
        search_manual(item['mansearchstr'], item['3let_language'])

    if len(item['tvshow']) > 0:
        query_TvShow(item['tvshow'], item['season'], item['episode'], item['3let_language'], filename)
    else:
        if str(item['year']) == "":
            titlu = item['title']
            item['title'], item['year'] = xbmc.getCleanMovieTitle(titlu)
            #log(__name__, "first item from filename='%s'" % (titlu))
            episodes = re.compile('S(\d{1,2})E(\d{1,2})', re.IGNORECASE).findall(item['title'])
            if episodes:
                item['season'] = episodes[0][0]
                item['episode'] = episodes[0][1]
            else:
                episodes = re.compile('(\d)(\d{1,2})', re.IGNORECASE).findall(item['title'])
                if episodes:
                    item['season'] = episodes[0][0]
                    item['episode'] = episodes[0][1]
            item['title'] = addic7ize((re.sub('(\d)(\d{1,2})', '', (re.sub('S(\d{1,2})E(\d{1,2})', '', item['title'])))).strip())
            try: item['title'] = item['title'].split('  ', 1)[0]
            except: pass
            log(__name__, "item from filename='%s'" % (item))
            if len(item['season']) > 0 and len(item['episode']) > 0:
                query_TvShow(item['title'], item['season'], item['episode'], item['3let_language'], filename)
            else:
                if item['year']:
                    query_Film(item['title'], item['year'], item['3let_language'], filename)
                else:
                    search_manual(item['title'], item['3let_language'], item['year'])
        else:
            query_Film(item['title'], item['year'], item['3let_language'], filename)
コード例 #52
0
def search_subtitles( file_original_path, title, tvshow, year, season, episode, set_temp, rar, lang1, lang2, lang3, stack ): #standard input
    subtitles_list = []
    msg = ""
    if len(tvshow) == 0:
        if str(year) == "":
            title, year = xbmc.getCleanMovieTitle( title )
        else:
            year  = year
            title = title
        searchstring = title
    if len(tvshow) > 0:
        searchstring = "%s S%#02dE%#02d" % (tvshow, int(season), int(episode))
        log( __name__ ,"%s Search string = %s" % (debug_pretext, searchstring))

    greek = 0
    if string.lower(lang1) == "greek": greek = 1
    elif string.lower(lang2) == "greek": greek = 2
    elif string.lower(lang3) == "greek": greek = 3

    getallsubs(searchstring, "el", "Greek", subtitles_list)
    if greek == 0:
        msg = "Won't work, subtitles.gr is only for Greek subtitles."

    return subtitles_list, "", msg #standard output
コード例 #53
0
ファイル: play.py プロジェクト: chimkentec/KodiMODo_rep
def clean(path, folder=False):
    return xbmc.getCleanMovieTitle(path, folder)
コード例 #54
0
def Search(item):
    """Called when searching for subtitles from XBMC."""
    #### Do what's needed to get the list of subtitles from service site
    #### use item["some_property"] that was set earlier
    #### once done, set xbmcgui.ListItem() below and pass it to xbmcplugin.addDirectoryItem()
    #### CHECKING FOR ANYTHING IN THE USERNAME AND PASSWORD, IF NULL IT STOPS THE SCRIPT WITH A WARNING
    username = _addon.getSetting( 'LDuser' )
    password = _addon.getSetting( 'LDpass' )
    if username == '' or password == '':
        xbmcplugin.endOfDirectory(int(sys.argv[1]))
        if username == '' and password != '': xbmc.executebuiltin(('Notification(%s,%s,%d)' % (_scriptname , _language(32016).encode('utf-8'),5000)))
        if username != '' and password == '': xbmc.executebuiltin(('Notification(%s,%s,%d)' % (_scriptname , _language(32017).encode('utf-8'),5000)))
        if username == '' and password == '': xbmc.executebuiltin(('Notification(%s,%s,%d)' % (_scriptname , _language(32018).encode('utf-8'),5000)))
    #### PARENT FOLDER TWEAK DEFINED IN THE ADD-ON SETTINGS (AUTO | ALWAYS ON (DEACTIVATED) | OFF)
    file_original_path = item['file_original_path']
    _parentfolder = _addon.getSetting( 'PARENT' )
    if _parentfolder == '0':
        filename = os.path.abspath(file_original_path)
        dirsearch = filename.split(os.sep)
        log(u"getallsubs: dirsearch string _parentfolder is 0 = %s" % (dirsearch,))
        if re.search(release_pattern, dirsearch[-2], re.IGNORECASE): _parentfolder = '1'
        else: _parentfolder = '2'
    if _parentfolder == '1':
        filename = os.path.abspath(file_original_path)
        dirsearch = filename.split(os.sep)
        filename = dirsearch[-2]
        log(u"getallsubs: filename string _parentfolder is 1 = %s" % (filename,))
    if _parentfolder == '2':   
        filename = os.path.splitext(os.path.basename(file_original_path))[0]
        log(u"getallsubs: filename string _parentfolder is 2 = %s" % (filename,))
 
    filename = xbmc.getCleanMovieTitle(filename)[0] + " " + xbmc.getCleanMovieTitle(filename)[1]
    log(u"Search: FILENAME = %s" % (filename,))
    searchstring_notclean = os.path.splitext(os.path.basename(file_original_path))[0]
    searchstring = ""
    global israr
    israr = os.path.abspath(file_original_path)
    israr = os.path.split(israr)
    israr = israr[0].split(os.sep)
    israr = string.split(israr[-1], '.')
    israr = string.lower(israr[-1])

    title = xbmc.getCleanMovieTitle(item['title'])[0]
    year = item['year']
    ## REMOVING THE YEAR FROM THE TV SHOW FOR BETTER MATCH ##
    tvshow = item['tvshow']
    tvshow = tvshow.split('(')
    tvshow = tvshow[0]
    ##########################################################
    season = item['season']
    episode = item['episode']
    log(u"Search: Tvshow string = %s" % (tvshow,))
    log(u"Search: Title string = %s" % (title,))
    subtitles_list = []
    
    if item['mansearch']:
        searchstring = '"' + item['mansearchstr'] + '"'
        log(u"Search: Manual String = %s" % (searchstring,))
    else:
        if tvshow != '':
            searchstring = "%s S%#02dE%#02d" % (tvshow, int(season), int(episode))
            log(u"Search: Title TV LIBRARY String = %s" % (searchstring,))
        elif title != '' and tvshow == '':
            searchstring = '"' + title + ' ' + year + '"'
            log(u"Search: Title MOVIE LIBRARY String = %s" % (searchstring,))
        else:
            if 'rar' in israr and searchstring is not None:
                log(u"Search: RAR Filename String = %s" % (searchstring,))
                if 'cd1' in string.lower(title) or 'cd2' in string.lower(title) or 'cd3' in string.lower(title):
                    dirsearch = os.path.abspath(file_original_path)
                    dirsearch = os.path.split(dirsearch)
                    dirsearch = dirsearch[0].split(os.sep)
                    if len(dirsearch) > 1:
                        searchstring_notclean = dirsearch[-3]
                        searchstring = xbmc.getCleanMovieTitle(dirsearch[-3])
                        searchstring = searchstring[0]
                        log(u"Search: RAR MULTI CD String = %s" % (searchstring,))
                    else: searchstring = title
                else:
                    searchstring = title
                    log(u"Search: RAR NO MULTI CD String = %s" % (searchstring,))
            elif 'cd1' in string.lower(title) or 'cd2' in string.lower(title) or 'cd3' in string.lower(title):
                dirsearch = os.path.abspath(file_original_path)
                dirsearch = os.path.split(dirsearch)
                dirsearch = dirsearch[0].split(os.sep)
                if len(dirsearch) > 1:
                    searchstring_notclean = dirsearch[-2]
                    searchstring = xbmc.getCleanMovieTitle(dirsearch[-2])
                    searchstring = searchstring[0]
                    log(u"Search: MULTI CD String = %s" % (searchstring,))
                else:
                    #We are at the root of the drive!!! so there's no dir to lookup only file#
                    title = os.path.split(file_original_path)
                    searchstring = title[-1]
            else:
                ########## TODO: EXTRACT THE YEAR FROM THE FILENAME AND ADD IT TO THE SEARCH ###########
                if _search == '0':
                    if re.search("(.+?s[0-9][0-9]e[0-9][0-9])", filename, re.IGNORECASE):
                        searchstring = re.search("(.+?s[0-9][0-9]e[0-9][0-9])", filename, re.IGNORECASE)
                        searchstring = searchstring.group(0)
                        log(u"Search: Filename is TV String (search is 0) = %s" % (searchstring,))
                    else:
                        searchstring = '"' + filename + '"'
                        log(u"Search: Filename is Not TV String (search is 0) = %s" % (searchstring,))
                else:
                    if re.search("(.+?s[0-9][0-9]e[0-9][0-9])", title, re.IGNORECASE):
                        searchstring = re.search("(.+?s[0-9][0-9]e[0-9][0-9])", title, re.IGNORECASE)
                        searchstring = searchstring.group(0)
                        log(u"Search: Title is TV String (search is 1) = %s" % (searchstring,))
                    else:
                        searchstring = title
                        log(u"Search: Title is Not TV String (search is 1) = %s" % (searchstring,))

    PT_ON = _addon.getSetting( 'PT' )
    PTBR_ON = _addon.getSetting( 'PTBR' )
    ES_ON = _addon.getSetting( 'ES' )
    EN_ON = _addon.getSetting( 'EN' )
    
    if 'por' in item['languages'] and PT_ON == 'true':
        subtitles_list = getallsubs(searchstring, "pt", "Portuguese", file_original_path, searchstring_notclean)
        for sub in subtitles_list: append_subtitle(sub)
    if 'por' in item['languages'] and PTBR_ON == 'true':
        subtitles_list = getallsubs(searchstring, "pb", "Brazilian", file_original_path, searchstring_notclean)
        for sub in subtitles_list: append_subtitle(sub)
    if 'spa' in item['languages'] and ES_ON == 'true':
        subtitles_list = getallsubs(searchstring, "es", "Spanish", file_original_path, searchstring_notclean)
        for sub in subtitles_list: append_subtitle(sub)
    if 'eng' in item['languages'] and EN_ON == 'true':
        subtitles_list = getallsubs(searchstring, "en", "English", file_original_path, searchstring_notclean)
        for sub in subtitles_list: append_subtitle(sub)
    if 'eng' not in item['languages'] and 'spa' not in item['languages'] and 'por' not in item['languages'] and 'por' not in item['languages']:
        xbmc.executebuiltin((u'Notification(%s,%s,%d)' % (_scriptname , 'Only Portuguese | Portuguese Brazilian | English | Spanish.',5000)))
コード例 #55
0
    item['tvshow']             = normalizeString(xbmc.getInfoLabel("VideoPlayer.TVshowtitle"))   # Show
    item['title']              = normalizeString(xbmc.getInfoLabel("VideoPlayer.OriginalTitle")) # try to get original title
    item['file_original_path'] = urllib.unquote(xbmc.Player().getPlayingFile().decode('utf-8'))  # Full path of a playing file
    item['3let_language']      = []

    if 'searchstring' in params:
        item['mansearch'] = True
        item['mansearchstr'] = params['searchstring']

    for lang in urllib.unquote(params['languages']).decode('utf-8').split(","):
        item['3let_language'].append(xbmc.convertLanguage(lang,xbmc.ISO_639_2))

    if item['title'] == "":
        item['title']  = xbmc.getInfoLabel("VideoPlayer.Title")                       # no original title, get just Title
        if item['title'] == os.path.basename(xbmc.Player().getPlayingFile()):         # get movie title and year if is filename
            title, year = xbmc.getCleanMovieTitle(item['title'])
            item['title'] = normalizeString(title.replace('[','').replace(']',''))
            item['year'] = year

    if item['episode'].lower().find("s") > -1:                                        # Check if season is "Special"
        item['season'] = "0"                                                          #
        item['episode'] = item['episode'][-1:]

    if ( item['file_original_path'].find("http") > -1 ):
        item['temp'] = True

    elif ( item['file_original_path'].find("rar://") > -1 ):
        item['rar']  = True
        item['file_original_path'] = os.path.dirname(item['file_original_path'][6:])

    elif ( item['file_original_path'].find("stack://") > -1 ):
コード例 #56
0
  def set_allparam(self):       
    self.list           = []
    service_list        = []
    self.stackPath      = []
    service             = ""
    self.man_search_str = ""   
    self.temp           = False
    self.rar            = False
    self.stack          = False
    self.autoDownload   = False
    use_subs_folder     = __addon__.getSetting( "use_subs_folder" ) == "true"           # use 'Subs' subfolder for storing subtitles
    movieFullPath       = urllib.unquote(xbmc.Player().getPlayingFile().decode('utf-8'))# Full path of a playing file
    path                = __addon__.getSetting( "subfolder" ) == "true"                 # True for movie folder
    self.sub_folder     = xbmc.translatePath(__addon__.getSetting( "subfolderpath" )).decode("utf-8")   # User specified subtitle folder
    self.year           = xbmc.getInfoLabel("VideoPlayer.Year")                         # Year
    self.season         = str(xbmc.getInfoLabel("VideoPlayer.Season"))                  # Season
    self.episode        = str(xbmc.getInfoLabel("VideoPlayer.Episode"))                 # Episode
    self.mansearch      =  __addon__.getSetting( "searchstr" ) == "true"                # Manual search string??
    self.parsearch      =  __addon__.getSetting( "par_folder" ) == "true"               # Parent folder as search string
    self.language_1     = languageTranslate(__addon__.getSetting( "Lang01" ), 4, 0)     # Full language 1
    self.language_2     = languageTranslate(__addon__.getSetting( "Lang02" ), 4, 0)     # Full language 2  
    self.language_3     = languageTranslate(__addon__.getSetting( "Lang03" ), 4, 0)     # Full language 3
    self.tmp_sub_dir    = os.path.join( __profile__ ,"sub_tmp" )                        # Temporary subtitle extraction directory   
    self.stream_sub_dir = os.path.join( __profile__ ,"sub_stream" )                     # Stream subtitle directory    
    
    self.clean_temp()                                                                   # clean temp dirs
    
    if ( movieFullPath.find("http") > -1 ):
      self.sub_folder = self.stream_sub_dir
      self.temp = True

    elif ( movieFullPath.find("rar://") > -1 ):
      self.rar = True
      movieFullPath = movieFullPath[6:]
      if path:
        if use_subs_folder:
          self.sub_folder = os.path.join(os.path.dirname(os.path.dirname( movieFullPath )),'Subs')
        else:
          self.sub_folder = os.path.dirname(os.path.dirname( movieFullPath ))  
    
    elif ( movieFullPath.find("stack://") > -1 ):
      self.stackPath = movieFullPath.split(" , ")
      movieFullPath = self.stackPath[0][8:]
      self.stack = True

    if not path:
      if len(self.sub_folder) < 1 :
        if use_subs_folder:
          self.sub_folder = os.path.join(os.path.dirname( movieFullPath ),'Subs')
        else:
          self.sub_folder = os.path.dirname( movieFullPath )

    if path and not self.rar and not self.temp:
      if use_subs_folder:
        self.sub_folder = os.path.join(os.path.dirname( movieFullPath ),'Subs')
      else:
        self.sub_folder = os.path.dirname( movieFullPath )    
      if self.sub_folder.find("smb://") > -1:
        if self.temp:
          dialog = xbmcgui.Dialog()
          self.sub_folder = dialog.browse( 0, _( 766 ), "files")
    
    if not xbmcvfs.exists(self.sub_folder):
      xbmcvfs.mkdir(self.sub_folder)
    
    if self.episode.lower().find("s") > -1:                                 # Check if season is "Special"             
      self.season = "0"                                                     #
      self.episode = self.episode[-1:]                                      #

    self.tvshow    = unicodedata.normalize('NFKD',
                      unicode(unicode(xbmc.getInfoLabel
                      ("VideoPlayer.TVshowtitle"), 'utf-8'))
                      ).encode('ascii','ignore')                            # Show
    self.title     = unicodedata.normalize('NFKD', 
                      unicode(unicode(xbmc.getInfoLabel
                      ("VideoPlayer.Title"), 'utf-8'))
                      ).encode('ascii','ignore')                            # Title

    if self.tvshow == "":
      if str(self.year) == "":
        title, season, episode = regex_tvshow(False, self.title)
        if episode != "":
          self.season = str(int(season))
          self.episode = str(int(episode))
          self.tvshow = title
        else:
          self.title, self.year = xbmc.getCleanMovieTitle( self.title )
    else:
      self.year = ""

    self.file_original_path = urllib.unquote ( movieFullPath )             # Movie Path

    if (__addon__.getSetting( "fil_name" ) == "true"):                     # Display Movie name or search string
      self.file_name = os.path.basename( movieFullPath )
    else:
      if (len(str(self.year)) < 1 ) :
        self.file_name = self.title.encode('utf-8')
        if (len(self.tvshow) > 0):
          self.file_name = "%s S%.2dE%.2d" % (self.tvshow.encode('utf-8'),
                                              int(self.season),
                                              int(self.episode)
                                             )
      else:
        self.file_name = "%s (%s)" % (self.title.encode('utf-8'), str(self.year),)

    if ((__addon__.getSetting( "auto_download" ) == "true") and 
        (__addon__.getSetting( "auto_download_file" ) != os.path.basename( movieFullPath ))):
         self.autoDownload = True
         __addon__.setSetting("auto_download_file", "")

    for name in os.listdir(SERVICE_DIR):
      if os.path.isdir(os.path.join(SERVICE_DIR,name)) and __addon__.getSetting( name ) == "true":
        service_list.append( name )
        service = name

    if len(self.tvshow) > 0:
      def_service = __addon__.getSetting( "deftvservice")
    else:
      def_service = __addon__.getSetting( "defmovieservice")
      
    if service_list.count(def_service) > 0:
      service = def_service

    if len(service_list) > 0:  
      if len(service) < 1:
        self.service = service_list[0]
      else:
        self.service = service  

      self.service_list = service_list
      self.next = list(service_list)
      self.controlId = -1

      log( __name__ ,"Addon Version: [%s]"         % __version__)
      log( __name__ ,"Manual Search : [%s]"        % self.mansearch)
      log( __name__ ,"Default Service : [%s]"      % self.service)
      log( __name__ ,"Services : [%s]"             % self.service_list)
      log( __name__ ,"Temp?: [%s]"                 % self.temp)
      log( __name__ ,"Rar?: [%s]"                  % self.rar)
      log( __name__ ,"File Path: [%s]"             % self.file_original_path)
      log( __name__ ,"Year: [%s]"                  % str(self.year))
      log( __name__ ,"Tv Show Title: [%s]"         % self.tvshow)
      log( __name__ ,"Tv Show Season: [%s]"        % self.season)
      log( __name__ ,"Tv Show Episode: [%s]"       % self.episode)
      log( __name__ ,"Movie/Episode Title: [%s]"   % self.title)
      log( __name__ ,"Subtitle Folder: [%s]"       % self.sub_folder)
      log( __name__ ,"Languages: [%s] [%s] [%s]"   % (self.language_1, self.language_2, self.language_3,))
      log( __name__ ,"Parent Folder Search: [%s]"  % self.parsearch)
      log( __name__ ,"Stacked(CD1/CD2)?: [%s]"     % self.stack)
  
    return self.autoDownload