def Search(item): filename = '.'.join( os.path.basename(item["file_original_path"]).split(".")[:-1]) helper = NapiProjektKatalog() results = helper.search(item) for result in results: listitem = xbmcgui.ListItem( label=xbmc.convertLanguage(result["language"], xbmc.ENGLISH_NAME), # language name for the found subtitle label2=result['label'], # file name for the found subtitle iconImage="5", # rating for the subtitle, string 0-5 thumbnailImage=xbmc.convertLanguage(result["language"], xbmc.ISO_639_1) # language flag, ISO_639_1 language + gif extention, e.g - "en.gif" ) # # 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 download url = "plugin://%s/?action=download&l=%s&f=%s&filename=%s" % ( __scriptid__, result["language"], result['link_hash'], filename) # # 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)
def _retrive_subtitles(self, page, item): ret = [] total_downloads = 0 if page is not None: found_subtitles = re.findall( "downloadsubtitle\.php\?id=(?P<fid>\d*).*?subt_lang.*?title=\"(?P<language>.*?)\".*?subtitle_title.*?title=\"(?P<title>.*?)\">.*?>(?P<downloads>[^ ]+) הורדות", page) for (subtitle_id, language, title, downloads) in found_subtitles: if xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_2) in item[ "3let_language"]: subtitle_rate = self._calc_rating(title, item["file_original_path"]) total_downloads += int(downloads.replace(",", "")) ret.append( {'lang_index': item["3let_language"].index( xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_2)), 'filename': title, 'link': subtitle_id, 'language_name': xbmc.convertLanguage(heb_to_eng(language), xbmc.ENGLISH_NAME), 'language_flag': xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_1), 'id': subtitle_id, 'rating': int(downloads.replace(",", "")), 'sync': subtitle_rate >= 3.8, 'hearing_imp': 0, 'is_preferred': xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_2) == item['preferredlanguage'] }) return ret, total_downloads
def _retrive_subtitles(self, page, item): ret = [] total_downloads = 0 if page is not None: found_subtitles = re.findall( 'downloadsubtitle\.php\?id=(?P<fid>\d*).*?subt_lang.*?title="(?P<language>.*?)".*?subtitle_title.*?title="(?P<title>.*?)">.*?>(?P<downloads>[^ ]+) הורדות', page, ) for (subtitle_id, language, title, downloads) in found_subtitles: if xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_2) in item["3let_language"]: subtitle_rate = self._calc_rating(title, item["file_original_path"]) total_downloads += int(downloads.replace(",", "")) ret.append( { "lang_index": item["3let_language"].index( xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_2) ), "filename": title, "link": subtitle_id, "language_name": xbmc.convertLanguage(heb_to_eng(language), xbmc.ENGLISH_NAME), "language_flag": xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_1), "ID": subtitle_id, "rating": int(downloads.replace(",", "")), "sync": subtitle_rate >= 4, "hearing_imp": 0, } ) return ret, total_downloads
def _build_subtitle_list(self, search_results, item): results = [] total_downloads = 0 for result in search_results: lang3 = xbmc.convertLanguage(result["language"], xbmc.ISO_639_2) if lang3 in item["3let_language"]: total_downloads += result["downloads"] results.append({ 'lang_index': item["3let_language"].index(lang3), 'filename': result["release"], 'language_name': xbmc.convertLanguage(result["language"], xbmc.ENGLISH_NAME), 'language_flag': result["language"], 'id': result["id"], 'rating': result["downloads"], 'sync': self._is_synced(item, result["video_file_size"], result["release"]), 'hearing_imp': False, 'is_preferred': lang3 == item['preferredlanguage'] }) # Fix the rating if total_downloads: for it in results: it["rating"] = min(int(round(it["rating"] / float(total_downloads), 1) * 8), 5) return sorted(results, key=lambda x: (x['is_preferred'], x['lang_index'], x['sync'], x['rating']), reverse=True)
def _retrive_subtitles(self, page, item): ret = [] total_downloads = 0 if page is not None: found_subtitles = re.findall( "downloadsubtitle\.php\?id=(?P<fid>\d*).*?subt_lang.*?title=\"(?P<language>.*?)\".*?subtitle_title.*?title=\"(?P<title>.*?)\">.*?>(?P<downloads>[^ ]+) הורדות", page) for (subtitle_id, language, title, downloads) in found_subtitles: if xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_2) in item["3let_language"]: subtitle_rate = self._calc_rating(title, item["file_original_path"]) total_downloads += int(downloads.replace(",", "")) ret.append( {'lang_index': item["3let_language"].index( xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_2)), 'filename': title, 'link': subtitle_id, 'language_name': xbmc.convertLanguage(heb_to_eng(language), xbmc.ENGLISH_NAME), 'language_flag': xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_1), 'id': subtitle_id, 'rating': int(downloads.replace(",", "")), 'sync': subtitle_rate >= 3.8, 'hearing_imp': 0, 'is_preferred': xbmc.convertLanguage(heb_to_eng(language), xbmc.ISO_639_2) == item[ 'preferredlanguage'] }) return ret, total_downloads
def get_languages(params, lang_format = 2): """ Get the requested languages the user want to search (3 letter format) Args: params: The passed parameters dict. lang_format: 0 to get full language name 1 to get two letter code (ISO 639-1) 2 to get three letter code (ISO 639-2/T or ISO 639-2/B) (default) Returns: An array with the requested languages, e.g. ['scc','eng'] """ langs = [] # ['scc','eng'] for lang in urllib.unquote(params['languages']).decode('utf-8').split(","): if lang_format == 0: # Full language name langs.append(lang) elif lang_format == 1: # 2 letter format langs.append(xbmc.convertLanguage(lang, xbmc.ISO_639_1)) else: # 3 letter format langs.append(xbmc.convertLanguage(lang, xbmc.ISO_639_2)) return langs
def Search(item): d = timeout(set_filehash, args=(item["file_original_path"], item["rar"]), timeout_duration=15) md5hash = d.hexdigest() t = f(md5hash) filename = '.'.join(os.path.basename(item["file_original_path"]).split(".")[:-1]) helper = NapiProjektHelper(filename, md5hash) results = helper.search(item, t) for result in results: listitem = xbmcgui.ListItem(label=xbmc.convertLanguage(result["language"], xbmc.ENGLISH_NAME), # language name for the found subtitle label2=filename, # file name for the found subtitle iconImage="5", # rating for the subtitle, string 0-5 thumbnailImage=xbmc.convertLanguage(result["language"], xbmc.ISO_639_1) # language flag, ISO_639_1 language + gif extention, e.g - "en.gif" ) listitem.setProperty("sync", '{0}'.format("true").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 download url = "plugin://%s/?action=download&l=%s&f=%s&filename=%s" % ( __scriptid__, result["language"], md5hash, filename) ## 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)
def main(): """Main entry point of the script when it is invoked by XBMC.""" # Get parameters from XBMC and launch actions params = get_params() if params['action'] == 'search': item = {} item['temp'] = False item['rar'] = False item['year'] = xbmc.getInfoLabel("VideoPlayer.Year") item['season'] = str(xbmc.getInfoLabel("VideoPlayer.Season")) item['episode'] = str(xbmc.getInfoLabel("VideoPlayer.Episode")) item['tvshow'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.TVshowtitle")) # Try to get original title item['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.OriginalTitle")) # Full path of a playing file item['file_original_path'] = urllib.unquote(xbmc.Player().getPlayingFile().decode('utf-8')) item['3let_language'] = [] item['2let_language'] = [] for lang in urllib.unquote(params['languages']).decode('utf-8').split(","): item['3let_language'].append(xbmc.convertLanguage(lang, xbmc.ISO_639_2)) item['2let_language'].append(xbmc.convertLanguage(lang, xbmc.ISO_639_1)) if not item['title']: # No original title, get just Title item['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.Title")) if "s" in item['episode'].lower(): # Check if season is "Special" item['season'] = "0" item['episode'] = item['episode'][-1:] if "http" in item['file_original_path']: item['temp'] = True elif "rar://" in item['file_original_path']: item['rar'] = True item['file_original_path'] = os.path.dirname(item['file_original_path'][6:]) elif "stack://" in item['file_original_path']: stackPath = item['file_original_path'].split(" , ") item['file_original_path'] = stackPath[0][8:] Search(item) elif params['action'] == 'download': # We pickup all our arguments sent from def Search() subs = Download(params["id"], params["filename"]) # We can return more than one subtitle for multi CD versions, for now # we are still working out how to handle that in XBMC core for sub in subs: listitem = xbmcgui.ListItem(label=sub) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=sub, listitem=listitem, isFolder=False) # Send end of directory to XBMC xbmcplugin.endOfDirectory(int(sys.argv[1]))
def _build_subtitle_list(self, search_results, item): ret = [] for result in search_results: total_downloads = 0 counter = 0 subs_list = result["subs"] if subs_list is not None: for language in subs_list.keys(): if xbmc.convertLanguage( language, xbmc.ISO_639_2) in item["3let_language"]: for current in subs_list[language]: counter += 1 title = current["version"] subtitle_rate = self._calc_rating( title, item["file_original_path"]) total_downloads += int(current["downloads"]) ret.append({ 'lang_index': item["3let_language"].index( xbmc.convertLanguage( language, xbmc.ISO_639_2)), 'filename': title, 'link': current["key"], 'language_name': xbmc.convertLanguage(language, xbmc.ENGLISH_NAME), 'language_flag': language, 'id': current["id"], 'rating': current["downloads"], 'sync': subtitle_rate >= 3.8, 'hearing_imp': False, 'is_preferred': xbmc.convertLanguage(language, xbmc.ISO_639_2) == item['preferredlanguage'] }) # Fix the rating if total_downloads: for it in ret[-1 * counter:]: it["rating"] = str( min( int( round( float(it["rating"]) / float(total_downloads), 1) * 8), 5)) return sorted( ret, key=lambda x: (x['is_preferred'], x['lang_index'], x['sync'], x['rating']), reverse=True)
def _set_languages(self): """Set accepted languages.""" self._languages = [] self._languages_codes = [] if 'languages' in self._parameters: for language in urllib.unquote( self._parameters['languages']).decode('utf-8').split(','): self._languages.append( xbmc.convertLanguage(language, xbmc.ENGLISH_NAME)) self._languages_codes.append( xbmc.convertLanguage(language, xbmc.ISO_639_1))
def parse_argv(argv: list) -> dict: log(parse_argv.__name__, f"Parsing arguments: {argv}") param = dict(parse.parse_qsl(sys.argv[2].lstrip('?'))) if 'languages' in param: param['languages'] = param['languages'] \ .replace('original', xbmc.convertLanguage(xbmc.getInfoLabel("VideoPlayer.AudioLanguage"), xbmc.ENGLISH_NAME)) \ .replace('default', xbmc.convertLanguage(xbmc.getInfoLabel("System.Language"), xbmc.ENGLISH_NAME)).split(',') log(parse_argv.__name__, f"Parsed arguments: {param}") return param
def search(): log( __name__, "action 'search' called") item = {} item['temp'] = False item['rar'] = False item['year'] = xbmc.getInfoLabel("VideoPlayer.Year") # Year item['season'] = str(xbmc.getInfoLabel("VideoPlayer.Season")) # Season item['episode'] = str(xbmc.getInfoLabel("VideoPlayer.Episode")) # Episode 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'] = [] # ['scc','eng'] 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'] == "": log( __name__, "VideoPlayer.OriginalTitle not found") item['title'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.Title")) # no original title, get just Title 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:]) log( __name__, item) search_subtitles( item['file_original_path'], item['title'], item['tvshow'], item['year'], item['season'], item['episode'], item['3let_language'])
def parse_profiles(data): """Parse profile information from Netflix response""" profiles_list = jgraph_get_list('profilesList', data) try: if not profiles_list: raise InvalidProfilesError('It has not been possible to obtain the list of profiles.') sort_order = 0 current_guids = [] for index, profile_data in iteritems(profiles_list): # pylint: disable=unused-variable summary = jgraph_get('summary', profile_data) guid = summary['guid'] current_guids.append(guid) LOG.debug('Parsing profile {}', summary['guid']) avatar_url = _get_avatar(profile_data, data, guid) is_active = summary.pop('isActive') G.LOCAL_DB.set_profile(guid, is_active, sort_order) G.SHARED_DB.set_profile(guid, sort_order) # Add profile language description translated from locale summary['language_desc'] = G.py2_decode(xbmc.convertLanguage(summary['language'][:2], xbmc.ENGLISH_NAME)) if LOG.level == LOG.LEVEL_VERBOSE: for key, value in iteritems(summary): if key in PROFILE_DEBUG_INFO: LOG.debug('Profile info {}', {key: value}) # Translate the profile name, is coded as HTML summary['profileName'] = parse_html(summary['profileName']) summary['avatar'] = avatar_url G.LOCAL_DB.insert_profile_configs(summary, guid) sort_order += 1 _delete_non_existing_profiles(current_guids) except Exception as exc: # pylint: disable=broad-except import traceback LOG.error(G.py2_decode(traceback.format_exc(), 'latin-1')) LOG.error('Profile list data: {}', profiles_list) raise_from(InvalidProfilesError, exc)
def search(self, item, t, langs): fulllang = xbmc.convertLanguage(item['preferredlanguage'], xbmc.ENGLISH_NAME) if fulllang == "Persian": fulllang = "Farsi/Persian" #xbmc.executebuiltin("Notification(Title," + item['mansearchstr'] + ")") QueryString = self.filename; if item['mansearch']: QueryString = item['mansearchstr']; addon = xbmcaddon.Addon(); if len(QueryString) < 6: xbmc.executebuiltin("Notification(" + addon.getLocalizedString(32003) + "," + addon.getLocalizedString(32002) + ")") return url = "http://www.subtitool.com/api/?query=" + QueryString + "&Lang=" + langs subs = urllib.urlopen(url).read() DOMTree = minidom.parseString(subs) if DOMTree.getElementsByTagName('Subtitle').length == 0: try: url = "http://www.subtitool.com/api/?query=" + QueryString + "&Lang=" + langs + "&OR=1" subs = urllib.urlopen(url).read() DOMTree = minidom.parseString(subs) except Exception, e: log("Subtitool","Not Found OR") try: url = "http://www.subtitool.com/api/?query=" + QueryString + "&Lang=" + langs subs = urllib.urlopen(url).read() DOMTree = minidom.parseString(subs) except Exception, e: log("Subtitool","Not Found")
def _add_subtitle(self, action, path, label, language): list_item = xbmcgui.ListItem(label=xbmc.convertLanguage( language, xbmc.ENGLISH_NAME), label2=label) list_item.setArt({ "icon": "0", "thumb": xbmc.convertLanguage(language, xbmc.ISO_639_1) }) # list_item.setProperty("sync", "false") # list_item.setProperty("hearing_imp", "false") url = "plugin://{}/?{}".format( self._id, urlencode(dict(action=action, path=path, language=language))) xbmcplugin.addDirectoryItem(self._handle, url, list_item)
def on_subtitle_found(self, subtitle): """Event handler called when a matching subtitle has been found. :param subtitle: Subtitle details :type subtitle: dict of [str, unicode] """ self.info(u'Found {0} subtitle {1}:{2}'.format(subtitle['language'], subtitle['url'], subtitle['filename'])) list_item = xbmcgui.ListItem( label=subtitle['language'], label2=os.path.basename(subtitle['filename']), iconImage=subtitle['rating'], thumbnailImage=xbmc.convertLanguage(subtitle['language'], xbmc.ISO_639_1), ) list_item.setProperty('sync', 'false') list_item.setProperty('hearing_imp', 'false') url = u'plugin://{0}/?action=download&url={1}&filename={2}'.format( __scriptid__, subtitle['url'], subtitle['filename']) xbmcplugin.addDirectoryItem(handle=self._handle, url=url, listitem=list_item, isFolder=False)
def append_subtitle(subname, lang_name, language, params, sync=False, h_impaired=False): listitem = xbmcgui.ListItem( # Languange name to display under the lang logo (for example english) label=lang_name, # Subtitle name (for example 'Lost 1x01 720p') label2=subname, # Languange 2 letter name (for example en) thumbnailImage=xbmc.convertLanguage(language, xbmc.ISO_639_1)) # Subtitles synced with the video listitem.setProperty("sync", 'true' if sync else 'false') # Hearing impaired subs listitem.setProperty("hearing_imp", 'true' if h_impaired else 'false') # Create the url to the plugin that will handle the subtitle download url = "plugin://{url}/?{params}".format(url=SCRIPT_ID, params=urllib.urlencode(params)) # Add the subtitle to the list xbmcplugin.addDirectoryItem(handle=HANDLE, url=url, listitem=listitem, isFolder=False)
def search_by_language(string, language): results = [] html_parser = HTMLParser.HTMLParser() if language in SUBTITLE_LANGUAGES: log('Searching for %s subtitles: %s' % (language, string)) # Language specific stuff search_url = SUBTITLE_LANGUAGES[language]['search_url'] regex_pattern = SUBTITLE_LANGUAGES[language]['regex_pattern'] priority = SUBTITLE_LANGUAGES[language]['priority'] # Get content content = get_content_from_url(search_url % urllib.quote(string.encode('latin'))) # Parse results pattern = re.compile(regex_pattern) matches = pattern.finditer(content) # Loop through all matches for match in matches: results.append({ 'name' : html_parser.unescape(match.group(2)).decode('latin'), 'language' : language, 'language_code' : xbmc.convertLanguage(language, xbmc.ISO_639_1), 'download_url' : match.group(1), 'priority' : priority }) else: log('Unsupported language: %s' % language) return results
def onPlayBackStarted(self): check_for_specific = (__addon__.getSetting('check_for_specific').lower() == 'true') specific_language = (__addon__.getSetting('selected_language')) specific_language = xbmc.convertLanguage(specific_language, xbmc.ISO_639_2) if self.run: movieFullPath = xbmc.Player().getPlayingFile() Debug("movieFullPath '%s'" % movieFullPath) xbmc.sleep(1000) availableLangs = xbmc.Player().getAvailableSubtitleStreams() Debug("availableLangs '%s'" % availableLangs) totalTime = xbmc.Player().getTotalTime() Debug("totalTime '%s'" % totalTime) videoclipAlbum = '' if getSettingAsBool('ExcludeVideoClip'): videoclipAlbum = xbmc.InfoTagMusic.getAlbum() Debug("videoclipAlbum '%s'" % videoclipAlbum) if (xbmc.Player().isPlayingVideo() and totalTime > ExcludeTime and (not videoclipAlbum) and ((not xbmc.getCondVisibility("VideoPlayer.HasSubtitles")) or (check_for_specific and not specific_language in availableLangs)) and all(movieFullPath.find (v) <= -1 for v in ignore_words) and (isExcluded(movieFullPath)) ): self.run = False xbmc.sleep(1000) Debug('Started: AutoSearching for Subs') xbmc.executebuiltin('XBMC.ActivateWindow(SubtitleSearch)') else: Debug('Started: Subs found or Excluded') self.run = False
def onPlayBackStarted(self): check_for_specific = ( __addon__.getSetting('check_for_specific').lower() == 'true') specific_language = (__addon__.getSetting('selected_language')) specific_language = xbmc.convertLanguage(specific_language, xbmc.ISO_639_2) if self.run: movieFullPath = xbmc.Player().getPlayingFile() Debug("movieFullPath '%s'" % movieFullPath) xbmc.sleep(1000) availableLangs = xbmc.Player().getAvailableSubtitleStreams() Debug("availableLangs '%s'" % availableLangs) totalTime = xbmc.Player().getTotalTime() Debug("totalTime '%s'" % totalTime) if (xbmc.Player().isPlayingVideo() and totalTime > ExcludeTime and ((not xbmc.getCondVisibility("VideoPlayer.HasSubtitles")) or (check_for_specific and not specific_language in availableLangs)) and all(movieFullPath.find(v) <= -1 for v in ignore_words) and (isExcluded(movieFullPath))): self.run = False xbmc.sleep(1000) Debug('Started: Procura automatica de legendas') xbmc.executebuiltin('XBMC.ActivateWindow(SubtitleSearch)') else: Debug('Started: Legendas nao encontradas ou excluidas') self.run = False
def collect_initial_data(): item_data = { 'temp': False, 'rar': False, '3let_language': [], 'preferredlanguage': unquote(params.get('preferredlanguage', '')) } item_data['preferredlanguage'] = xbmc.convertLanguage(item_data['preferredlanguage'], xbmc.ISO_639_2) if xbmc.Player().isPlaying(): item_data['year'] = xbmc.getInfoLabel("VideoPlayer.Year") # Year item_data['season'] = str(xbmc.getInfoLabel("VideoPlayer.Season")) # Season item_data['episode'] = str(xbmc.getInfoLabel("VideoPlayer.Episode")) # Episode item_data['tvshow'] = normalizeString(xbmc.getInfoLabel("VideoPlayer.TVshowtitle")) # Show item_data['title'] = normalizeString( xbmc.getInfoLabel("VideoPlayer.OriginalTitle")) # try to get original title item_data['file_original_path'] = unquote(xbmc.Player().getPlayingFile()) # Full path of a playing file if item_data['title'] == "": log("VideoPlayer.OriginalTitle not found") item_data['title'] = normalizeString( xbmc.getInfoLabel("VideoPlayer.Title")) # no original title, get just Title else: item_data['year'] = xbmc.getInfoLabel("ListItem.Year") item_data['season'] = xbmc.getInfoLabel("ListItem.Season") item_data['episode'] = xbmc.getInfoLabel("ListItem.Episode") item_data['tvshow'] = xbmc.getInfoLabel("ListItem.TVShowTitle") item_data['title'] = title_from_focused_item(item_data) item_data['file_original_path'] = "" return item_data
def _get_default_audio_language(manifest): channelList = {'1.0': '1', '2.0': '2'} channelListDolby = {'5.1': '6', '7.1': '8'} # Read language in kodi settings audio_language = common.json_rpc('Settings.GetSettingValue', {'setting': 'locale.audiolanguage'}) audio_language = xbmc.convertLanguage(audio_language['value'], xbmc.ISO_639_1) audio_language = audio_language if audio_language else xbmc.getLanguage(xbmc.ISO_639_1, False) audio_language = audio_language if audio_language else 'en' # Try to find the preferred language with the right channels if g.ADDON.getSettingBool('enable_dolby_sound'): for index, audio_track in enumerate(manifest['audio_tracks']): if audio_track['language'] == audio_language and audio_track['channels'] in channelListDolby: return index break # If dolby audio track not exists check other channels list for index, audio_track in enumerate(manifest['audio_tracks']): if audio_track['language'] == audio_language and audio_track['channels'] in channelList: return index break # If there is no matches to preferred language, try to sets the original language track as default # Check if the dolby audio track in selected language exists if g.ADDON.getSettingBool('enable_dolby_sound'): for index, audio_track in enumerate(manifest['audio_tracks']): if audio_track['isNative'] and audio_track['channels'] in channelListDolby: return index break # If dolby audio track not exists check other channels list for index, audio_track in enumerate(manifest['audio_tracks']): if audio_track['isNative'] and audio_track['channels'] in channelList: return index break return 0
def parse_profiles(data): """Parse profile information from Netflix response""" profiles_list = jgraph_get_list('profilesList', data) try: if not profiles_list: raise InvalidProfilesError('It has not been possible to obtain the list of profiles.') sort_order = 0 current_guids = [] for index, profile_data in iteritems(profiles_list): # pylint: disable=unused-variable summary = jgraph_get('summary', profile_data) guid = summary['guid'] current_guids.append(guid) common.debug('Parsing profile {}', summary['guid']) avatar_url = _get_avatar(profile_data, data, guid) is_active = summary.pop('isActive') g.LOCAL_DB.set_profile(guid, is_active, sort_order) g.SHARED_DB.set_profile(guid, sort_order) # Add profile language description translated from locale summary['language_desc'] = g.py2_decode(xbmc.convertLanguage(summary['language'][:2], xbmc.ENGLISH_NAME)) for key, value in iteritems(summary): if key in PROFILE_DEBUG_INFO: common.debug('Profile info {}', {key: value}) if key == 'profileName': # The profile name is coded as HTML value = parse_html(value) g.LOCAL_DB.set_profile_config(key, value, guid) g.LOCAL_DB.set_profile_config('avatar', avatar_url, guid) sort_order += 1 _delete_non_existing_profiles(current_guids) except Exception: import traceback common.error(g.py2_decode(traceback.format_exc(), 'latin-1')) common.error('Profile list data: {}', profiles_list) raise InvalidProfilesError
def search(info, languages): """Add subtitles to the list using information gathered with get_info and get_languages""" logging.debug("---TUCAN---") logging.debug(info) url = addictedutils.build_show_url( addictedutils.get_show_id(info['tvshow']), info['season'], addictedutils.build_language_code_string(languages)) logging.debug(url) subs = addictedutils.subs_array(url, info) #logging.debug(subs) for sub in subs: sub_name = sub['showTitle'] + " " + sub['season'] + "x" + sub['episode'] + " " + sub['version'] sub_params = { "action": "download-addicted", "link": sub['link'], "name": sub_name } append_subtitle( sub_name, sub['lang'], xbmc.convertLanguage(sub['lang'], xbmc.ISO_639_2), sub_params, sub['sync'], sub['himp'])
def _action_search(self): self.search() sorter = sublib.sub.sorter(self.item.languages[0]) self._subs.sort(key=sorter.method, reverse=True) for sub in self._subs: if sub.iso not in self.item.languages and len(sub.iso) == 2: continue listitem = xbmcgui.ListItem( label=xbmc.convertLanguage(sub.iso, xbmc.ENGLISH_NAME), label2=sub.label, iconImage=str(sub.rating), thumbnailImage=sub.iso ) listitem.setProperty("sync", '{0}'.format(sub.sync).lower()) listitem.setProperty("hearing_imp", '{0}'.format(sub.cc).lower()) args = { "action": "download", "args": sub.args, "kwargs": sub.kwargs, "languages": self._params['languages'], "prefferedlanguage": self._params['preferredlanguage'] } url = urllib.urlencode(sublib.utils.dformat(args, json.dumps)) url = "plugin://%s/?%s" % (self._sid, url) xbmcplugin.addDirectoryItem( handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=False )
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)
def get_language(abbrev): try: lang_string = (key for key,value in LANGUAGES.items() if value == abbrev).next() except: lang_string = xbmc.convertLanguage(abbrev, xbmc.ENGLISH_NAME) if not lang_string: lang_string = 'n/a' return lang_string
def _build_subtitle_list(self, search_results, item): language = 'he' lang3 = xbmc.convertLanguage(language, xbmc.ISO_639_2) total_downloads = 0 ret = [] for result in search_results: title = result["rls"] subtitle_rate = self._calc_rating(title, item["file_original_path"]) total_downloads += result['downloads'] ret.append({ 'lang_index': item["3let_language"].index(lang3), 'filename': title, 'language_name': xbmc.convertLanguage(language, xbmc.ENGLISH_NAME), 'language_flag': language, 'id': result["id"], 'sub_id': result["sub_id"], 'rating': result['downloads'], 'sync': subtitle_rate >= 3.8, 'hearing_imp': False, 'is_preferred': lang3 == item['preferredlanguage'] }) # Fix the rating if total_downloads: for it in ret: log('rating %s totals %s' % (it['rating'], total_downloads)) it["rating"] = str( int(round(it["rating"] / float(total_downloads), 1) * 5)) return sorted( ret, key=lambda x: (x['is_preferred'], x['lang_index'], x['sync'], x['rating']), reverse=True)
def get_kodi_audio_language(): """ Return the audio language from Kodi settings """ audio_language = json_rpc('Settings.GetSettingValue', {'setting': 'locale.audiolanguage'}) audio_language = xbmc.convertLanguage(audio_language['value'].encode('utf-8'), xbmc.ISO_639_1) audio_language = audio_language if audio_language else xbmc.getLanguage(xbmc.ISO_639_1, False) return audio_language if audio_language else 'en'
def search(self,item): if item['mansearch']: title = item['mansearchstr'] dialog = xbmcgui.Dialog() item['season'] = dialog.numeric(0, self._t(32111), item['season']) item['episode'] = dialog.numeric(0, self._t(32112), item['episode']) else: title = self.normalize_input_title(item['tvshow']) if self.addon.getSetting("ignore_articles") == "true" and re.match(r'^The ',title,re.IGNORECASE): log(__name__, "Ignoring The in Title") title = re.sub(r'(?i)^The ',"", title) if not title or not item['season'] or not item['episode']: xbmc.executebuiltin("XBMC.Notification(%s,%s,5000,%s)" % ( self.addon.getAddonInfo('name'), self._t(32110), os.path.join(xbmc.translatePath(self.addon.getAddonInfo('path')).decode("utf-8"),'icon.png') )) log(__name__, ["Input validation error", title, item['season'], item['episode']]) return results_with_stats(None, self.addon, title, item) tvshow_url = self.search_show_url(title) if tvshow_url == None: return results_with_stats(None, self.addon, title, item) file_size = get_file_size(item['file_original_path'], item['rar']) log(__name__, "File size: %s" % file_size) found_season_subtitles = self.search_season_subtitles(tvshow_url,item['season']) log(__name__, ["Season filter", found_season_subtitles]) episode_subtitle_list = self.filter_episode_from_season_subtitles(found_season_subtitles,item['season'],item['episode']) log(__name__, ["Episode filter", episode_subtitle_list]) if episode_subtitle_list == None: return results_with_stats(None, self.addon, title, item) lang_filetred_episode_subtitle_list = self.filter_subtitles_by_language(item['3let_language'], episode_subtitle_list) log(__name__, ["Language filter", lang_filetred_episode_subtitle_list]) if lang_filetred_episode_subtitle_list == None: return results_with_stats(None, self.addon, title, item) max_down_count = self.detect_max_download_stats(lang_filetred_episode_subtitle_list) result_subtitles = [] for episode_subtitle in lang_filetred_episode_subtitle_list['versions']: print_out_filename = episode_subtitle['rip'] + " by " + episode_subtitle['author'] if episode_subtitle['notes']: print_out_filename += " (" + episode_subtitle['notes'] + ")" result_subtitles.append({ 'filename': HTMLParser.HTMLParser().unescape(print_out_filename), 'link': episode_subtitle['link'], 'lang': episode_subtitle['lang'], 'rating': str(episode_subtitle['down_count']*5/max_down_count) if max_down_count > 0 else "0", 'sync': (episode_subtitle['file_size'] == file_size and file_size > 0), 'lang_flag': xbmc.convertLanguage(episode_subtitle['lang'],xbmc.ISO_639_1), }) log(__name__,["Search result", result_subtitles]) return results_with_stats(result_subtitles, self.addon, title, item)
def get_language(abbrev): try: lang_string = (key for key, value in LANGUAGES.items() if value == abbrev).next() except: lang_string = xbmc.convertLanguage(abbrev, xbmc.ENGLISH_NAME) if not lang_string: lang_string = 'n/a' return lang_string
def display_movie(title, movieurl): divpname = re.search(r"/title/(.*.)", movieurl).group(1) log('MOVIE ID: %s' % divpname) (req, page) = load_url(movieurl) subtitles_list = [] tb = page.find(id='subtable') links = tb.findAll('a', class_='download-btn') for link in links: addr = link['href'] s_tr = link.find_parent('tr') tr_id = re.sub('row_id', '', s_tr['id']) s_tr2 = page.find('tr', id="row_id_alt%s" % tr_id) s_tr3 = page.find('tr', id="row_id_note%s" % tr_id) lantext = s_tr.find('img')['src'] if lantext: if "en.png" in lantext: language = "English" lan_short = "en" elif "tr.png" in lantext: language = "Turkish" lan_short = "tr" else: raise ValueError("unsupported language: %s" % lantext) filename = u"%s.%s" % (title, lan_short) dtd = s_tr3.find('td').text description = dtd[dtd.index(' :') + 2:dtd.index(' - ')] log('description and filename:'), log(description) log(filename) l_item = xbmcgui.ListItem( label=language, # language name for the found subtitle label2=description, # file name for the found subtitle iconImage="0", # rating for the subtitle, string 0-5 thumbnailImage=xbmc.convertLanguage(language, xbmc.ISO_639_1) ) # set to "true" if subtitle is for hearing impared l_item.setProperty("hearing_imp", '{0}'.format("false").lower()) subtitles_list.append(l_item) url = "plugin://%s/?action=download&link=%s&lang=%s&description=%s&season=%s" % ( __scriptid__, addr, lan_short, normalize_filename(filename), "" ) xbmcplugin.addDirectoryItem( handle=int(sys.argv[1]), url=url, listitem=l_item, isFolder=False ) log("PlanetDP: found %d subtitles from %s" % (len(subtitles_list), len(links)))
def _build_subtitle_list(self, search_results, item): ret = [] for result in search_results: subs_list = result["subs"] if subs_list is not None: for language in subs_list.keys(): if xbmc.convertLanguage( language, xbmc.ISO_639_2) in item["3let_language"]: for current in subs_list[language]: title = current["SubtitleName"] subtitle_rate = self._calc_rating( title, item["file_original_path"]) ret.append({ 'lang_index': item["3let_language"].index( xbmc.convertLanguage( language, xbmc.ISO_639_2)), 'filename': title, 'language_name': xbmc.convertLanguage(language, xbmc.ENGLISH_NAME), 'language_flag': language, 'id': current["Identifier"], 'rating': '5', 'sync': subtitle_rate >= 3.8, 'hearing_imp': False, 'is_preferred': xbmc.convertLanguage(language, xbmc.ISO_639_2) == item['preferredlanguage'] }) return sorted( ret, key=lambda x: (x['is_preferred'], x['lang_index'], x['sync'], x['rating']), reverse=True)
def onInit(self): self.getControl(1).setLabel( "Artwork Beef: " + L(CHOOSE_ART_HEADER).format(self.arttype, self.medialabel)) self.getControl(3).setVisible(False) self.getControl(5).setVisible(self.multi) self.getControl(5).setLabel('$LOCALIZE[186]') self.guilist = self.getControl(6) for image in self.artlist: provider = image['provider'].display if isinstance(provider, int): provider = L(provider) secondprovider = image.get('second provider') if secondprovider: if isinstance(secondprovider, int): secondprovider = L(secondprovider) provider = '{0}, {1}'.format(provider, secondprovider) title = image.get('title') if not title and 'subtype' in image: title = image['subtype'].display language = xbmc.convertLanguage( image['language'], xbmc.ENGLISH_NAME) if image.get('language') else None if not title: title = language if title and len(title) < 20 and not secondprovider: label = '{0} from {1}'.format(title, provider) summary = language if language and language != title else '' else: label = provider if language and language != title: title = language + ' ' + title summary = title if title else '' rating = image.get('rating') size = image.get('size') if (rating or size) and summary: summary += '\n' if size: summary += image['size'].display if rating and size: summary += ' ' if rating: summary += image['rating'].display listitem = xbmcgui.ListItem(label) listitem.setLabel2(summary) # DEPRECATED: Above Krypton and higher (only), below Jarvis and lower (only) listitem.setProperty('Addon.Summary', summary) listitem.setIconImage(image['preview']) # DEPRECATED: Above is deprecated in Jarvis, but still works through Krypton (at least) # listitem.setArt({'icon': image['preview']}) listitem.setPath(image['url']) if image.get('existing'): listitem.select(True) self.guilist.addItem(listitem) self.setFocus(self.guilist)
def get_languages_dict(languages_param): langs = {} for lang in languages_param.split(','): if lang == "Portuguese (Brazil)": langs["pob"] = lang elif lang == "Greek": langs["ell"] = lang else: langs[xbmc.convertLanguage(lang, xbmc.ISO_639_2)] = lang return langs
def get_language(language_format=xbmc.ENGLISH_NAME, region=False): language = xbmc.getLanguage(language_format, region) if not language or region and language.startswith('-'): engname = xbmc.getLanguage(xbmc.ENGLISH_NAME) regiontag = language if ' (' in engname: language = engname[:engname.rfind(' (')] if language_format != xbmc.ENGLISH_NAME: language = xbmc.convertLanguage(language, language_format) + regiontag return language
def get_abbrev(lang_string): try: language_abbrev = xbmc.convertLanguage(lang_string, xbmc.ISO_639_1) except: language_abbrev = REAL_SETTINGS.getSetting('limit_preferred_language') if language_abbrev in LANGUAGES: return LANGUAGES[language_abbrev] else: language_abbrev = 'en' ### Default to English if conversion fails return language_abbrev
def _build_subtitle_list(self, search_results, item): ret = [] for result in search_results: total_downloads = 0 counter = 0 url = self.BASE_URL + "cinemast/data/" + result["type"] + "/sb/" + result["slug"] url += "/" + item["season"] + "/" + item["episode"] + "/" if result["type"] == "series" else "/" subs_list = self.urlHandler.request(url) if subs_list is not None: if not isinstance(subs_list, dict): subs_list = json.loads(subs_list, encoding="utf-8") for language in subs_list: if xbmc.convertLanguage(language, xbmc.ISO_639_2) in item["3let_language"]: for translator in subs_list[language]: for quality in subs_list[language][translator]: for current in subs_list[language][translator][quality]: current = subs_list[language][translator][quality][current] counter += 1 title = current["subtitle_version"] subtitle_rate = self._calc_rating(title, item["file_original_path"]) total_downloads += current["downloaded"] ret.append( {'lang_index': item["3let_language"].index( xbmc.convertLanguage(language, xbmc.ISO_639_2)), 'filename': title, 'link': current["key"], 'language_name': xbmc.convertLanguage(language, xbmc.ENGLISH_NAME), 'language_flag': language, 'id': current["id"], 'rating': current["downloaded"], 'sync': subtitle_rate >= 3.8, 'hearing_imp': current["hearing_impaired"] > 0, 'is_preferred': xbmc.convertLanguage(language, xbmc.ISO_639_2) == item[ 'preferredlanguage'] }) # Fix the rating if total_downloads: for it in ret[-1 * counter:]: it["rating"] = str(min(int(round(float(it["rating"]) / float(total_downloads), 1) * 8), 5)) return sorted(ret, key=lambda x: (x['is_preferred'], x['lang_index'], x['sync'], x['rating']), reverse=True)
def convert_language_iso_639_2(name): """ Returns the given language converted to the ISO 639-2 format as a string. """ try: language = iso_639_2_languages[name] except KeyError: language = xbmc.convertLanguage(name, xbmc.ISO_639_2) return language
def get(name, imdb, season, episode): try: langs = [] try: langs.append(langDict[control.setting('sublang1')]) except: pass try: langs.append(langDict[control.setting('sublang2')]) except: pass try: subLang = xbmc.Player().getSubtitles() except: subLang = '' if subLang == langs[0]: raise Exception() server = xmlrpclib.Server('http://api.opensubtitles.org/xml-rpc', verbose=0) token = server.LogIn('', '', 'en', 'XBMC_Subtitles_v1')['token'] sublanguageid = ','.join(langs) ; imdbid = re.sub('[^0-9]', '', imdb) if not (season == '' or episode == ''): result = server.SearchSubtitles(token, [{'sublanguageid': sublanguageid, 'imdbid': imdbid, 'season': season, 'episode': episode}])['data'] fmt = ['hdtv'] else: result = server.SearchSubtitles(token, [{'sublanguageid': sublanguageid, 'imdbid': imdbid}])['data'] try: vidPath = xbmc.Player().getPlayingFile() except: vidPath = '' fmt = re.split('\.|\(|\)|\[|\]|\s|\-', vidPath) fmt = [i.lower() for i in fmt] fmt = [i for i in fmt if i in quality] filter = [] result = [i for i in result if i['SubSumCD'] == '1'] for lang in langs: filter += [i for i in result if i['SubLanguageID'] == lang and any(x in i['MovieReleaseName'].lower() for x in fmt)] filter += [i for i in result if i['SubLanguageID'] == lang and any(x in i['MovieReleaseName'].lower() for x in quality)] filter += [i for i in result if i['SubLanguageID'] == lang] try: lang = xbmc.convertLanguage(filter[0]['SubLanguageID'], xbmc.ISO_639_1) except: lang = filter[0]['SubLanguageID'] content = [filter[0]['IDSubtitleFile'],] content = server.DownloadSubtitles(token, content) content = base64.b64decode(content['data'][0]['data']) content = zlib.decompressobj(16+zlib.MAX_WBITS).decompress(content) subtitle = xbmc.translatePath('special://temp/') subtitle = os.path.join(subtitle, 'TemporarySubs.%s.srt' % lang) file = control.openFile(subtitle, 'w') file.write(str(content)) file.close() xbmc.sleep(1000) xbmc.Player().setSubtitles(subtitle) except: pass
def check_active_player(): global videofilename if xbmc.Player().isPlayingVideo(): current_subs = xbmc.Player().getAvailableSubtitleStreams() playingfile = xbmc.Player().getPlayingFile() if any(current_subs): active_sub_lang = xbmc.Player().getSubtitles() lang = xbmc.convertLanguage(active_sub_lang, xbmc.ISO_639_1) if not lang: filename = os.path.splitext(playingfile)[0] + ".srt" else: filename = os.path.splitext( playingfile)[0] + "." + lang + ".srt" if xbmcvfs.exists(filename): subtitlefile, filename = load_subtitle(False, filename) videofilename = playingfile if len(os.path.basename(playingfile)) < 50: playbase = os.path.basename(playingfile) subbase = os.path.basename(filename) else: playbase = os.path.basename( playingfile)[:35] + "(...)" + os.path.basename( playingfile)[-10:] subbase = os.path.basename( filename)[:35] + "(...)" + os.path.basename( filename)[-10:] result = xbmcgui.Dialog().yesno( _(31001), _(35003) + "\n" + _(35006).ljust(11) + playbase + "\n" + _(35007).ljust(11) + subbase + "\n" + _(35004), yeslabel=_(35000), nolabel=_(35001)) if not result: xbmc.Player().stop() show_dialog(subtitlefile, filename) else: sys.exit() res = xbmcgui.Dialog().yesno(_(31001), _(35005) + "\n" + _(35004), nolabel=_(35000), yeslabel=_(35002)) if not res: sys.exit() playing_dir = os.path.dirname(playingfile) + "/" filename = xbmcgui.Dialog().browse(1, _(32035), 'files', ".srt|.sub", False, False, playing_dir) if filename == playing_dir: sys.exit() videofilename = playingfile subtitlefile, filename = load_subtitle(False, filename) xbmc.Player().stop() show_dialog(subtitlefile, filename) show_dialog()
def get_kodi_subtitle_language(): """ Return the subtitle language from Kodi settings """ subtitle_language = json_rpc('Settings.GetSettingValue', {'setting': 'locale.subtitlelanguage'}) if subtitle_language['value'] == 'forced_only': return subtitle_language['value'] subtitle_language = xbmc.convertLanguage(subtitle_language['value'].encode('utf-8'), xbmc.ISO_639_1) subtitle_language = subtitle_language if subtitle_language else xbmc.getLanguage(xbmc.ISO_639_1, False) subtitle_language = subtitle_language if subtitle_language else 'en' return subtitle_language
def convert_language_iso(from_value, use_fallback=True): """ Convert language code from an English name or three letter code (ISO 639-2) to two letter code (ISO 639-1) :param use_fallback: if True when the conversion fails, is returned the current Kodi active language """ converted_lang = xbmc.convertLanguage(g.py2_encode(from_value), xbmc.ISO_639_1) if not use_fallback: return converted_lang converted_lang = converted_lang if converted_lang else xbmc.getLanguage(xbmc.ISO_639_1, False) return converted_lang if converted_lang else 'en'
def create_subs_list(subs): for sub in subs: filename = "[" + str(sub["version"].encode('utf8')) + "]" + str(sub["showTitle"].encode('utf8')) + " - " + str(sub["episodeTitle"].encode('utf8')) + " " + "S" + str(sub["season"]) + "E" + str(format(int(sub["episode"]), "02d")) listitem = xbmcgui.ListItem(label = sub["lang"], label2 = filename, iconImage = "", thumbnailImage = xbmc.convertLanguage(sub['lang'], xbmc.ISO_639_1)) listitem.setProperty("hearing_imp", sub["hi"]) url = u'plugin://' + __scriptid__ + u'/?action=download&link=' + sub["link"] + u'&filename=' + filename.decode('utf8') # url = u'plugin://%s/?action=download&link=%s&filename=%s' % (__scriptid__.encode('utf8'), sub["link"].encode('utf8'), str(filename.encode('utf8'))) xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]),url=url,listitem=listitem,isFolder=False)
def getsubtitles(name, tag, season, episode,lang1=None,lang2=None): quality = ['bluray', 'hdrip', 'brrip', 'bdrip', 'dvdrip', 'webrip', 'hdtv'] langDict = {'Afrikaans': 'afr', 'Albanian': 'alb', 'Arabic': 'ara', 'Armenian': 'arm', 'Basque': 'baq', 'Bengali': 'ben', 'Bosnian': 'bos', 'Breton': 'bre', 'Bulgarian': 'bul', 'Burmese': 'bur', 'Catalan': 'cat', 'Chinese': 'chi', 'Croatian': 'hrv', 'Czech': 'cze', 'Danish': 'dan', 'Dutch': 'dut', 'English': 'eng', 'Esperanto': 'epo', 'Estonian': 'est', 'Finnish': 'fin', 'French': 'fre', 'Galician': 'glg', 'Georgian': 'geo', 'German': 'ger', 'Greek': 'ell', 'Hebrew': 'heb', 'Hindi': 'hin', 'Hungarian': 'hun', 'Icelandic': 'ice', 'Indonesian': 'ind', 'Italian': 'ita', 'Japanese': 'jpn', 'Kazakh': 'kaz', 'Khmer': 'khm', 'Korean': 'kor', 'Latvian': 'lav', 'Lithuanian': 'lit', 'Luxembourgish': 'ltz', 'Macedonian': 'mac', 'Malay': 'may', 'Malayalam': 'mal', 'Manipuri': 'mni', 'Mongolian': 'mon', 'Montenegrin': 'mne', 'Norwegian': 'nor', 'Occitan': 'oci', 'Persian': 'per', 'Polish': 'pol', 'Portuguese': 'por,pob', 'Portuguese(Brazil)': 'pob,por', 'Romanian': 'rum', 'Russian': 'rus', 'Serbian': 'scc', 'Sinhalese': 'sin', 'Slovak': 'slo', 'Slovenian': 'slv', 'Spanish': 'spa', 'Swahili': 'swa', 'Swedish': 'swe', 'Syriac': 'syr', 'Tagalog': 'tgl', 'Tamil': 'tam', 'Telugu': 'tel', 'Thai': 'tha', 'Turkish': 'tur', 'Ukrainian': 'ukr', 'Urdu': 'urd'} print '##name',name print '##tag',tag langs = [] try: langs.append(langDict[lang1]) except: pass try: langs.append(langDict[lang2]) except: pass langs = ','.join(langs) import xmlrpclib counterloop = 0 result = [] while not result and counterloop <=5 : try: server = xmlrpclib.Server('http://api.opensubtitles.org/xml-rpc', verbose=0) token = server.LogIn('', '', 'en', 'XBMC_Subtitles_v1')['token'] if not (season == '' or episode == ''): result = server.SearchSubtitles(token, [{'query': name, 'sublanguageid': langs, 'season': season, 'episode': episode}])['data'] else: result = server.SearchSubtitles(token, [{'query': name, 'sublanguageid': langs }])['data'] result = [i for i in result if i['SubSumCD'] == '1'] except: pass counterloop = counterloop + 1 print '##counterloop',counterloop #print '#all',result subtitles = [] for lang in langs.split(','): filter = [i for i in result if lang == i['SubLanguageID']] if filter == []: continue print tag subtitles += [i for i in filter if tag.lower() in i['MovieReleaseName'].lower()] print '#tagresult',subtitles for q in quality: subtitles += [i for i in filter if q in i['MovieReleaseName'].lower()] subtitles += [i for i in filter if not any(x in i['MovieReleaseName'].lower() for x in quality)] try: lang = xbmc.convertLanguage(lang, xbmc.ISO_639_1) except: pass break import zlib, base64 content = [subtitles[0]["IDSubtitleFile"],] content = server.DownloadSubtitles(token, content) content = base64.b64decode(content['data'][0]['data']) content = zlib.decompressobj(16+zlib.MAX_WBITS).decompress(content) subtitle = xbmc.translatePath('special://temp/') subtitle = os.path.join(subtitle, 'TemporarySubs.%s.srt' % lang) file = open(subtitle, 'wb') file.write(content) file.close() return subtitle
def convert(item): ret = {'filename': item['fnev'], 'name': item['nev'].strip(), 'language_hun': item['language'], 'id': item['felirat'], 'uploader': item['feltolto'].strip(), 'hearing': False, 'language_eng': lang_hun2eng(item['language'])} score = int(item['pontos_talalat'], 2) ret['score'] = score ret['rating'] = str(score * 5 / 7) ret['sync'] = score >= 6 ret['flag'] = xbmc.convertLanguage(ret['language_eng'], xbmc.ISO_639_1) ret['seasonpack'] = item['evadpakk'] == '1' return ret
def _build_subtitle_list(self, search_results, item): ret = [] total_downloads = 0 for result in search_results: url = self.BASE_URL + "/he/cinemast/data/" + result["type"] + "/sb/" + result["slug"] url += "/" + item["season"] + "/" + item["episode"] + "/" if result["type"] == "series" else "/" subs_list = self.urlHandler.request(url) if subs_list is not None: subs_list = json.loads(subs_list, encoding="utf-8") for language in subs_list.keys(): if xbmc.convertLanguage(language, xbmc.ISO_639_2) in item["3let_language"]: for translator_group in subs_list[language]: for quality in subs_list[language][translator_group]: for index in subs_list[language][translator_group][quality]: current = subs_list[language][translator_group][quality][index] title = current["subtitle_version"] subtitle_rate = self._calc_rating(title, item["file_original_path"]) total_downloads += current["downloaded"] ret.append( {'lang_index': item["3let_language"].index( xbmc.convertLanguage(language, xbmc.ISO_639_2)), 'filename': title, 'link': current["key"], 'language_name': xbmc.convertLanguage(language, xbmc.ENGLISH_NAME), 'language_flag': language, 'id': current["id"], 'rating': str(current["downloaded"]), 'sync': subtitle_rate >= 3.8, 'hearing_imp': current["hearing_impaired"] > 0, 'is_preferred': xbmc.convertLanguage(language, xbmc.ISO_639_2) == item[ 'preferredlanguage'] }) # Fix the rating if total_downloads: for it in ret: it["rating"] = str(int(round(float(it["rating"]) / float(total_downloads), 1) * 5)) return sorted(ret, key=lambda x: (x['is_preferred'], x['lang_index'], x['sync'], x['rating']), reverse=True)
def onInit(self): self.getControl(1).setLabel(L(CHOOSE_ART_HEADER).format(self.arttype, self.medialabel)) self.getControl(3).setVisible(False) self.getControl(5).setVisible(self.multi) self.getControl(5).setLabel('$LOCALIZE[186]') self.guilist = self.getControl(6) for image in self.artlist: provider = image['provider'].display if isinstance(provider, int): provider = L(provider) secondprovider = image.get('second provider') if secondprovider: if isinstance(secondprovider, int): secondprovider = L(secondprovider) provider = '{0}, {1}'.format(provider, secondprovider) title = image.get('title') if not title and 'subtype' in image: title = image['subtype'].display language = xbmc.convertLanguage(image['language'], xbmc.ENGLISH_NAME) if image.get('language') else None if not title: title = language if title and len(title) < 20 and not secondprovider: label = '{0} from {1}'.format(title, provider) summary = language if language and language != title else '' else: label = provider if language and language != title: title = language + ' ' + title summary = title if title else '' rating = image.get('rating') size = image.get('size') if (rating or size) and summary: summary += '\n' if size: summary += image['size'].display if rating and size: summary += ' ' if rating: summary += image['rating'].display listitem = xbmcgui.ListItem(label) listitem.setLabel2(summary) # DEPRECATED: Above Krypton and higher (only), below Jarvis and lower (only) listitem.setProperty('Addon.Summary', summary) listitem.setIconImage(image['url'] if self.hqpreview else image['preview']) # DEPRECATED: Above is deprecated in Jarvis, but still works through Krypton (at least) # listitem.setArt({'icon': image['url'] if self.hqpreview else image['preview']}) listitem.setPath(image['url']) if image.get('existing'): listitem.select(True) self.guilist.addItem(listitem) self.setFocus(self.guilist)
def search(self, item): if item['mansearch']: title = item['mansearchstr'] dialog = xbmcgui.Dialog() item['season'] = dialog.numeric(0, self._t(32111), item['season']) item['episode'] = dialog.numeric(0, self._t(32112), item['episode']) else: title = self.normalize_input_title(item['tvshow']) if not title or not item['season'] or not item['episode']: xbmc.executebuiltin("XBMC.Notification(%s,%s,5000,%s)" % ( self.addon.getAddonInfo('name'), self._t(32110), os.path.join(xbmc.translatePath(self.addon.getAddonInfo('path')).decode("utf-8"),'icon.png') )) log(__name__, ["Input validation error", title, item['season'], item['episode']]) return results_with_stats(None, self.addon, title, item) if item['3let_language'] and "cze" not in item['3let_language']: dialog = xbmcgui.Dialog() if dialog.yesno(self.addon.getAddonInfo('name'), self._t(32100), self._t(32101)): xbmc.executebuiltin("Dialog.Close(subtitlesearch)") xbmc.executebuiltin("PlayerControl(Stop)") xbmc.executebuiltin("ActivateWindowAndFocus(playersettings,-96,0,-67,0)") return results_with_stats(None, self.addon, title, item) all_tv_show_list = self.get_tv_show_list() if not all_tv_show_list: return results_with_stats(None, self.addon, title, item) tvshow_url = self.search_show_url(title, all_tv_show_list) if tvshow_url == None: return results_with_stats(None, self.addon, title, item) found_season_subtitles = self.search_season_subtitles(tvshow_url,item['season']) log(__name__, ["Season filter", found_season_subtitles]) if found_season_subtitles == None: return results_with_stats(None, self.addon, title, item) episode_subtitle = self.filter_episode_from_season_subtitles(found_season_subtitles,item['season'],item['episode']) log(__name__, ["Episode filter", episode_subtitle]) if episode_subtitle == None: return results_with_stats(None, self.addon, title, item) result_subtitles = [{ 'filename': HTMLParser.HTMLParser().unescape(episode_subtitle['full_title']), 'link': self.server_url + episode_subtitle['link'], 'lang': episode_subtitle['lang'], 'rating': "0", 'sync': False, 'lang_flag': xbmc.convertLanguage(episode_subtitle['lang'],xbmc.ISO_639_1), }] log(__name__,["Search result", result_subtitles]) return results_with_stats(result_subtitles, self.addon, title, item)
def Search(item): d = timeout(set_filehash, args=(item["file_original_path"], item["rar"]), timeout_duration=15) for language in item["3let_language"]: language = "pl" if language == "pol" else language params = { "l": language.upper(), "f": d.hexdigest(), "t": f(d.hexdigest()), "v": "dreambox", "kolejka": "false", "nick": "", "pass": "", "napios": os.name } url = "http://napiprojekt.pl/unit_napisy/dl.php?" + urllib.urlencode(params) subs = urllib.urlopen(url).read() if subs[0:4] != 'NPc0': file_name = '.'.join(os.path.basename(item["file_original_path"]).split(".")[:-1]) listitem = xbmcgui.ListItem(label=xbmc.convertLanguage(language, xbmc.ENGLISH_NAME), # language name for the found subtitle label2=file_name, # file name for the found subtitle iconImage="5", # rating for the subtitle, string 0-5 thumbnailImage=xbmc.convertLanguage(language, xbmc.ISO_639_1) # language flag, ISO_639_1 language + gif extention, e.g - "en.gif" ) listitem.setProperty("sync", '{0}'.format("true").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 download url = "plugin://%s/?action=download&l=%s&f=%s&t=%s&filename=%s" % ( __scriptid__, params["l"], params["f"], params["t"], file_name) ## 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)
def from_english(self, language): if language in EXCEPTIONS: return Language.fromietf(EXCEPTIONS[language]) language_match = re.search('(\w[\w\s]*\w)', language) if not language_match: return language_english = language_match.group(1) language_alpha3 = xbmc.convertLanguage(language_english, format=xbmc.ISO_639_2) if not language_alpha3: return result = Language.fromcode(language_alpha3, 'alpha3b') result.country = self.get_country(language) return result
def search(self, item): if item['mansearch']: title = item['mansearchstr'] dialog = xbmcgui.Dialog() item['season'] = dialog.numeric(0, self._t(32111), item['season']) item['episode'] = dialog.numeric(0, self._t(32112), item['episode']) else: title = self.normalize_input_title(item['tvshow']) if not title or not item['season'] or not item['episode']: xbmc.executebuiltin("XBMC.Notification(%s,%s,5000,%s)" % ( self.addon.getAddonInfo('name'), self._t(32110), os.path.join(xbmc.translatePath(self.addon.getAddonInfo('path')).decode("utf-8"),'icon.png') )) log(__name__, ["Input validation error", title, item['season'], item['episode']]) return results_with_stats(None, self.addon, title, item) tvshow_url = self.search_show_url(title) if tvshow_url == None: return results_with_stats(None, self.addon, title, item) found_season_subtitles = self.search_season_subtitles(tvshow_url,item['season']) log(__name__, ["Season filter", found_season_subtitles]) episode_subtitle_list = self.filter_episode_from_season_subtitles(found_season_subtitles,item['season'],item['episode']) log(__name__, ["Episode filter", episode_subtitle_list]) if episode_subtitle_list == None: return results_with_stats(None, self.addon, title, item) lang_filetred_episode_subtitle_list = self.filter_subtitles_by_language(item['3let_language'], episode_subtitle_list) log(__name__, ["Language filter", lang_filetred_episode_subtitle_list]) if lang_filetred_episode_subtitle_list == None: return results_with_stats(None, self.addon, title, item) result_subtitles = [] for episode_subtitle in lang_filetred_episode_subtitle_list['versions']: result_subtitles.append({ 'filename': HTMLParser.HTMLParser().unescape(lang_filetred_episode_subtitle_list['full_title']), 'link': self.server_url + episode_subtitle['link'], 'lang': episode_subtitle['lang'], 'rating': "0", 'sync': False, 'lang_flag': xbmc.convertLanguage(episode_subtitle['lang'],xbmc.ISO_639_1), }) log(__name__,["Search result", result_subtitles]) return results_with_stats(result_subtitles, self.addon, title, item)
def onPlayBackStarted(self): check_for_specific = (__addon__.getSetting('check_for_specific').lower() == 'true') specific_language = (__addon__.getSetting('selected_language')) specific_language = xbmc.convertLanguage(specific_language, xbmc.ISO_639_2) if self.run: movieFullPath = xbmc.Player().getPlayingFile() availableLangs = xbmc.Player().getAvailableSubtitleStreams() if (xbmc.Player().isPlayingVideo() and ((not xbmc.getCondVisibility("VideoPlayer.HasSubtitles")) or (check_for_specific and not specific_language in availableLangs)) and all(movieFullPath.find (v) <= -1 for v in ignore_words) and (isExcluded(movieFullPath)) ): self.run = False xbmc.sleep(1000) Debug('[AutoSubsPlayer] Started: AutoSearching for Subs') xbmc.executebuiltin('XBMC.ActivateWindow(SubtitleSearch)') else: Debug('[AutoSubsPlayer] Started: Subs found or Excluded') self.run = False
def settings(self, settings): self.id_teamwatch = settings['twid'] self.id_playerctl = settings['pcid'] self.nickname = settings['nickname'] self.twitter_enabled = settings['twitter_enabled'] self.twitter_language = settings['language'] self.twitter_language = xbmc.convertLanguage(self.twitter_language, xbmc.ISO_639_1) self.twitter_result_type = settings['result_type'] self.facebook_enabled = settings['facebook_enabled'] self.facebook_email = settings['facebook_email'] self.facebook_password = settings['facebook_password'] if settings['imdb_lang'] == 'Italian': self.imdb_translate = 'it' elif settings['imdb_lang'] == 'French': self.imdb_translate = 'fr' elif settings['imdb_lang'] == 'German': self.imdb_translate = 'de' else: self.imdb_translate = None self.email_enabled = settings['email_enabled'] self.email = settings['email'] self.email_password = settings['email_password'] self.email_imap = settings['email_imap'] self.facebook = settings['facebook'] self.show_allways = not (settings['showallways'] == "true") self.screen_height = settings['screen_height'] if self.screen_height == "" or self.screen_height == None: self.screen_height = xbmcgui.getScreenHeight() else: self.screen_height = int(settings['screen_height']) self.screen_width = settings['screen_width'] if self.screen_width == "" or self.screen_width == None: self.screen_width = xbmcgui.getScreenWidth() else: self.screen_width = int(settings['screen_width']) self.bartop = self.screen_height - 75
def filter_subtitles_by_language(self, set_languages, subtitles_list): if not set_languages: return subtitles_list log(__name__, ['Filter by languages', set_languages]) filter_subtitles_list = [] for subtitle in subtitles_list: if xbmc.convertLanguage(subtitle['lang'],xbmc.ISO_639_2) in set_languages: filter_subtitles_list.append(subtitle) if not filter_subtitles_list: if "cze" not in set_languages and "slo" not in set_languages: dialog = xbmcgui.Dialog() if dialog.yesno(self.addon.getAddonInfo('name'), self._t(32100), self._t(32101)): xbmc.executebuiltin("Dialog.Close(subtitlesearch)") xbmc.executebuiltin("PlayerControl(Stop)") xbmc.executebuiltin("ActivateWindowAndFocus(playersettings,-96,0,-67,0)") return None else: return filter_subtitles_list
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)