def toggle_language_invoker(): import xml.etree.ElementTree as ET from modules.utils import gen_file_hash kodi_utils.close_all_dialog() kodi_utils.sleep(100) addon_dir = kodi_utils.translate_path( 'special://home/addons/plugin.video.fen') addon_xml = os.path.join(addon_dir, 'addon.xml') tree = ET.parse(addon_xml) root = tree.getroot() try: current_value = [ str(i.text) for i in root.iter('reuselanguageinvoker') ][0] except: return current_setting = get_setting('reuse_language_invoker') new_value = 'false' if current_value == 'true' else 'true' if not kodi_utils.confirm_dialog( text=ls(33018) % (current_value.upper(), new_value.upper())): return if new_value == 'true': if not kodi_utils.confirm_dialog(text=33019, top_space=True): return for item in root.iter('reuselanguageinvoker'): item.text = new_value hash_start = gen_file_hash(addon_xml) tree.write(addon_xml) hash_end = gen_file_hash(addon_xml) if hash_start != hash_end: set_setting('reuse_language_invoker', new_value) else: return kodi_utils.ok_dialog(text=32574, top_space=True) kodi_utils.ok_dialog(text=33020, top_space=True) kodi_utils.execute_builtin('LoadProfile(%s)' % kodi_utils.get_infolabel('system.profilename'))
def debrid_check_dialog(self): start_time = time.time() end_time = start_time + self.timeout line = '%s[CR]%s[CR]%s' plswait_str, checking_debrid, remaining_debrid = ls(32577), ls( 32578), ls(32579) while not self.progress_dialog.iscanceled(): try: if monitor.abortRequested() is True: break remaining_debrids = [ x.getName() for x in self.main_threads if x.is_alive() is True ] current_time = time.time() current_progress = current_time - start_time try: line3 = remaining_debrid % ', '.join( remaining_debrids).upper() percent = int( (current_progress / float(self.timeout)) * 100) self.progress_dialog.update( line % (plswait_str, checking_debrid, line3), percent) except: pass sleep(self.sleep_time) if len(remaining_debrids) == 0: break if current_time > end_time: break except Exception: pass
def mark_as_watched_unwatched_movie(params): action = params.get('action') db_type = 'movie' tmdb_id = params.get('tmdb_id') title = params.get('title') year = params.get('year') refresh = params.get('refresh', 'true') from_playback = params.get('from_playback', 'false') watched_indicators = settings.watched_indicators() if watched_indicators == 1: if from_playback == 'true' and trakt_official_status(db_type) == False: skip_trakt_mark = True else: skip_trakt_mark = False if skip_trakt_mark: kodi_utils.sleep(3000) elif not trakt_watched_unwatched(action, 'movies', tmdb_id): return kodi_utils.notification(32574) clear_trakt_collection_watchlist_data('watchlist', db_type) data_base = TRAKT_DB data_base = TRAKT_DB else: data_base = WATCHED_DB mark_as_watched_unwatched(db_type, tmdb_id, action, title=title, data_base=data_base) erase_bookmark(db_type, tmdb_id) if settings.sync_kodi_library_watchstatus(): from modules.kodi_library import mark_as_watched_unwatched_kodi_library mark_as_watched_unwatched_kodi_library(db_type, action, title, year) refresh_container(refresh)
def build_trakt_list(params): def _process_ids(item_position, item): item['media_id'] = trakt_api.get_trakt_movie_id(item['media_ids']) if item['media_type'] == 'movie' else trakt_api.get_trakt_tvshow_id(item['media_ids']) final_append((item_position, item)) def _add_misc_dir(url_params, list_name=ls(32799), iconImage='item_next.png', isFolder=True): icon = kodi_utils.translate_path('special://home/addons/script.tikiart/resources/media/%s' % iconImage) listitem = make_listitem() listitem.setLabel(list_name) listitem.setArt({'icon': icon, 'poster': icon, 'thumb': icon, 'fanart': fanart, 'banner': icon}) if url_params['mode'] == 'build_navigate_to_page': listitem.setProperty('SpecialSort', 'top') listitem.addContextMenuItems([(ls(32784),'RunPlugin(%s)' % build_url({'mode': 'toggle_jump_to'}))]) else: listitem.setProperty('SpecialSort', 'bottom') kodi_utils.add_item(__handle__, build_url(url_params), listitem, isFolder) __handle__ = int(argv[1]) is_widget = kodi_utils.external_browse() user, slug, list_type = params.get('user'), params.get('slug'), params.get('list_type') letter, page_no = params.get('new_letter', 'None'), int(params.get('new_page', '1')) original_list, final_list, final_listitems = [], [], [] original_append, final_append = original_list.append, final_list.append result = trakt_api.get_trakt_list_contents(list_type, user, slug) for item in result: try: media_type = item['type'] if not media_type in ('movie', 'show'): continue original_append({'media_type': media_type, 'title': item[media_type]['title'], 'media_ids': item[media_type]['ids']}) except: pass if paginate(): limit = page_limit() trakt_list, total_pages = paginate_list(original_list, page_no, letter, limit) else: trakt_list, total_pages = original_list, 1 threads = list(make_thread_list_enumerate(_process_ids, trakt_list, Thread)) [i.join() for i in threads] final_list.sort(key=lambda k: k[0]) final_list = [i[1] for i in final_list] movie_list = [(i['media_id'], final_list.index(i), 'movie') for i in final_list if i['media_type'] == 'movie'] tvshow_list = [(i['media_id'], final_list.index(i), 'tvshow') for i in final_list if i['media_type'] == 'show'] content = 'movies' if len(movie_list) > len(tvshow_list) else 'tvshows' if total_pages > 2 and not is_widget: _add_misc_dir({'mode': 'build_navigate_to_page', 'db_type': 'Media', 'user': user, 'slug': slug, 'current_page': page_no, 'total_pages': total_pages, 'transfer_mode': 'trakt.list.build_trakt_list'}, ls(32964), 'item_jump.png', False) if len(movie_list) > 0: movie_listitems = Movies({'list': [i[0] for i in movie_list]}).worker() final_listitems.extend([(i, x[1]) for i in movie_listitems for x in movie_list if [str(x[0]) == i[1].getUniqueID('tmdb') and x[2] == 'movie'][0]]) if len(tvshow_list) > 0: tvshow_listitems = TVShows({'list': [i[0] for i in tvshow_list]}).worker() final_listitems.extend([(i, x[1]) for i in tvshow_listitems for x in tvshow_list if [str(x[0]) == i[1].getUniqueID('tmdb') and x[2] == 'tvshow'][0]]) final_listitems.sort(key=lambda k: k[1]) item_list = [i[0] for i in final_listitems] kodi_utils.add_items(__handle__, item_list) if total_pages > page_no: _add_misc_dir({'mode': 'trakt.list.build_trakt_list', 'user': user, 'slug': slug, 'new_page': str(page_no + 1), 'new_letter': letter}) kodi_utils.set_content(__handle__, content) kodi_utils.end_directory(__handle__) if params.get('refreshed'): kodi_utils.sleep(1500) kodi_utils.set_view_mode('view.trakt_list', content)
def _background(): kodi_utils.sleep(1500) start_time = time.time() end_time = start_time + self.timeout while time.time() < end_time: alive_threads = [x for x in threads if x.is_alive()] kodi_utils.sleep(self.sleep_time) if len(alive_threads) <= 5: return if len(self.sources) >= 100 * len(alive_threads): return
def _get(self, url, stream=False, retry=False): response = requests.get(url, headers=self.headers, stream=stream) if '200' in str(response): return response elif '429' in str(response) and retry: notification(32740, 3500) sleep(10000) return self._get(url, stream) else: return
def build_navigate_to_page(params): import json from modules.settings import nav_jump_use_alphabet use_alphabet = nav_jump_use_alphabet() icon = kodi_utils.translate_path( 'special://home/addons/script.tikiart/resources/media/item_jump.png') fanart = kodi_utils.translate_path( 'special://home/addons/plugin.video.fen/fanart.png') db_type = params.get('db_type') def _builder(use_alphabet): for i in start_list: if use_alphabet: line1, line2 = i.upper(), ls(32821) % (db_type, i.upper()) else: line1, line2 = '%s %s' % (ls(32022), i), ls(32822) % i yield {'line1': line1, 'line2': line2, 'icon': icon} if use_alphabet: start_list = [chr(i) for i in range(97, 123)] else: start_list = [ str(i) for i in range(1, int(params.get('total_pages')) + 1) ] start_list.remove(params.get('current_page')) list_items = list(_builder(use_alphabet)) kwargs = { 'items': json.dumps(list_items), 'heading': 'Fen', 'enumerate': 'false', 'multi_choice': 'false', 'multi_line': 'false' } new_start = kodi_utils.select_dialog(start_list, **kwargs) kodi_utils.sleep(100) if new_start == None: return if use_alphabet: new_page, new_letter = '', new_start else: new_page, new_letter = new_start, None url_params = { 'mode': params.get('transfer_mode', ''), 'action': params.get('transfer_action', ''), 'new_page': new_page, 'new_letter': new_letter, 'media_type': params.get('media_type', ''), 'query': params.get('query', ''), 'actor_id': params.get('actor_id', ''), 'user': params.get('user', ''), 'slug': params.get('slug', '') } kodi_utils.execute_builtin('Container.Update(%s)' % kodi_utils.build_url(url_params))
def _return_failed(message=32574, cancelled=False): try: progressDialog.close() except Exception: pass hide_busy_dialog() sleep(500) if cancelled: if confirm_dialog(text=32044, top_space=True): ok_dialog(heading=32733, text=ls(32732) % ls(32054)) else: self.delete_torrent(torrent_id) else: ok_dialog(heading=32733, text=message) return False
def open_settings(query, addon='plugin.video.fen'): kodi_utils.sleep(250) if query: try: button, control = 100, 80 kodi_utils.hide_busy_dialog() menu, function = query.split('.') kodi_utils.execute_builtin('Addon.OpenSettings(%s)' % addon) kodi_utils.execute_builtin('SetFocus(%i)' % (int(menu) - button)) kodi_utils.execute_builtin('SetFocus(%i)' % (int(function) - control)) except: kodi_utils.execute_builtin('Addon.OpenSettings(%s)' % addon) else: kodi_utils.execute_builtin('Addon.OpenSettings(%s)' % addon)
def batch_mark_episodes_as_watched_unwatched_kodi_library( action, show_info, episode_list): playcount = 1 if action == 'mark_as_watched' else 0 tvshowid = str(show_info['tvshowid']) ep_ids = [] action_list = [] ep_ids_append = ep_ids.append action_append = action_list.append progressDialogBG.create(ls(32577), '') try: for item in episode_list: try: season = item[2] episode = item[3] r = execute_JSON( '{"jsonrpc": "2.0", "method": "VideoLibrary.GetEpisodes", "params": {"filter":{"and": [{"field": "season", "operator": "is", "value": "%s"}, {"field": "episode", "operator": "is", "value": "%s"}]}, "properties": ["file", "playcount"], "tvshowid": %s }, "id": 1}' % (str(season), str(episode), str(tvshowid))) r = to_utf8(r) r = json.loads(r)['result']['episodes'][0] ep_ids_append((r['episodeid'], r['playcount'])) except: pass for count, item in enumerate(ep_ids, 1): try: ep_id = item[0] current_playcount = item[1] if int(current_playcount) != playcount: sleep(50) display = ls(32856) progressDialogBG.update( int(float(count) / float(len(ep_ids)) * 100), ls(32577), display) t = '{"jsonrpc": "2.0", "method": "VideoLibrary.SetEpisodeDetails", "params": {"episodeid" : %d, "playcount" : %d }, "id": 1 }' % ( int(ep_id), playcount) t = json.loads(t) action_append(t) else: pass except: pass progressDialogBG.update(100, ls(32577), ls(32788)) r = execute_JSON(json.dumps(action_list)) progressDialogBG.close() return r except: pass
def auth_loop(self): sleep(1000 * self.auth_step) url = 'client_id=%s&code=%s' % (self.client_ID, self.device_code) url = auth_url + credentials_url % url response = json.loads(requests.get(url, timeout=self.timeout).text) if 'error' in response: return try: progressDialog.close() set_setting('rd.client_id', response['client_id']) set_setting('rd.secret', response['client_secret']) self.secret = response['client_secret'] self.client_ID = response['client_id'] except: ok_dialog(text=ls(32574), top_space=True) self.break_auth_loop = True return
def _return_failed(message=32574, cancelled=False): try: kodi_utils.progressDialog.close() except Exception: pass kodi_utils.hide_busy_dialog() kodi_utils.sleep(500) if cancelled: if kodi_utils.confirm_dialog(text=32044, top_space=True): kodi_utils.ok_dialog(heading=32733, text=ls(32732) % ls(32063), top_space=True) else: self.delete_transfer(transfer_id) else: kodi_utils.ok_dialog(heading=2733, text=message) return False
def auth_loop(self): kodi_utils.sleep(5000) response = requests.get(self.check_url, timeout=self.timeout).json() response = response['data'] if 'error' in response: self.token = 'failed' return kodi_utils.ok_dialog(text=32574, top_space=True) if response['activated']: try: kodi_utils.progressDialog.close() self.token = str(response['apikey']) set_setting('ad.token', self.token) except: self.token = 'failed' self.break_auth_loop = True return kodi_utils.ok_dialog(text=32574, top_space=True) return
def open_MyAccounts(params): from myaccounts import openMASettings query = params.get('query', None) openMASettings(query) kodi_utils.sleep(100) while kodi_utils.get_visibility( 'Window.IsVisible(addonsettings)') or kodi_utils.get_property( 'myaccounts.active') == 'true': kodi_utils.sleep(250) kodi_utils.sleep(100) sync_MyAccounts() kodi_utils.sleep(100) open_settings('4.0')
def auth_loop(self): if progressDialog.iscanceled(): progressDialog.close() return sleep(5000) url = 'https://www.premiumize.me/token' data = { 'grant_type': 'device_code', 'client_id': self.client_id, 'code': self.device_code } response = self._post(url, data) if 'error' in response: return try: progressDialog.close() self.token = str(response['access_token']) set_setting('pm.token', self.token) except: ok_dialog(text=32574, top_space=True) return
def _control(): confirm_threshold = False final_action = 'cancel' while player.isPlayingVideo(): try: total_time = player.getTotalTime() curr_time = player.getTime() remaining_time = round(total_time - curr_time) if remaining_time <= nextep_threshold_check: if not confirm_threshold: confirm_threshold = _confirm_threshold() if not confirm_threshold: final_action = 'cancel' break if remaining_time <= display_nextep_popup: final_action = _continue_action() break kodi_utils.sleep(200) except: pass return final_action
def clear_all_cache(): if not kodi_utils.confirm_dialog(): return line = '[CR]%s....[CR]%s' kodi_utils.progressDialog.create('Fen', '') caches = (('meta', '%s %s' % (ls(32527), ls(32524))), ('internal_scrapers', '%s %s' % (ls(32096), ls(32524))), ('external_scrapers', '%s %s' % (ls(32118), ls(32524))), ('trakt', ls(32087)), ('imdb', '%s %s' % (ls(32064), ls(32524))), ('list', '%s %s' % (ls(32815), ls(32524))), ('pm_cloud', '%s %s' % (ls(32061), ls(32524))), ('rd_cloud', '%s %s' % (ls(32054), ls(32524))), ('ad_cloud', '%s %s' % (ls(32063), ls(32524)))) for count, cache_type in enumerate(caches, 1): kodi_utils.progressDialog.update( int(float(count) / float(len(caches)) * 100), line % (ls(32816), cache_type[1])) clear_cache(cache_type[0], silent=True) kodi_utils.sleep(400) kodi_utils.progressDialog.close() kodi_utils.sleep(250) kodi_utils.ok_dialog(text=32576, top_space=True)
def _scraperDialog(): close_dialog = True while not self.progress_dialog.iscanceled(): try: if kodi_utils.monitor.abortRequested() is True: return sysexit() remaining_providers = [ x.getName() for x in _threads if x.is_alive() is True ] self._process_internal_results() s4k_label = total_format % self.sources4K s1080_label = total_format % self.sources1080p s720_label = total_format % self.sources720p ssd_label = total_format % self.sourcesSD stotal_label = total_format % self.sourcesTotal try: current_time = time.time() current_progress = current_time - start_time line2 = diag_format % ( int_dialog_hl, line2_inst, s4k_label, s1080_label, s720_label, ssd_label, stotal_label) line3_insert = ', '.join(remaining_providers).upper() line3 = remaining_providers_str % line3_insert percent = int( (current_progress / float(timeout)) * 100) self.progress_dialog.update( line % (line1, line2, line3), percent) kodi_utils.sleep(self.sleep_time) if len(remaining_providers) == 0: close_dialog = False break if end_time < current_time: close_dialog = False break except: pass except: pass if close_dialog or scrape_type == 'internal': self._kill_progress_dialog()
def mark_as_watched_unwatched_episode(params): action = params.get('action') db_type = 'episode' tmdb_id = params.get('tmdb_id') try: tvdb_id = int(params.get('tvdb_id', '0')) except: tvdb_id = 0 season = int(params.get('season')) episode = int(params.get('episode')) title = params.get('title') year = params.get('year') refresh = params.get('refresh', 'true') from_playback = params.get('from_playback', 'false') watched_indicators = settings.watched_indicators() if season == 0: kodi_utils.notification(32490) return if watched_indicators == 1: if from_playback == 'true' and trakt_official_status(db_type) == False: skip_trakt_mark = True else: skip_trakt_mark = False if skip_trakt_mark: kodi_utils.sleep(3000) elif not trakt_watched_unwatched(action, db_type, tmdb_id, tvdb_id, season, episode): return kodi_utils.notification(32574) clear_trakt_collection_watchlist_data('watchlist', 'tvshow') data_base = TRAKT_DB else: data_base = WATCHED_DB mark_as_watched_unwatched(db_type, tmdb_id, action, season, episode, title, data_base) erase_bookmark(db_type, tmdb_id, season, episode) if settings.sync_kodi_library_watchstatus(): from modules.kodi_library import mark_as_watched_unwatched_kodi_library mark_as_watched_unwatched_kodi_library(db_type, action, title, year, season, episode) refresh_container(refresh)
def clear_all_trakt_cache_data(silent=False, confirm=True): def _process(): dbcon = _cache.connect_database() dbcur = dbcon.cursor() for table in ('trakt_data', 'progress', 'watched_status'): dbcur.execute(BASE_DELETE % table) dbcon.commit() dbcur.execute('VACUUM') dbcon.close() if silent: return _process() else: if confirm: if not confirm_dialog(): return False from apis.trakt_api import trakt_sync_activities close_all_dialog() sleep(200) try: _process() trakt_sync_activities() return True except: return False
def auth(self): self.token = '' url = base_url + 'pin/get?agent=%s' % user_agent response = requests.get(url, timeout=self.timeout).json() response = response['data'] line = '%s[CR]%s[CR]%s' kodi_utils.progressDialog.create('Fen', '') kodi_utils.progressDialog.update( -1, line % (ls(32517), ls(32700) % response.get('base_url'), ls(32701) % response.get('pin'))) self.check_url = response.get('check_url') kodi_utils.sleep(2000) while not self.token: if self.break_auth_loop: break if kodi_utils.progressDialog.iscanceled(): kodi_utils.progressDialog.close() break self.auth_loop() if self.token in (None, '', 'failed'): return kodi_utils.sleep(2000) account_info = self._get('user') set_setting('ad.account_id', str(account_info['user']['username'])) kodi_utils.ok_dialog(text=32576, top_space=True)
def refresh_artwork(): if not kodi_utils.confirm_dialog(): return import sqlite3 as database for item in ('icon.png', 'fanart.png'): try: icon_path = kodi_utils.translate_path( 'special://home/addons/plugin.video.fen/%s' % item) thumbs_folder = kodi_utils.translate_path('special://thumbnails') TEXTURE_DB = kodi_utils.translate_path( 'special://database/Textures13.db') dbcon = database.connect(TEXTURE_DB) dbcur = dbcon.cursor() dbcur.execute("SELECT cachedurl FROM texture WHERE url = ?", (icon_path, )) image = dbcur.fetchone()[0] dbcon.close() removal_path = os.path.join(thumbs_folder, image) kodi_utils.delete_file(removal_path) except: pass kodi_utils.sleep(200) kodi_utils.execute_builtin('ReloadSkin()') kodi_utils.sleep(500) kodi_utils.notification(32576)
def doDownload(self, url, dest): headers = self.headers file = dest.rsplit(os.sep, 1)[-1] resp = self.getResponse(url, headers, 0) if not resp: kodi_utils.hide_busy_dialog() kodi_utils.ok_dialog(text=32490, top_space=True) return try: content = int(resp.headers['Content-Length']) except: content = 0 try: resumable = 'bytes' in resp.headers['Accept-Ranges'].lower() except: resumable = False if content < 1: kodi_utils.hide_busy_dialog() kodi_utils.ok_dialog(text=32490, top_space=True) return size = 1024 * 1024 mb = content / (1024 * 1024) if content < size: size = content kodi_utils.hide_busy_dialog() if not self.confirmDownload(mb): return if self.action not in ('image', 'meta.pack'): show_notifications = True notification_frequency = 25 else: if self.action == 'meta.pack': kodi_utils.notification(32134, 3500, self.image) show_notifications = False notification_frequency = 0 notify, total, errors, count, resume, sleep_time = 25, 0, 0, 0, 0, 0 f = kodi_utils.open_file(dest, 'w') chunk = None chunks = [] while True: downloaded = total for c in chunks: downloaded += len(c) percent = min(round(float(downloaded) * 100 / content), 100) playing = kodi_utils.player.isPlaying() if show_notifications: if percent >= notify: notify += notification_frequency try: line1 = '%s - [I]%s[/I]' % (str(percent) + '%', self.final_name) if not playing: kodi_utils.notification(line1, 3000, self.image) except: pass chunk = None error = False try: chunk = resp.read(size) if not chunk: if percent < 99: error = True else: while len(chunks) > 0: c = chunks.pop(0) f.write(c) del c f.close() try: progressDialog.close() except: pass return self.done(self.final_name, self.db_type, True, self.image) except Exception as e: error = True sleep_time = 10 errno = 0 if hasattr(e, 'errno'): errno = e.errno if errno == 10035: # 'A non-blocking socket operation could not be completed immediately' pass if errno == 10054: #'An existing connection was forcibly closed by the remote host' errors = 10 #force resume sleep_time = 30 if errno == 11001: # 'getaddrinfo failed' errors = 10 #force resume sleep_time = 30 if chunk: errors = 0 chunks.append(chunk) if len(chunks) > 5: c = chunks.pop(0) f.write(c) total += len(c) del c if error: errors += 1 count += 1 kodi_utils.sleep(sleep_time * 1000) if (resumable and errors > 0) or errors >= 10: if (not resumable and resume >= 50) or resume >= 500: try: progressDialog.close() except: pass return self.done(self.final_name, self.db_type, False, self.image) resume += 1 errors = 0 if resumable: chunks = [] resp = self.getResponse(url, headers, total) else: pass
def external_scrapers_manager(): icon = kodi_utils.ext_addon('script.module.fenomscrapers').getAddonInfo( 'icon') all_color, hosters_color, torrent_color = 'mediumvioletred', get_setting( 'hoster.identify'), get_setting('torrent.identify') enable_string, disable_string, specific_string, all_string = ls(32055), ls( 32024), ls(32536), ls(32525) scrapers_string, hosters_string, torrent_string = ls(32533), ls(33031), ls( 32535) fs_default_string = ls(32137) all_scrapers_string = '%s %s' % (all_string, scrapers_string) hosters_scrapers_string = '%s %s' % (hosters_string, scrapers_string) torrent_scrapers_string = '%s %s' % (torrent_string, scrapers_string) enable_string_base = '%s %s %s %s' % (enable_string, all_string, '%s', scrapers_string) disable_string_base = '%s %s %s %s' % (disable_string, all_string, '%s', scrapers_string) enable_disable_string_base = '%s/%s %s %s %s' % ( enable_string, disable_string, specific_string, '%s', scrapers_string) all_scrapers_base = '[COLOR %s]%s [/COLOR]' % (all_color, all_scrapers_string.upper()) debrid_scrapers_base = '[COLOR %s]%s [/COLOR]' % ( hosters_color, hosters_scrapers_string.upper()) torrent_scrapers_base = '[COLOR %s]%s [/COLOR]' % ( torrent_color, torrent_scrapers_string.upper()) tools_menu = \ [(all_scrapers_base, fs_default_string, {'mode': 'set_default_scrapers'}), (all_scrapers_base, enable_string_base % '', {'mode': 'toggle_all', 'folder': 'all', 'setting': 'true'}), (all_scrapers_base, disable_string_base % '', {'mode': 'toggle_all', 'folder': 'all', 'setting': 'false'}), (all_scrapers_base, enable_disable_string_base % '', {'mode': 'enable_disable', 'folder': 'all'}), (debrid_scrapers_base, enable_string_base % hosters_string, {'mode': 'toggle_all', 'folder': 'hosters', 'setting': 'true'}), (debrid_scrapers_base, disable_string_base % hosters_string, {'mode': 'toggle_all', 'folder': 'hosters', 'setting': 'false'}), (debrid_scrapers_base, enable_disable_string_base % hosters_string, {'mode': 'enable_disable', 'folder': 'hosters'}), (torrent_scrapers_base, enable_string_base % torrent_string, {'mode': 'toggle_all', 'folder': 'torrents', 'setting': 'true'}), (torrent_scrapers_base, disable_string_base % torrent_string, {'mode': 'toggle_all', 'folder': 'torrents', 'setting': 'false'}), (torrent_scrapers_base, enable_disable_string_base % torrent_string, {'mode': 'enable_disable', 'folder': 'torrents'})] list_items = [{ 'line1': item[0], 'line2': item[1], 'icon': icon } for item in tools_menu] kwargs = { 'items': json.dumps(list_items), 'heading': 'Fen', 'enumerate': 'false', 'multi_choice': 'false', 'multi_line': 'true' } chosen_tool = kodi_utils.select_dialog(tools_menu, **kwargs) if chosen_tool == None: return from modules import source_utils params = chosen_tool[2] mode = params['mode'] if mode == 'toggle_all': source_utils.toggle_all(params['folder'], params['setting']) elif mode == 'enable_disable': source_utils.enable_disable(params['folder']) elif mode == 'set_default_scrapers': source_utils.set_default_scrapers() kodi_utils.sleep(350) return external_scrapers_manager()
def options_menu(params, meta=None): def _builder(): for item in listing: line1 = item[0] line2 = item[1] if line2 == '': line2 = line1 yield {'line1': line1, 'line2': line2} content = params.get('content', None) if not content: content = kodi_utils.container_content()[:-1] season = params.get('season', None) episode = params.get('episode', None) if not meta: function = metadata.movie_meta if content == 'movie' else metadata.tvshow_meta meta_user_info = metadata.retrieve_user_info() meta = function('tmdb_id', params['tmdb_id'], meta_user_info) watched_indicators = settings.watched_indicators() on_str, off_str, currently_str, open_str, settings_str = ls(32090), ls( 32027), ls(32598), ls(32641), ls(32247) autoplay_status, autoplay_toggle, quality_setting = (on_str, 'false', 'autoplay_quality_%s' % content) if settings.auto_play(content) \ else (off_str, 'true', 'results_quality_%s' % content) quality_filter_setting = 'autoplay_quality_%s' % content if autoplay_status == on_str else 'results_quality_%s' % content autoplay_next_status, autoplay_next_toggle = ( on_str, 'false') if settings.autoplay_next_episode() else (off_str, 'true') results_xml_style_status = get_setting('results.xml_style', 'Default') results_filter_ignore_status, results_filter_ignore_toggle = ( on_str, 'false') if settings.ignore_results_filter() else (off_str, 'true') results_sorting_status = get_setting('results.sort_order_display').replace( '$ADDON[plugin.video.fen 32582]', ls(32582)) current_results_highlights_action = get_setting('highlight.type') results_highlights_status = ls( 32240) if current_results_highlights_action == '0' else ls( 32583) if current_results_highlights_action == '1' else ls(32241) current_subs_action = get_setting('subtitles.subs_action') current_subs_action_status = 'Auto' if current_subs_action == '0' else ls( 32193) if current_subs_action == '1' else off_str active_internal_scrapers = [ i.replace('_', '') for i in settings.active_internal_scrapers() ] current_scrapers_status = ', '.join([ i for i in active_internal_scrapers ]) if len(active_internal_scrapers) > 0 else 'N/A' current_quality_status = ', '.join( settings.quality_filter(quality_setting)) uncached_torrents_status, uncached_torrents_toggle = ( on_str, 'false') if settings.display_uncached_torrents() else (off_str, 'true') listing = [] base_str1 = '%s%s' base_str2 = '%s: [B]%s[/B]' % (currently_str, '%s') if content in ('movie', 'episode'): multi_line = 'true' listing += [(ls(32014), '', 'clear_and_rescrape')] listing += [(ls(32006), '', 'rescrape_with_disabled')] listing += [(ls(32135), '', 'scrape_with_custom_values')] listing += [(base_str1 % (ls(32175), ' (%s)' % content), base_str2 % autoplay_status, 'toggle_autoplay')] if autoplay_status == on_str and content == 'episode': listing += [ (base_str1 % (ls(32178), ''), base_str2 % autoplay_next_status, 'toggle_autoplay_next') ] listing += [(base_str1 % (ls(32105), ' (%s)' % content), base_str2 % current_quality_status, 'set_quality')] listing += [(base_str1 % ('', '%s %s' % (ls(32055), ls(32533))), base_str2 % current_scrapers_status, 'enable_scrapers')] if autoplay_status == off_str: listing += [(base_str1 % ('', ls(32140)), base_str2 % results_xml_style_status, 'set_results_xml_display')] listing += [ (base_str1 % ('', ls(32151)), base_str2 % results_sorting_status, 'set_results_sorting') ] listing += [(base_str1 % ('', ls(32138)), base_str2 % results_highlights_status, 'set_results_highlights')] listing += [(base_str1 % ('', ls(32686)), base_str2 % results_filter_ignore_status, 'set_results_filter_ignore')] listing += [(base_str1 % ('', ls(32183)), base_str2 % current_subs_action_status, 'set_subs_action') ] if 'external' in active_internal_scrapers: listing += [(base_str1 % ('', ls(32160)), base_str2 % uncached_torrents_status, 'toggle_torrents_display_uncached')] else: multi_line = 'false' listing += [(ls(32046), '', 'extras_lists_choice')] if content in ('movie', 'tvshow') and meta: listing += [ (ls(32604) % (ls(32028) if meta['mediatype'] == 'movie' else ls(32029)), '', 'clear_media_cache') ] if watched_indicators == 1: listing += [(ls(32497) % ls(32037), '', 'clear_trakt_cache')] if content in ('movie', 'episode'): listing += [(ls(32637), '', 'clear_scrapers_cache')] listing += [('%s %s' % (ls(32118), ls(32513)), '', 'open_external_scrapers_manager')] listing += [('%s %s %s' % (open_str, ls(32522), settings_str), '', 'open_scraper_settings')] listing += [('%s %s %s' % (open_str, ls(32036), settings_str), '', 'open_fen_settings')] listing += [(ls(32640), '', 'save_and_exit')] list_items = list(_builder()) heading = ls(32646).replace('[B]', '').replace('[/B]', '') kwargs = { 'items': json.dumps(list_items), 'heading': heading, 'enumerate': 'false', 'multi_choice': 'false', 'multi_line': multi_line } choice = kodi_utils.select_dialog([i[2] for i in listing], **kwargs) if choice in (None, 'save_and_exit'): return elif choice == 'clear_and_rescrape': return clear_and_rescrape(content, meta, season, episode) elif choice == 'rescrape_with_disabled': return rescrape_with_disabled(content, meta, season, episode) elif choice == 'scrape_with_custom_values': return scrape_with_custom_values(content, meta, season, episode) elif choice == 'toggle_autoplay': set_setting('auto_play_%s' % content, autoplay_toggle) elif choice == 'toggle_autoplay_next': set_setting('autoplay_next_episode', autoplay_next_toggle) elif choice == 'enable_scrapers': enable_scrapers_choice() elif choice == 'set_results_xml_display': results_layout_choice() elif choice == 'set_results_sorting': results_sorting_choice() elif choice == 'set_results_filter_ignore': set_setting('ignore_results_filter', results_filter_ignore_toggle) elif choice == 'set_results_highlights': results_highlights_choice() elif choice == 'set_quality': set_quality_choice(quality_filter_setting) elif choice == 'set_subs_action': set_subtitle_choice() elif choice == 'extras_lists_choice': extras_lists_choice() elif choice == 'clear_media_cache': return refresh_cached_data(meta['mediatype'], 'tmdb_id', meta['tmdb_id'], meta['tvdb_id'], settings.get_language()) elif choice == 'toggle_torrents_display_uncached': set_setting('torrent.display.uncached', uncached_torrents_toggle) elif choice == 'clear_trakt_cache': return clear_cache('trakt') elif choice == 'clear_scrapers_cache': return clear_scrapers_cache() elif choice == 'open_external_scrapers_manager': return external_scrapers_manager() elif choice == 'open_scraper_settings': return kodi_utils.execute_builtin( 'Addon.OpenSettings(script.module.fenomscrapers)') elif choice == 'open_fen_settings': return open_settings('0.0') if choice == 'clear_trakt_cache' and content in ('movie', 'tvshow', 'season', 'episode'): kodi_utils.execute_builtin('Container.Refresh') kodi_utils.show_busy_dialog() kodi_utils.sleep(200) kodi_utils.hide_busy_dialog() options_menu(params, meta=meta)
def add_uncached_torrent(self, magnet_url, pack=False): from modules.kodi_utils import show_busy_dialog, hide_busy_dialog from modules.source_utils import supported_video_extensions def _return_failed(message=32574, cancelled=False): try: progressDialog.close() except Exception: pass hide_busy_dialog() sleep(500) if cancelled: if confirm_dialog(text=32044, top_space=True): ok_dialog(heading=32733, text=ls(32732) % ls(32054)) else: self.delete_torrent(torrent_id) else: ok_dialog(heading=32733, text=message) return False show_busy_dialog() try: active_count = self.torrents_activeCount() if active_count['nb'] >= active_count['limit']: return _return_failed() except: pass interval = 5 stalled = ('magnet_error', 'error', 'virus', 'dead') extensions = supported_video_extensions() torrent = self.add_magnet(magnet_url) torrent_id = torrent['id'] if not torrent_id: return _return_failed() torrent_info = self.torrent_info(torrent_id) if 'error_code' in torrent_info: return _return_failed() status = torrent_info['status'] line = '%s[CR]%s[CR]%s' if status == 'magnet_conversion': line1 = ls(32737) line2 = torrent_info['filename'] line3 = ls(32738) % torrent_info['seeders'] timeout = 100 progressDialog.create(ls(32733), line % (line1, line2, line3)) while status == 'magnet_conversion' and timeout > 0: progressDialog.update(timeout, line % (line1, line2, line3)) if monitor.abortRequested() == True: return sysexit() try: if progressDialog.iscanceled(): return _return_failed(32736, cancelled=True) except Exception: pass timeout -= interval sleep(1000 * interval) torrent_info = self.torrent_info(torrent_id) status = torrent_info['status'] if any(x in status for x in stalled): return _return_failed() line3 = ls(32738) % torrent_info['seeders'] try: progressDialog.close() except Exception: pass if status == 'downloaded': hide_busy_dialog() return True if status == 'magnet_conversion': return _return_failed() if any(x in status for x in stalled): return _return_failed(str(status)) if status == 'waiting_files_selection': video_files = [] append = video_files.append all_files = torrent_info['files'] for item in all_files: if any(item['path'].lower().endswith(x) for x in extensions): append(item) if pack: try: if len(video_files) == 0: return _return_failed() video_files.sort(key=lambda x: x['path']) torrent_keys = [str(i['id']) for i in video_files] if not torrent_keys: return _return_failed(ls(32736)) torrent_keys = ','.join(torrent_keys) self.add_torrent_select(torrent_id, torrent_keys) ok_dialog(text=ls(32732) % ls(32054)) self.clear_cache() hide_busy_dialog() return True except Exception: return _return_failed() else: try: video = max(video_files, key=lambda x: x['bytes']) file_id = video['id'] except ValueError: return _return_failed() self.add_torrent_select(torrent_id, str(file_id)) sleep(2000) torrent_info = self.torrent_info(torrent_id) status = torrent_info['status'] if status == 'downloaded': hide_busy_dialog() return True file_size = round(float(video['bytes']) / (1000**3), 2) line1 = '%s...' % (ls(32732) % ls(32054)) line2 = torrent_info['filename'] line3 = status progressDialog.create(ls(32733), line % (line1, line2, line3)) while not status == 'downloaded': sleep(1000 * interval) torrent_info = self.torrent_info(torrent_id) status = torrent_info['status'] if status == 'downloading': line3 = ls(32739) % ( file_size, round(float(torrent_info['speed']) / (1000**2), 2), torrent_info['seeders'], torrent_info['progress']) else: line3 = status progressDialog.update(int(float(torrent_info['progress'])), line % (line1, line2, line3)) if monitor.abortRequested() == True: return sys.exit() try: if progressDialog.iscanceled(): return _return_failed(32736, cancelled=True) except: pass if any(x in status for x in stalled): return _return_failed() try: progressDialog.close() except: pass hide_busy_dialog() return True hide_busy_dialog() return False
def add_uncached_torrent(self, magnet_url, pack=False): def _return_failed(message=32574, cancelled=False): try: kodi_utils.progressDialog.close() except Exception: pass kodi_utils.hide_busy_dialog() kodi_utils.sleep(500) if cancelled: if kodi_utils.confirm_dialog(text=32044, top_space=True): kodi_utils.ok_dialog(heading=32733, text=ls(32732) % ls(32063), top_space=True) else: self.delete_transfer(transfer_id) else: kodi_utils.ok_dialog(heading=2733, text=message) return False kodi_utils.show_busy_dialog() transfer_id = self.create_transfer(magnet_url) if not transfer_id: return _return_failed() transfer_info = self.list_transfer(transfer_id) if not transfer_info: return _return_failed() if pack: self.clear_cache() kodi_utils.hide_busy_dialog() kodi_utils.ok_dialog(text=ls(32732) % ls(32063)) return True interval = 5 line = '%s[CR]%s[CR]%s' line1 = '%s...' % (ls(32732) % ls(32063)) line2 = transfer_info['filename'] line3 = transfer_info['status'] kodi_utils.progressDialog.create(ls(32733), line % (line1, line2, line3)) while not transfer_info['statusCode'] == 4: kodi_utils.sleep(1000 * interval) transfer_info = self.list_transfer(transfer_id) file_size = transfer_info['size'] line2 = transfer_info['filename'] if transfer_info['statusCode'] == 1: download_speed = round( float(transfer_info['downloadSpeed']) / (1000**2), 2) progress = int( float(transfer_info['downloaded']) / file_size * 100) if file_size > 0 else 0 line3 = ls(32734) % (download_speed, transfer_info['seeders'], progress, round(float(file_size) / (1000**3), 2)) elif transfer_info['statusCode'] == 3: upload_speed = round( float(transfer_info['uploadSpeed']) / (1000**2), 2) progress = int( float(transfer_info['uploaded']) / file_size * 100) if file_size > 0 else 0 line3 = ls(32735) % (upload_speed, progress, round(float(file_size) / (1000**3), 2)) else: line3 = transfer_info['status'] progress = 0 kodi_utils.progressDialog.update(progress, line % (line1, line2, line3)) if kodi_utils.monitor.abortRequested() == True: return sysexit() try: if kodi_utils.progressDialog.iscanceled(): return _return_failed(32736, cancelled=True) except Exception: pass if 5 <= transfer_info['statusCode'] <= 10: return _return_failed() kodi_utils.sleep(1000 * interval) try: kodi_utils.progressDialog.close() except Exception: pass kodi_utils.hide_busy_dialog() return True
def clean_settings(): import xml.etree.ElementTree as ET def _make_content(dict_object): content = '<settings version="2">' for item in dict_object: _id = item['id'] if _id in active_settings: if 'default' in item and 'value' in item: content += '\n <setting id="%s" default="%s">%s</setting>' % ( _id, item['default'], item['value']) elif 'default' in item: content += '\n <setting id="%s" default="%s"></setting>' % ( _id, item['default']) elif 'value' in item: content += '\n <setting id="%s">%s</setting>' % ( _id, item['value']) else: content += '\n <setting id="%s"></setting>' else: removed_append(item) content += '\n</settings>' return content kodi_utils.close_all_dialog() kodi_utils.sleep(200) kodi_utils.progressDialog.create(ls(32577), '') kodi_utils.progressDialog.update(0) addon_ids = [ 'plugin.video.fen', 'script.module.fenomscrapers', 'script.module.myaccounts' ] addon_names = [ kodi_utils.ext_addon(i).getAddonInfo('name') for i in addon_ids ] addon_dirs = [ kodi_utils.translate_path( kodi_utils.ext_addon(i).getAddonInfo('path')) for i in addon_ids ] profile_dirs = [ kodi_utils.translate_path( kodi_utils.ext_addon(i).getAddonInfo('profile')) for i in addon_ids ] active_settings_xmls = [ os.path.join( kodi_utils.translate_path( kodi_utils.ext_addon(i).getAddonInfo('path')), 'resources', 'settings.xml') for i in addon_ids ] params = list(zip(addon_names, profile_dirs, active_settings_xmls)) for addon in params: try: try: if kodi_utils.progressDialog.iscanceled(): break except: pass current_progress = params.index(addon) + 1 removed_settings = [] active_settings = [] current_user_settings = [] removed_append = removed_settings.append active_append = active_settings.append current_append = current_user_settings.append root = ET.parse(addon[2]).getroot() for item in root.findall('./category/setting'): setting_id = item.get('id') if setting_id: active_append(setting_id) settings_xml = os.path.join(addon[1], 'settings.xml') root = ET.parse(settings_xml).getroot() for item in root: dict_item = {} setting_id = item.get('id') setting_default = item.get('default') setting_value = item.text dict_item['id'] = setting_id if setting_value: dict_item['value'] = setting_value if setting_default: dict_item['default'] = setting_default current_append(dict_item) new_content = _make_content(current_user_settings) xml_file = kodi_utils.open_file(settings_xml, 'w') xml_file.write(new_content) xml_file.close() percent = int((current_progress / float(len(params))) * 100) line2 = ls(32812) % addon[0] line3 = ls(32813) % len(removed_settings) kodi_utils.progressDialog.update(percent, '[CR]%s[CR]%s' % (line2, line3)) except: kodi_utils.notification(32574, 2000) kodi_utils.sleep(800) try: kodi_utils.progressDialog.close() except: pass kodi_utils.ok_dialog(text=32576, top_space=True)
def add_uncached_torrent(self, magnet_url, pack=False): from modules.kodi_utils import show_busy_dialog, hide_busy_dialog from modules.source_utils import supported_video_extensions def _transfer_info(transfer_id): info = self.transfers_list() if 'status' in info and info['status'] == 'success': for item in info['transfers']: if item['id'] == transfer_id: return item return {} def _return_failed(message=32574, cancelled=False): try: progressDialog.close() except Exception: pass hide_busy_dialog() sleep(500) if cancelled: if confirm_dialog(heading=32733, text=32044, top_space=True): ok_dialog(heading=32733, text=ls(32732) % ls(32061)) else: self.delete_transfer(transfer_id) else: ok_dialog(heading=32733, text=message) return False show_busy_dialog() extensions = supported_video_extensions() transfer_id = self.create_transfer(magnet_url) if not transfer_id['status'] == 'success': return _return_failed(transfer_id.get('message')) transfer_id = transfer_id['id'] transfer_info = _transfer_info(transfer_id) if not transfer_info: return _return_failed() if pack: self.clear_cache() hide_busy_dialog() ok_dialog(text=ls(32732) % ls(32061)) return True interval = 5 line = '%s[CR]%s[CR]%s' line1 = '%s...' % (ls(32732) % ls(32061)) line2 = transfer_info['name'] line3 = transfer_info['message'] progressDialog.create(ls(32733), line % (line1, line2, line3)) while not transfer_info['status'] == 'seeding': sleep(1000 * interval) transfer_info = _transfer_info(transfer_id) line3 = transfer_info['message'] progressDialog.update(int(float(transfer_info['progress']) * 100), line % (line1, line2, line3)) if monitor.abortRequested() == True: return sysexit() try: if progressDialog.iscanceled(): return _return_failed(ls(32736), cancelled=True) except Exception: pass if transfer_info.get('status') == 'stalled': return _return_failed() sleep(1000 * interval) try: progressDialog.close() except Exception: pass hide_busy_dialog() return True
def execute_nextep(meta, nextep_settings): def _get_nextep_params(): nextep_params = nextep_playback_info(meta) return nextep_params def _get_nextep_url(): Sources().playback_prep(nextep_params) return kodi_utils.get_property('fen_nextep_url') def _confirm_threshold(): nextep_threshold = nextep_settings['threshold'] if nextep_threshold == 0: return True try: current_number = int( kodi_utils.get_property('fen_total_autoplays')) except: current_number = 1 if current_number == nextep_threshold: current_number = 1 kodi_utils.set_property('fen_total_autoplays', str(current_number)) if open_window(('windows.next_episode', 'NextEpisode'), 'next_episode.xml', meta=nextep_meta, function='confirm'): return True else: kodi_utils.notification(32736, 1500) return False else: current_number += 1 kodi_utils.set_property('fen_total_autoplays', str(current_number)) return True def _continue_action(): if run_popup: action = open_window(('windows.next_episode', 'NextEpisode'), 'next_episode.xml', meta=nextep_meta, function='next_ep') else: action = 'close' return action def _control(): confirm_threshold = False final_action = 'cancel' while player.isPlayingVideo(): try: total_time = player.getTotalTime() curr_time = player.getTime() remaining_time = round(total_time - curr_time) if remaining_time <= nextep_threshold_check: if not confirm_threshold: confirm_threshold = _confirm_threshold() if not confirm_threshold: final_action = 'cancel' break if remaining_time <= display_nextep_popup: final_action = _continue_action() break kodi_utils.sleep(200) except: pass return final_action kodi_utils.clear_property('fen_nextep_url') player = FenPlayer() run_popup, display_nextep_popup = nextep_settings[ 'run_popup'], nextep_settings['window_time'] nextep_prep, nextep_threshold_check = nextep_settings[ 'start_prep'], nextep_settings['threshold_check'] nextep_meta, nextep_params = _get_nextep_params() if nextep_params == 'error': return kodi_utils.notification(32574, 3000) elif nextep_params == 'no_next_episode': return nextep_url = _get_nextep_url() if not nextep_url: return kodi_utils.notification(32760, 3000) action = _control() if action == 'cancel': return kodi_utils.notification(32736, 3000) elif action == 'play': player.stop() elif action == 'close': if not run_popup: kodi_utils.notification( '%s %s S%02dE%02d' % (ls(32801), nextep_meta['title'], nextep_meta['season'], nextep_meta['episode']), 6500, nextep_meta['poster']) while player.isPlayingVideo(): kodi_utils.sleep(100) kodi_utils.sleep(1000) player.run(nextep_url)