Ejemplo n.º 1
0
def historySetting():

    if kodi.get_setting('history_setting') == 'true':
        kodi.set_setting('history_setting', 'false')
    else:
        kodi.set_setting('history_setting', 'true')
    xbmc.executebuiltin("Container.Refresh")
Ejemplo n.º 2
0
def set_default_url(Scraper):
    default_url = kodi.get_setting('%s-default_url' % (Scraper.get_name()))
    if not default_url:
        default_url = random.choice(Scraper.OPTIONS)
        kodi.set_setting('%s-default_url' % (Scraper.get_name()), default_url)
    Scraper.base_url = default_url
    return default_url
Ejemplo n.º 3
0
    def __update_base_url(self, html):
        if re.search('new domain', html, re.I):
            match = dom_parser2.parse_dom(html,
                                          'a', {'rel': 'nofollow'},
                                          req='href')
            if match:
                html = super(self.__class__,
                             self)._http_get(match[0].attrs['href'],
                                             require_debrid=True,
                                             cache_limit=24)

        match = dom_parser2.parse_dom(html,
                                      'link', {'rel': 'canonical'},
                                      req='href')
        if match:
            new_base = match[0].attrs['href']
            parts = urlparse.urlparse(new_base)
            new_base = parts.scheme + '://' + parts.hostname
            if new_base not in self.base_url:
                logger.log('Updating 2DDL Base Url from: %s to %s' %
                           (self.base_url, new_base))
                self.base_url = new_base
                kodi.set_setting('%s-base_url' % (self.get_name()), new_base)
                return True

        return False
Ejemplo n.º 4
0
def update_all_scrapers():
    try:
        last_check = int(kodi.get_setting('last_list_check'))
    except:
        last_check = 0
    now = int(time.time())
    list_url = kodi.get_setting('scraper_url')
    scraper_password = kodi.get_setting('scraper_password')
    list_path = os.path.join(kodi.translate_path(kodi.get_profile()),
                             'scraper_list.txt')
    exists = os.path.exists(list_path)
    if list_url and scraper_password and (not exists or
                                          (now - last_check) > 15 * 60):
        _etag, scraper_list = utils2.get_and_decrypt(list_url,
                                                     scraper_password)
        if scraper_list:
            try:
                with open(list_path, 'w') as f:
                    f.write(scraper_list)

                kodi.set_setting('last_list_check', str(now))
                kodi.set_setting(
                    'scraper_last_update',
                    time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)))
                for line in scraper_list.split('\n'):
                    line = line.replace(' ', '')
                    if line:
                        scraper_url, filename = line.split(',')
                        if scraper_url.startswith('http'):
                            update_scraper(filename, scraper_url)
            except Exception as e:
                logger.log('Exception during scraper update: %s' % (e),
                           log_utils.LOGWARNING)
Ejemplo n.º 5
0
def do_auto_config():
    ACTION_PREVIOUS_MENU = 10
    ACTION_BACK = 92
    CONTINUE_BUTTON = 200
    CANCEL_BUTTON = 201
    RADIO_BUTTONS = range(302, 316)

    class AutoConfDialog(xbmcgui.WindowXMLDialog):
        def onInit(self):
            log_utils.log('onInit:', log_utils.LOGDEBUG, COMPONENT)
            self.OK = False
            
            try: responses = json.loads(kodi.get_setting('prev_responses'))
            except: responses = [True] * len(RADIO_BUTTONS)
            if len(responses) < len(RADIO_BUTTONS):
                responses += [True] * (len(RADIO_BUTTONS) - len(responses))
                
            for button, response in zip(RADIO_BUTTONS, responses):
                self.getControl(button).setSelected(response)
            
        def onAction(self, action):
            # log_utils.log('Action: %s' % (action.getId()), log_utils.LOGDEBUG, COMPONENT)
            if action == ACTION_PREVIOUS_MENU or action == ACTION_BACK:
                self.close()

        def onControl(self, control):
            # log_utils.log('onControl: %s' % (control), log_utils.LOGDEBUG, COMPONENT)
            pass

        def onFocus(self, control):
            # log_utils.log('onFocus: %s' % (control), log_utils.LOGDEBUG, COMPONENT)
            pass

        def onClick(self, control):
            # log_utils.log('onClick: %s' % (control), log_utils.LOGDEBUG, COMPONENT)
            focus_button = self.getControl(control)
            if focus_button.getId() == RADIO_BUTTONS[-1]:
                all_status = focus_button.isSelected()
                for button in RADIO_BUTTONS:
                    self.getControl(button).setSelected(all_status)
            
            if control == CONTINUE_BUTTON:
                self.OK = True
                
            if control == CANCEL_BUTTON:
                self.OK = False

            if control == CONTINUE_BUTTON or control == CANCEL_BUTTON:
                self.close()
        
        def get_responses(self):
            return [bool(self.getControl(button).isSelected()) for button in RADIO_BUTTONS]

    dialog = AutoConfDialog('AutoConfDialog.xml', kodi.get_path())
    dialog.doModal()
    if dialog.OK:
        responses = dialog.get_responses()
        kodi.set_setting('prev_responses', json.dumps(responses))
        perform_auto_conf(responses)
    del dialog
Ejemplo n.º 6
0
def update_all_scrapers():
        try: last_check = int(kodi.get_setting('last_list_check'))
        except: last_check = 0
        now = int(time.time())
        list_url = kodi.get_setting('scraper_url')
        scraper_password = kodi.get_setting('scraper_password')
        list_path = os.path.join(kodi.translate_path(kodi.get_profile()), 'scraper_list.txt')
        exists = os.path.exists(list_path)
        if list_url and scraper_password and (not exists or last_check < (now - (24 * 60 * 60))):
            scraper_list = utils2.get_and_decrypt(list_url, scraper_password)
            if scraper_list:
                try:
                    with open(list_path, 'w') as f:
                        f.write(scraper_list)
    
                    kodi.set_setting('last_list_check', str(now))
                    kodi.set_setting('scraper_last_update', time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)))
                    for line in scraper_list.split('\n'):
                        line = line.replace(' ', '')
                        if line:
                            scraper_url, filename = line.split(',')
                            if scraper_url.startswith('http'):
                                update_scraper(filename, scraper_url)
                except Exception as e:
                    log_utils.log('Exception during scraper update: %s' % (e), log_utils.LOGWARNING)
Ejemplo n.º 7
0
def do_disable_check():
    auto_disable = kodi.get_setting('auto-disable')
    disable_limit = int(kodi.get_setting('disable-limit'))
    cur_failures = utils2.get_failures()
    for cls in relevant_scrapers():
        fails = cur_failures.get(cls.get_name(), 0)
        if fails >= disable_limit:
            if auto_disable == DISABLE_SETTINGS.ON:
                kodi.set_setting('%s-enable' % (cls.get_name()), 'false')
                kodi.notify(msg='[COLOR blue]%s[/COLOR] %s' %
                            (cls.get_name(), utils2.i18n('scraper_disabled')),
                            duration=5000)
                cur_failures[cls.get_name()] = 0
            elif auto_disable == DISABLE_SETTINGS.PROMPT:
                dialog = xbmcgui.Dialog()
                line1 = utils2.i18n('disable_line1') % (cls.get_name(), fails)
                line2 = utils2.i18n('disable_line2')
                line3 = utils2.i18n('disable_line3')
                ret = dialog.yesno('SALTS', line1, line2, line3,
                                   utils2.i18n('keep_enabled'),
                                   utils2.i18n('disable_it'))
                if ret:
                    kodi.set_setting('%s-enable' % (cls.get_name()), 'false')
                    cur_failures[cls.get_name()] = 0
                else:
                    cur_failures[cls.get_name()] = -1
    utils2.store_failures(cur_failures)
Ejemplo n.º 8
0
def do_disable_check():
    auto_disable = kodi.get_setting('auto-disable')
    disable_limit = int(kodi.get_setting('disable-limit'))
    for cls in relevant_scrapers():
        setting = '%s_last_results' % (cls.get_name())
        fails = kodi.get_setting(setting)
        fails = int(fails) if fails else 0
        if fails >= disable_limit:
            if auto_disable == DISABLE_SETTINGS.ON:
                kodi.set_setting('%s-enable' % (cls.get_name()), 'false')
                kodi.notify(msg='[COLOR blue]%s[/COLOR] %s' %
                            (cls.get_name(), utils2.i18n('scraper_disabled')),
                            duration=5000)
                kodi.set_setting(setting, '0')
            elif auto_disable == DISABLE_SETTINGS.PROMPT:
                dialog = xbmcgui.Dialog()
                line1 = utils2.i18n('disable_line1') % (cls.get_name(), fails)
                line2 = utils2.i18n('disable_line2')
                line3 = utils2.i18n('disable_line3')
                ret = dialog.yesno('SALTS', line1, line2, line3,
                                   utils2.i18n('keep_enabled'),
                                   utils2.i18n('disable_it'))
                if ret:
                    kodi.set_setting('%s-enable' % (cls.get_name()), 'false')
                    kodi.set_setting(setting, '0')
                else:
                    kodi.set_setting(setting, '-1')
Ejemplo n.º 9
0
def set_default_url(Scraper):
    default_url = kodi.get_setting('%s-default_url' % (Scraper.get_name()))
    if not default_url:
        default_url = random.choice(Scraper.OPTIONS)
        kodi.set_setting('%s-default_url' % (Scraper.get_name()), default_url)
    Scraper.base_url = default_url
    return default_url
Ejemplo n.º 10
0
def do_auto_config():
    ACTION_PREVIOUS_MENU = 10
    ACTION_BACK = 92
    CONTINUE_BUTTON = 200
    CANCEL_BUTTON = 201
    RADIO_BUTTONS = range(302, 316)

    class AutoConfDialog(xbmcgui.WindowXMLDialog):
        def onInit(self):
            logger.log('onInit:', log_utils.LOGDEBUG)
            self.OK = False
            
            try: responses = json.loads(kodi.get_setting('prev_responses'))
            except: responses = [True] * len(RADIO_BUTTONS)
            if len(responses) < len(RADIO_BUTTONS):
                responses += [True] * (len(RADIO_BUTTONS) - len(responses))
                
            for button, response in zip(RADIO_BUTTONS, responses):
                self.getControl(button).setSelected(response)
            
        def onAction(self, action):
            # logger.log('Action: %s' % (action.getId()), log_utils.LOGDEBUG)
            if action == ACTION_PREVIOUS_MENU or action == ACTION_BACK:
                self.close()

        def onControl(self, control):
            # logger.log('onControl: %s' % (control), log_utils.LOGDEBUG)
            pass

        def onFocus(self, control):
            # logger.log('onFocus: %s' % (control), log_utils.LOGDEBUG)
            pass

        def onClick(self, control):
            # logger.log('onClick: %s' % (control), log_utils.LOGDEBUG)
            focus_button = self.getControl(control)
            if focus_button.getId() == RADIO_BUTTONS[-1]:
                all_status = focus_button.isSelected()
                for button in RADIO_BUTTONS:
                    self.getControl(button).setSelected(all_status)
            
            if control == CONTINUE_BUTTON:
                self.OK = True
                
            if control == CANCEL_BUTTON:
                self.OK = False

            if control == CONTINUE_BUTTON or control == CANCEL_BUTTON:
                self.close()
        
        def get_responses(self):
            return [bool(self.getControl(button).isSelected()) for button in RADIO_BUTTONS]

    dialog = AutoConfDialog('AutoConfDialog.xml', kodi.get_path())
    dialog.doModal()
    if dialog.OK:
        responses = dialog.get_responses()
        kodi.set_setting('prev_responses', json.dumps(responses))
        perform_auto_conf(responses)
    del dialog
Ejemplo n.º 11
0
def keep_search(section, search_text):
    head = int(kodi.get_setting('%s_search_head' % (section)))
    new_head = (head + 1) % SEARCH_HISTORY
    log_utils.log('Setting %s to %s' % (new_head, search_text),
                  log_utils.LOGDEBUG)
    _get_db_connection().set_setting('%s_search_%s' % (section, new_head),
                                     search_text)
    kodi.set_setting('%s_search_head' % (section), str(new_head))
Ejemplo n.º 12
0
	def authorize(self, pin):
		response = self._authorize(pin)
		if response:
			kodi.notify(header='Trakt', msg='You are now authorized' , duration=5000, sound=None)
			the_username=self.my_username()
			kodi.set_setting('trakt_username',the_username['username'])
		else:
			kodi.notify(header='Trakt', msg='Authorization Failed try again' , duration=5000, sound=None)
		return response
Ejemplo n.º 13
0
def disableSearch():

    if kodi.get_setting('search_setting') == 'true':
        try: os.remove(searchfile)
        except: pass
        kodi.set_setting('search_setting','false')
    else: kodi.set_setting('search_setting','true')
    kodi.notify(msg='Search history disabled.')
    quit()
Ejemplo n.º 14
0
def reset_base_url():
    xml_path = os.path.join(kodi.get_path(), 'resources', 'settings.xml')
    tree = ET.parse(xml_path)
    for category in tree.getroot().findall('category'):
        if category.get('label').startswith('Scrapers '):
            for setting in category.findall('setting'):
                if re.search('-base_url\d*$', setting.get('id')):
                    log_utils.log('Resetting: %s -> %s' % (setting.get('id'), setting.get('default')), xbmc.LOGDEBUG)
                    kodi.set_setting(setting.get('id'), setting.get('default'))
Ejemplo n.º 15
0
def reset_base_url():
    xml_path = os.path.join(kodi.get_path(), 'resources', 'settings.xml')
    tree = ET.parse(xml_path)
    for category in tree.getroot().findall('category'):
        if category.get('label').startswith('Scrapers '):
            for setting in category.findall('setting'):
                if setting.get('id').endswith('-base_url'):
                    log_utils.log('Resetting: %s -> %s' % (setting.get('id'), setting.get('default')), xbmc.LOGDEBUG)
                    kodi.set_setting(setting.get('id'), setting.get('default'))
Ejemplo n.º 16
0
	def do_init(self):
		do_init = True
		try:	
			test = self.query("SELECT 1 FROM version WHERE db_version >= ?", [self.db_version], force_double_array=False, silent=True)
			if test:
				kodi.set_setting("database.version", self.db_version)
				do_init = False
		except:
			do_init = True
		return do_init
Ejemplo n.º 17
0
def check_cooldown(cd_begin):
    black_list = ['plugin.video.metalliq', 'plugin.video.meta']
    active_plugin = xbmc.getInfoLabel('Container.PluginName')
    if active_plugin in black_list:
        cd_begin = time.time()
    
    active = 'false' if (time.time() - cd_begin) > 30 else 'true'
    if kodi.get_setting('cool_down') != active:
        kodi.set_setting('cool_down', active)
    
    return cd_begin
Ejemplo n.º 18
0
def check_cooldown(cd_begin):
    black_list = ['plugin.video.metalliq', 'plugin.video.meta']
    active_plugin = xbmc.getInfoLabel('Container.PluginName')
    if active_plugin in black_list:
        cd_begin = time.time()

    active = 'false' if (time.time() - cd_begin) > 30 else 'true'
    if kodi.get_setting('cool_down') != active:
        kodi.set_setting('cool_down', active)

    return cd_begin
Ejemplo n.º 19
0
 def __get_token(self):
     pin = self.pin_edit_control.getText().strip()
     if pin:
         try:
             trakt_api = Trakt_API(use_https=use_https, timeout=trakt_timeout)
             result = trakt_api.get_token(pin=pin)
             kodi.set_setting('trakt_oauth_token', result['access_token'])
             kodi.set_setting('trakt_refresh_token', result['refresh_token'])
             return True
         except:
             return False
     return False
Ejemplo n.º 20
0
 def do_init(self):
     do_init = True
     try:
         test = self.query("SELECT 1 FROM version WHERE db_version >= ?",
                           [self.db_version],
                           force_double_array=False,
                           silent=True)
         if test:
             kodi.set_setting("database.version", self.db_version)
             do_init = False
     except:
         do_init = True
     return do_init
Ejemplo n.º 21
0
def get_ua():
    try: last_gen = int(kodi.get_setting('last_ua_create'))
    except: last_gen = 0
    if not kodi.get_setting('current_ua') or last_gen < (time.time() - (7 * 24 * 60 * 60)):
        index = random.randrange(len(RAND_UAS))
        versions = {'win_ver': random.choice(WIN_VERS), 'feature': random.choice(FEATURES), 'br_ver': random.choice(BR_VERS[index])}
        user_agent = RAND_UAS[index].format(**versions)
        # logger.log('Creating New User Agent: %s' % (user_agent), log_utils.LOGDEBUG)
        kodi.set_setting('current_ua', user_agent)
        kodi.set_setting('last_ua_create', str(int(time.time())))
    else:
        user_agent = kodi.get_setting('current_ua')
    return user_agent
Ejemplo n.º 22
0
def get_ua():
    try: last_gen = int(kodi.get_setting('last_ua_create'))
    except: last_gen = 0
    if not kodi.get_setting('current_ua') or last_gen < (time.time() - (7 * 24 * 60 * 60)):
        index = random.randrange(len(RAND_UAS))
        versions = {'win_ver': random.choice(WIN_VERS), 'feature': random.choice(FEATURES), 'br_ver': random.choice(BR_VERS[index])}
        user_agent = RAND_UAS[index].format(**versions)
        logger.log('Creating New User Agent: %s' % (user_agent), log_utils.LOGDEBUG)
        kodi.set_setting('current_ua', user_agent)
        kodi.set_setting('last_ua_create', str(int(time.time())))
    else:
        user_agent = kodi.get_setting('current_ua')
    return user_agent
Ejemplo n.º 23
0
def make_source_sort_key():
    sso = kodi.get_setting('source_sort_order')
    # migrate sso to kodi setting
    if not sso:
        db_connection = _get_db_connection()
        sso = db_connection.get_setting('source_sort_order')
        sso = kodi.set_setting('source_sort_order', sso)
        db_connection.set_setting('source_sort_order', '')
        
    sort_key = {}
    i = 0
    scrapers = relevant_scrapers(include_disabled=True)
    scraper_names = [scraper.get_name() for scraper in scrapers]
    if sso:
        sources = sso.split('|')
        sort_key = {}
        for i, source in enumerate(sources):
            if source in scraper_names:
                sort_key[source] = -i

    for j, scraper in enumerate(scrapers):
        if scraper.get_name() not in sort_key:
            sort_key[scraper.get_name()] = -(i + j)

    return sort_key
Ejemplo n.º 24
0
def record_failures(fails, counts=None):
    if counts is None: counts = {}

    for name in fails:
        setting = '%s_last_results' % (name)
        # remove timeouts from counts so they aren't double counted
        if name in counts: del counts[name]
        if int(kodi.get_setting(setting)) > -1:
            accumulate_setting(setting, 5)

    for name in counts:
        setting = '%s_last_results' % (name)
        if counts[name]:
            kodi.set_setting(setting, '0')
        elif int(kodi.get_setting(setting)) > -1:
            accumulate_setting(setting)
Ejemplo n.º 25
0
def record_failures(fails, counts=None):
    if counts is None: counts = {}

    for name in fails:
        setting = '%s_last_results' % (name)
        # remove timeouts from counts so they aren't double counted
        if name in counts: del counts[name]
        if int(kodi.get_setting(setting)) > -1:
            accumulate_setting(setting, 5)
    
    for name in counts:
        setting = '%s_last_results' % (name)
        if counts[name]:
            kodi.set_setting(setting, '0')
        elif int(kodi.get_setting(setting)) > -1:
            accumulate_setting(setting)
Ejemplo n.º 26
0
 def __update_base_url(self, html):
     if re.search('new domain', html, re.I):
         match = dom_parser2.parse_dom(html, 'a', {'rel': 'nofollow'}, req='href')
         if match:
             html = super(self.__class__, self)._http_get(match[0].attrs['href'], require_debrid=True, cache_limit=24)
                     
     match = dom_parser2.parse_dom(html, 'link', {'rel': 'canonical'}, req='href')
     if match:
         new_base = match[0].attrs['href']
         parts = urlparse.urlparse(new_base)
         new_base = parts.scheme + '://' + parts.hostname
         if new_base not in self.base_url:
             logger.log('Updating 2DDL Base Url from: %s to %s' % (self.base_url, new_base))
             self.base_url = new_base
             kodi.set_setting('%s-base_url' % (self.get_name()), new_base)
             return True
     
     return False
Ejemplo n.º 27
0
        def onClick(self, control):
            # print 'onClick: %s' % (control)
            if control == AUTH_BUTTON:
                if not self.__get_token():
                    kodi.notify(msg=i18n('pin_auth_failed'), duration=5000)
                    return
                self.auth = True

            if control == LATER_BUTTON:
                kodi.notify(msg=i18n('remind_in_24hrs'), duration=5000)
                kodi.set_setting('last_reminder', str(int(time.time())))

            if control == NEVER_BUTTON:
                kodi.notify(msg=i18n('use_addon_settings'), duration=5000)
                kodi.set_setting('last_reminder', '-1')

            if control in [AUTH_BUTTON, LATER_BUTTON, NEVER_BUTTON]:
                self.close()
Ejemplo n.º 28
0
        def onClick(self, control):
            # print 'onClick: %s' % (control)
            if control == AUTH_BUTTON:
                if not self.__get_token():
                    kodi.notify(msg=i18n('pin_auth_failed'), duration=5000)
                    return
                self.auth = True

            if control == LATER_BUTTON:
                kodi.notify(msg=i18n('remind_in_24hrs'), duration=5000)
                kodi.set_setting('last_reminder', str(int(time.time())))

            if control == NEVER_BUTTON:
                kodi.notify(msg=i18n('use_addon_settings'), duration=5000)
                kodi.set_setting('last_reminder', '-1')

            if control in [AUTH_BUTTON, LATER_BUTTON, NEVER_BUTTON]:
                self.close()
Ejemplo n.º 29
0
def get_ua():
    import kodi
    try:
        last_gen = int(kodi.get_setting('last_ua_create'))
    except:
        last_gen = 0

    if not kodi.get_setting('current_ua') or last_gen < time.time() - 604800:

        index = random.randrange(len(RAND_UAS))
        versions = {
            'win_ver': random.choice(WIN_VERS),
            'feature': random.choice(FEATURES),
            'br_ver': random.choice(BR_VERS[index])
        }
        user_agent = RAND_UAS[index].format(**versions)
        kodi.set_setting('current_ua', user_agent)
        kodi.set_setting('last_ua_create', str(int(time.time())))
    else:
        user_agent = kodi.get_setting('current_ua')
    return user_agent
Ejemplo n.º 30
0
    def __update_writers(self):
        global MAX_WRITERS
        global INCREASED
        if self.db_type == DB_TYPES.SQLITE and DB_Connection.writes >= CHECK_THRESHOLD:
            lock_percent = DB_Connection.locks * 100 / DB_Connection.writes
            log_utils.log('Max Writers Update: %s/%s (%s%%) - %s' % (DB_Connection.locks, DB_Connection.writes, lock_percent, MAX_WRITERS))
            DB_Connection.writes = 0
            DB_Connection.locks = 0

            # allow more writers if locks are rare
            if lock_percent <= UP_THRESHOLD and not INCREASED:
                INCREASED = True
                MAX_WRITERS += 1
            # limit to fewer writers if locks are common
            elif MAX_WRITERS > 1 and lock_percent >= DOWN_THRESHOLD:
                MAX_WRITERS -= 1
            # just reset test if between threshholds or already only one writer
            else:
                return

            kodi.set_setting('sema_value', str(MAX_WRITERS))
Ejemplo n.º 31
0
    def __update_writers(self):
        global MAX_WRITERS
        global INCREASED
        if self.db_type == DB_TYPES.SQLITE and DB_Connection.writes >= CHECK_THRESHOLD:
            lock_percent = DB_Connection.locks * 100 / DB_Connection.writes
            log_utils.log('Max Writers Update: %s/%s (%s%%) - %s' % (DB_Connection.locks, DB_Connection.writes, lock_percent, MAX_WRITERS), COMPONENT)
            DB_Connection.writes = 0
            DB_Connection.locks = 0

            # allow more writers if locks are rare
            if lock_percent <= UP_THRESHOLD and not INCREASED:
                INCREASED = True
                MAX_WRITERS += 1
            # limit to fewer writers if locks are common
            elif MAX_WRITERS > 1 and lock_percent >= DOWN_THRESHOLD:
                MAX_WRITERS -= 1
            # just reset test if between threshholds or already only one writer
            else:
                return

            kodi.set_setting('sema_value', str(MAX_WRITERS))
Ejemplo n.º 32
0
def do_disable_check():
    scrapers = relevant_scrapers()
    auto_disable = kodi.get_setting('auto-disable')
    check_freq = int(kodi.get_setting('disable-freq'))
    disable_thresh = int(kodi.get_setting('disable-thresh'))
    for cls in scrapers:
        last_check = db_connection.get_setting('%s_check' % (cls.get_name()))
        last_check = int(last_check) if last_check else 0
        tries = kodi.get_setting('%s_try' % (cls.get_name()))
        tries = int(tries) if tries else 0
        if tries > 0 and tries / check_freq > last_check / check_freq:
            kodi.set_setting('%s_check' % (cls.get_name()), str(tries))
            success_rate = calculate_success(cls.get_name())
            if success_rate < disable_thresh:
                if auto_disable == DISABLE_SETTINGS.ON:
                    kodi.set_setting('%s-enable' % (cls.get_name()), 'false')
                    kodi.notify(msg='[COLOR blue]%s[/COLOR] %s' %
                                (i18n('scraper_disabled')),
                                duration=5000)
                elif auto_disable == DISABLE_SETTINGS.PROMPT:
                    dialog = xbmcgui.Dialog()
                    line1 = i18n('disable_line1') % (cls.get_name(),
                                                     100 - success_rate, tries)
                    line2 = i18n('disable_line2')
                    line3 = i18n('disable_line3')
                    ret = dialog.yesno('SALTS', line1, line2, line3,
                                       i18n('keep_enabled'),
                                       i18n('disable_it'))
                    if ret:
                        kodi.set_setting('%s-enable' % (cls.get_name()),
                                         'false')
Ejemplo n.º 33
0
def do_disable_check():
    scrapers = relevant_scrapers()
    auto_disable = kodi.get_setting('auto-disable')
    check_freq = int(kodi.get_setting('disable-freq'))
    disable_thresh = int(kodi.get_setting('disable-thresh'))
    for cls in scrapers:
        last_check = db_connection.get_setting('%s_check' % (cls.get_name()))
        last_check = int(last_check) if last_check else 0
        tries = kodi.get_setting('%s_try' % (cls.get_name()))
        tries = int(tries) if tries else 0
        if tries > 0 and tries / check_freq > last_check / check_freq:
            kodi.set_setting('%s_check' % (cls.get_name()), str(tries))
            success_rate = calculate_success(cls.get_name())
            if success_rate < disable_thresh:
                if auto_disable == DISABLE_SETTINGS.ON:
                    kodi.set_setting('%s-enable' % (cls.get_name()), 'false')
                    kodi.notify(msg='[COLOR blue]%s[/COLOR] %s' % (i18n('scraper_disabled')), duration=5000)
                elif auto_disable == DISABLE_SETTINGS.PROMPT:
                    dialog = xbmcgui.Dialog()
                    line1 = i18n('disable_line1') % (cls.get_name(), 100 - success_rate, tries)
                    line2 = i18n('disable_line2')
                    line3 = i18n('disable_line3')
                    ret = dialog.yesno('SALTS', line1, line2, line3, i18n('keep_enabled'), i18n('disable_it'))
                    if ret:
                        kodi.set_setting('%s-enable' % (cls.get_name()), 'false')
Ejemplo n.º 34
0
def auth_trakt(Trakt_API, translations):
    i18n = translations.i18n
    start = time.time()
    use_https = kodi.get_setting('use_https') == 'true'
    trakt_timeout = int(kodi.get_setting('trakt_timeout'))
    trakt_api = Trakt_API(use_https=use_https, timeout=trakt_timeout)
    result = trakt_api.get_code()
    code, expires, interval = result['device_code'], result[
        'expires_in'], result['interval']
    time_left = expires - int(time.time() - start)
    line1 = i18n('verification_url') % (result['verification_url'])
    line2 = i18n('prompt_code') % (result['user_code'])
    with kodi.CountdownDialog(i18n('trakt_acct_auth'),
                              line1=line1,
                              line2=line2,
                              countdown=time_left,
                              interval=interval) as cd:
        result = cd.start(__auth_trakt, [trakt_api, code, i18n])

    try:
        kodi.set_setting('trakt_oauth_token', result['access_token'])
        kodi.set_setting('trakt_refresh_token', result['refresh_token'])
        trakt_api = Trakt_API(result['access_token'],
                              use_https=use_https,
                              timeout=trakt_timeout)
        profile = trakt_api.get_user_profile(cached=False)
        kodi.set_setting('trakt_user',
                         '%s (%s)' % (profile['username'], profile['name']))
        kodi.notify(msg=i18n('trakt_auth_complete'), duration=3000)
    except Exception as e:
        logger.log('Trakt Authorization Failed: %s' % (e), log_utils.LOGDEBUG)
Ejemplo n.º 35
0
def do_disable_check():
    auto_disable = kodi.get_setting('auto-disable')
    disable_limit = int(kodi.get_setting('disable-limit'))
    cur_failures = utils2.get_failures()
    for cls in relevant_scrapers():
        fails = cur_failures.get(cls.get_name(), 0)
        if fails >= disable_limit:
            if auto_disable == DISABLE_SETTINGS.ON:
                kodi.set_setting('%s-enable' % (cls.get_name()), 'false')
                kodi.notify(msg='[COLOR blue]%s[/COLOR] %s' % (cls.get_name(), utils2.i18n('scraper_disabled')), duration=5000)
                cur_failures[cls.get_name()] = 0
            elif auto_disable == DISABLE_SETTINGS.PROMPT:
                dialog = xbmcgui.Dialog()
                line1 = utils2.i18n('disable_line1') % (cls.get_name(), fails)
                line2 = utils2.i18n('disable_line2')
                line3 = utils2.i18n('disable_line3')
                ret = dialog.yesno('SALTS', line1, line2, line3, utils2.i18n('keep_enabled'), utils2.i18n('disable_it'))
                if ret:
                    kodi.set_setting('%s-enable' % (cls.get_name()), 'false')
                    cur_failures[cls.get_name()] = 0
                else:
                    cur_failures[cls.get_name()] = -1
    utils2.store_failures(cur_failures)
Ejemplo n.º 36
0
def do_disable_check():
    auto_disable = kodi.get_setting("auto-disable")
    disable_limit = int(kodi.get_setting("disable-limit"))
    for cls in relevant_scrapers():
        setting = "%s_last_results" % (cls.get_name())
        fails = kodi.get_setting(setting)
        fails = int(fails) if fails else 0
        if fails >= disable_limit:
            if auto_disable == DISABLE_SETTINGS.ON:
                kodi.set_setting("%s-enable" % (cls.get_name()), "false")
                kodi.notify(msg="[COLOR blue]%s[/COLOR] %s" % (cls.get_name(), i18n("scraper_disabled")), duration=5000)
                kodi.set_setting(setting, "0")
            elif auto_disable == DISABLE_SETTINGS.PROMPT:
                dialog = xbmcgui.Dialog()
                line1 = i18n("disable_line1") % (cls.get_name(), fails)
                line2 = i18n("disable_line2")
                line3 = i18n("disable_line3")
                ret = dialog.yesno("SALTS", line1, line2, line3, i18n("keep_enabled"), i18n("disable_it"))
                if ret:
                    kodi.set_setting("%s-enable" % (cls.get_name()), "false")
                    kodi.set_setting(setting, "0")
                else:
                    kodi.set_setting(setting, "-1")
Ejemplo n.º 37
0
def do_disable_check():
    auto_disable = kodi.get_setting('auto-disable')
    disable_limit = int(kodi.get_setting('disable-limit'))
    for cls in relevant_scrapers():
        setting = '%s_last_results' % (cls.get_name())
        fails = kodi.get_setting(setting)
        fails = int(fails) if fails else 0
        if fails >= disable_limit:
            if auto_disable == DISABLE_SETTINGS.ON:
                kodi.set_setting('%s-enable' % (cls.get_name()), 'false')
                kodi.notify(msg='[COLOR blue]%s[/COLOR] %s' % (cls.get_name(), i18n('scraper_disabled')), duration=5000)
                kodi.set_setting(setting, '0')
            elif auto_disable == DISABLE_SETTINGS.PROMPT:
                dialog = xbmcgui.Dialog()
                line1 = i18n('disable_line1') % (cls.get_name(), fails)
                line2 = i18n('disable_line2')
                line3 = i18n('disable_line3')
                ret = dialog.yesno('SALTS', line1, line2, line3, i18n('keep_enabled'), i18n('disable_it'))
                if ret:
                    kodi.set_setting('%s-enable' % (cls.get_name()), 'false')
                    kodi.set_setting(setting, '0')
                else:
                    kodi.set_setting(setting, '-1')
Ejemplo n.º 38
0
 def __get_token(self, client_id, client_secret, code):
     try:
         name = self.get_name()
         kodi.set_setting('%s-client_id' % (name), client_id)
         kodi.set_setting('%s-client_secret' % (name), client_secret)
         data = {'client_id': client_id, 'client_secret': client_secret, 'code': code}
         html = self._http_get(OAUTH_TOKEN_URL, data=data, cache_limit=0)
         if not html:
             return False
         
         js_data = scraper_utils.parse_json(html, OAUTH_TOKEN_URL)
         kodi.set_setting('%s-token' % (name), js_data['access_token'])
         kodi.set_setting('%s-refresh' % (name), js_data['refresh_token'])
         return js_data['access_token']
     except Exception as e:
         log_utils.log('Torba Authorization failed: %s' % (e), log_utils.LOGWARNING)
         return False
Ejemplo n.º 39
0
def auth_trakt():
    start = time.time()
    use_https = kodi.get_setting('use_https') == 'true'
    trakt_timeout = int(kodi.get_setting('trakt_timeout'))
    trakt_api = Trakt_API(use_https=use_https, timeout=trakt_timeout)
    result = trakt_api.get_code()
    code, expires, interval = result['device_code'], result[
        'expires_in'], result['interval']
    time_left = expires - int(time.time() - start)
    line1 = i18n('verification_url') % (result['verification_url'])
    line2 = i18n('prompt_code') % (result['user_code'])
    line3 = i18n('code_expires') % (time_left)
    with ProgressDialog(i18n('trakt_acct_auth'),
                        line1=line1,
                        line2=line2,
                        line3=line3) as pd:
        pd.update(100)
        while time_left:
            for _ in range(INTERVALS):
                kodi.sleep(interval * 1000 / INTERVALS)
                if pd.is_canceled(): return

            try:
                result = trakt_api.get_device_token(code)
                break
            except urllib2.URLError as e:
                # authorization is pending; too fast
                if e.code in [400, 429]:
                    pass
                elif e.code == 418:
                    kodi.notify(msg=i18n('user_reject_auth'), duration=3000)
                    return
                elif e.code == 410:
                    break
                else:
                    raise

            time_left = expires - int(time.time() - start)
            progress = time_left * 100 / expires
            pd.update(progress, line3=i18n('code_expires') % (time_left))

    try:
        kodi.set_setting('trakt_oauth_token', result['access_token'])
        kodi.set_setting('trakt_refresh_token', result['refresh_token'])
        trakt_api = Trakt_API(result['access_token'],
                              use_https=use_https,
                              timeout=trakt_timeout)
        profile = trakt_api.get_user_profile(cached=False)
        kodi.set_setting('trakt_user',
                         '%s (%s)' % (profile['username'], profile['name']))
        kodi.notify(msg=i18n('trakt_auth_complete'), duration=3000)
    except Exception as e:
        log_utils.log('Trakt Authorization Failed: %s' % (e),
                      log_utils.LOGDEBUG)
Ejemplo n.º 40
0
 def __get_token(self):
     pin = self.pin_edit_control.getText().strip()
     if pin:
         try:
             trakt_api = Trakt_API(use_https=use_https, timeout=trakt_timeout)
             result = trakt_api.get_token(pin=pin)
             kodi.set_setting('trakt_oauth_token', result['access_token'])
             kodi.set_setting('trakt_refresh_token', result['refresh_token'])
             profile = trakt_api.get_user_profile(cached=False)
             kodi.set_setting('trakt_user', '%s (%s)' % (profile['username'], profile['name']))
             return True
         except:
             return False
     return False
Ejemplo n.º 41
0
def auth_trakt():
    trakt_api = trakt.TraktAPI()
    start = time.time()
    use_https = kodi.get_setting('use_https') == 'true'
    trakt_timeout = int(kodi.get_setting('timeout'))
    trakt_api = trakt.TraktAPI(use_https=use_https, timeout=trakt_timeout)
    result = trakt_api.get_code()
    kodi.log(result)
    code, expires, interval = result['device_code'], result[
        'expires_in'], result['interval']
    time_left = expires - int(time.time() - start)
    line1 = 'On ANY Device visit: ' + result['verification_url']
    line2 = 'When promted , enter code: ' + result['user_code']
    with kodi.CountdownDialog('Authorizer your account',
                              line1=line1,
                              line2=line2,
                              countdown=time_left,
                              interval=interval) as cd:
        result = cd.start(__auth_trakt, [trakt_api, code, 'TEST'])

    try:
        trakt_api = trakt.TraktAPI()
        kodi.set_setting('trakt_oauth_token', result['access_token'])
        kodi.set_setting('trakt_refresh_token', result['refresh_token'])
        kodi.set_setting('trakt_authorized', "true")
        # trakt_api = trakt.Trakt_API(result['access_token'], use_https=True, timeout=trakt_timeout)
        kodi.log(result['access_token'])
        profile = trakt_api.my_username()
        #kodi.log("PROFILE RESULT " + profile['username'])
        kodi.set_setting('trakt_username',
                         profile['username'] + '/' + profile['name'])
        kodi.notify(header='Trakt',
                    msg='You are now authorized',
                    duration=5000,
                    sound=None)
        #kodi.notify(msg='trakt_auth_complete', duration=3000)
    except Exception as e:
        log_utils.log('Trakt Authorization Failed: %s' % (e),
                      log_utils.LOGDEBUG)
Ejemplo n.º 42
0
def auth_trakt():
    start = time.time()
    use_https = kodi.get_setting('use_https') == 'true'
    trakt_timeout = int(kodi.get_setting('trakt_timeout'))
    trakt_api = Trakt_API(use_https=use_https, timeout=trakt_timeout)
    result = trakt_api.get_code()
    code, expires, interval = result['device_code'], result['expires_in'], result['interval']
    time_left = expires - int(time.time() - start)
    line1 = i18n('verification_url') % (result['verification_url'])
    line2 = i18n('prompt_code') % (result['user_code'])
    line3 = i18n('code_expires') % (time_left)
    with ProgressDialog(i18n('trakt_acct_auth'), line1=line1, line2=line2, line3=line3) as pd:
        pd.update(100)
        while time_left:
            for _ in range(INTERVALS):
                kodi.sleep(interval * 1000 / INTERVALS)
                if pd.is_canceled(): return

            try:
                result = trakt_api.get_device_token(code)
                break
            except urllib2.URLError as e:
                # authorization is pending; too fast
                if e.code in [400, 429]:
                    pass
                elif e.code == 418:
                    kodi.notify(msg=i18n('user_reject_auth'), duration=3000)
                    return
                elif e.code == 410:
                    break
                else:
                    raise
                
            time_left = expires - int(time.time() - start)
            progress = time_left * 100 / expires
            pd.update(progress, line3=i18n('code_expires') % (time_left))
        
    try:
        kodi.set_setting('trakt_oauth_token', result['access_token'])
        kodi.set_setting('trakt_refresh_token', result['refresh_token'])
        trakt_api = Trakt_API(result['access_token'], use_https=use_https, timeout=trakt_timeout)
        profile = trakt_api.get_user_profile(cached=False)
        kodi.set_setting('trakt_user', '%s (%s)' % (profile['username'], profile['name']))
        kodi.notify(msg=i18n('trakt_auth_complete'), duration=3000)
    except Exception as e:
        log_utils.log('Trakt Authorization Failed: %s' % (e), log_utils.LOGDEBUG)
Ejemplo n.º 43
0
 def __get_token(self):
     pin = self.pin_edit_control.getText().strip()
     if pin:
         try:
             trakt_api = Trakt_API(use_https=use_https,
                                   timeout=trakt_timeout)
             result = trakt_api.get_token(pin=pin)
             kodi.set_setting('trakt_oauth_token',
                              result['access_token'])
             kodi.set_setting('trakt_refresh_token',
                              result['refresh_token'])
             profile = trakt_api.get_user_profile(cached=False)
             kodi.set_setting(
                 'trakt_user',
                 '%s (%s)' % (profile['username'], profile['name']))
             return True
         except:
             return False
     return False
Ejemplo n.º 44
0
def auth_trakt(Trakt_API, translations):
    i18n = translations.i18n
    start = time.time()
    use_https = kodi.get_setting('use_https') == 'true'
    trakt_timeout = int(kodi.get_setting('trakt_timeout'))
    trakt_api = Trakt_API(use_https=use_https, timeout=trakt_timeout)
    result = trakt_api.get_code()
    code, expires, interval = result['device_code'], result['expires_in'], result['interval']
    time_left = expires - int(time.time() - start)
    line1 = i18n('verification_url') % (result['verification_url'])
    line2 = i18n('prompt_code') % (result['user_code'])
    with kodi.CountdownDialog(i18n('trakt_acct_auth'), line1=line1, line2=line2, countdown=time_left, interval=interval) as cd:
        result = cd.start(__auth_trakt, [trakt_api, code, i18n])
    
    try:
        kodi.set_setting('trakt_oauth_token', result['access_token'])
        kodi.set_setting('trakt_refresh_token', result['refresh_token'])
        trakt_api = Trakt_API(result['access_token'], use_https=use_https, timeout=trakt_timeout)
        profile = trakt_api.get_user_profile(cached=False)
        kodi.set_setting('trakt_user', '%s (%s)' % (profile['username'], profile['name']))
        kodi.notify(msg=i18n('trakt_auth_complete'), duration=3000)
    except Exception as e:
        logger.log('Trakt Authorization Failed: %s' % (e), log_utils.LOGDEBUG)
Ejemplo n.º 45
0
def store_failures(failures):
    failures = dict(
        (key, value) for key, value in failures.iteritems() if value != 0)
    kodi.set_setting('scraper_failures', json.dumps(failures))
Ejemplo n.º 46
0
def accumulate_setting(setting, addend=1):
    cur_value = kodi.get_setting(setting)
    cur_value = int(cur_value) if cur_value else 0
    kodi.set_setting(setting, cur_value + addend)
Ejemplo n.º 47
0
def keep_search(section, search_text):
    head = int(kodi.get_setting("%s_search_head" % (section)))
    new_head = (head + 1) % SEARCH_HISTORY
    log_utils.log("Setting %s to %s" % (new_head, search_text), log_utils.LOGDEBUG)
    db_connection.set_setting("%s_search_%s" % (section, new_head), search_text)
    kodi.set_setting("%s_search_head" % (section), str(new_head))
Ejemplo n.º 48
0
    def __call_trakt(self, url, data=None, params=None, auth=True, cache_limit=.25, cached=True):
        if not cached: cache_limit = 0
        db_cache_limit = cache_limit if cache_limit > 8 else 8
        json_data = json.dumps(data) if data else None
        headers = {'Content-Type': 'application/json', 'trakt-api-key': V2_API_KEY, 'trakt-api-version': 2}
        url = '%s%s%s' % (self.protocol, BASE_URL, url)
        if params: url = url + '?' + urllib.urlencode(params)

        db_connection = DB_Connection()
        created, cached_result = db_connection.get_cached_url(url, db_cache_limit)
        if cached_result and (time.time() - created) < (60 * 60 * cache_limit):
            result = cached_result
            log_utils.log('Returning cached result for: %s' % (url), log_utils.LOGDEBUG)
        else:
            auth_retry = False
            while True:
                try:
                    if auth: headers.update({'Authorization': 'Bearer %s' % (self.token)})
                    log_utils.log('Trakt Call: %s, header: %s, data: %s' % (url, headers, data), log_utils.LOGDEBUG)
                    request = urllib2.Request(url, data=json_data, headers=headers)
                    f = urllib2.urlopen(request, timeout=self.timeout)
                    result = ''
                    while True:
                        data = f.read()
                        if not data: break
                        result += data

                    db_connection.cache_url(url, result)
                    break
                except (ssl.SSLError, socket.timeout)  as e:
                    if cached_result:
                        result = cached_result
                        log_utils.log('Temporary Trakt Error (%s). Using Cached Page Instead.' % (str(e)), log_utils.LOGWARNING)
                    else:
                        raise TransientTraktError('Temporary Trakt Error: ' + str(e))
                except urllib2.URLError as e:
                    if isinstance(e, urllib2.HTTPError):
                        if e.code in TEMP_ERRORS:
                            if cached_result:
                                result = cached_result
                                log_utils.log('Temporary Trakt Error (%s). Using Cached Page Instead.' % (str(e)), log_utils.LOGWARNING)
                                break
                            else:
                                raise TransientTraktError('Temporary Trakt Error: ' + str(e))
                        elif e.code == 401 or e.code == 405:
                            if auth_retry or url.endswith('/token'):
                                self.token = None
                                kodi.set_setting('trakt_oauth_token', '')
                                kodi.set_setting('trakt_refresh_token', '')
                                raise TraktError('Trakt Call Authentication Failed (%s)' % (e.code))
                            else:
                                result = self.get_token()
                                self.token = result['access_token']
                                kodi.set_setting('trakt_oauth_token', result['access_token'])
                                kodi.set_setting('trakt_refresh_token', result['refresh_token'])
                                auth_retry = True
                        elif e.code == 404:
                            raise TraktNotFoundError()
                        else:
                            raise
                    elif isinstance(e.reason, socket.timeout) or isinstance(e.reason, ssl.SSLError):
                        if cached_result:
                            result = cached_result
                            log_utils.log('Temporary Trakt Error (%s). Using Cached Page Instead' % (str(e)), log_utils.LOGWARNING)
                            break
                        else:
                            raise TransientTraktError('Temporary Trakt Error: ' + str(e))
                    else:
                        raise TraktError('Trakt Error: ' + str(e))
                except:
                    raise

        response = json.loads(result)

        if 'status' in response and response['status'] == 'failure':
            if 'message' in response: raise TraktError(response['message'])
            if 'error' in response: raise TraktError(response['error'])
            else: raise TraktError()
        else:
            # log_utils.log('Trakt Response: %s' % (response), xbmc.LOGDEBUG)
            return response
Ejemplo n.º 49
0
    def __call_trakt(self, url, method=None, data=None, params=None, auth=True, cache_limit=.25, cached=True):
        res_headers = {}
        if not cached: cache_limit = 0
        if self.offline:
            db_cache_limit = int(time.time()) / 60 / 60
        else:
            if cache_limit > 8:
                db_cache_limit = cache_limit
            else:
                db_cache_limit = 8
        json_data = json.dumps(data) if data else None
        headers = {'Content-Type': 'application/json', 'trakt-api-key': V2_API_KEY, 'trakt-api-version': 2}
        url = '%s%s%s' % (self.protocol, BASE_URL, url)
        if params: url = url + '?' + urllib.urlencode(params)

        db_connection = DB_Connection()
        created, cached_headers, cached_result = db_connection.get_cached_url(url, json_data, db_cache_limit)
        if cached_result and (self.offline or (time.time() - created) < (60 * 60 * cache_limit)):
            result = cached_result
            res_headers = dict(cached_headers)
            log_utils.log('***Using cached result for: %s' % (url), log_utils.LOGDEBUG)
        else:
            auth_retry = False
            while True:
                try:
                    if auth: headers.update({'Authorization': 'Bearer %s' % (self.token)})
                    log_utils.log('***Trakt Call: %s, header: %s, data: %s cache_limit: %s cached: %s' % (url, headers, json_data, cache_limit, cached), log_utils.LOGDEBUG)
                    request = urllib2.Request(url, data=json_data, headers=headers)
                    if method is not None: request.get_method = lambda: method.upper()
                    response = urllib2.urlopen(request, timeout=self.timeout)
                    result = ''
                    while True:
                        data = response.read()
                        if not data: break
                        result += data
                    res_headers = dict(response.info().items())

                    db_connection.cache_url(url, result, json_data, response.info().items())
                    break
                except (ssl.SSLError, socket.timeout) as e:
                    if cached_result:
                        result = cached_result
                        log_utils.log('Temporary Trakt Error (%s). Using Cached Page Instead.' % (str(e)), log_utils.LOGWARNING)
                    else:
                        raise TransientTraktError('Temporary Trakt Error: ' + str(e))
                except urllib2.URLError as e:
                    if isinstance(e, urllib2.HTTPError):
                        if e.code in TEMP_ERRORS:
                            if cached_result:
                                result = cached_result
                                log_utils.log('Temporary Trakt Error (%s). Using Cached Page Instead.' % (str(e)), log_utils.LOGWARNING)
                                break
                            else:
                                raise TransientTraktError('Temporary Trakt Error: ' + str(e))
                        elif e.code == 401 or e.code == 405:
                            # token is fine, profile is private
                            if e.info().getheader('X-Private-User') == 'true':
                                raise TraktAuthError('Object is No Longer Available (%s)' % (e.code))
                            # auth failure retry or a token request
                            elif auth_retry or url.endswith('/oauth/token'):
                                self.token = None
                                kodi.set_setting('trakt_oauth_token', '')
                                kodi.set_setting('trakt_refresh_token', '')
                                raise TraktAuthError('Trakt Call Authentication Failed (%s)' % (e.code))
                            # first try token fail, try to refresh token
                            else:
                                result = self.refresh_token(kodi.get_setting('trakt_refresh_token'))
                                self.token = result['access_token']
                                kodi.set_setting('trakt_oauth_token', result['access_token'])
                                kodi.set_setting('trakt_refresh_token', result['refresh_token'])
                                auth_retry = True
                        elif e.code == 404:
                            raise TraktNotFoundError('Object Not Found (%s)' % (e.code))
                        else:
                            raise
                    elif isinstance(e.reason, socket.timeout) or isinstance(e.reason, ssl.SSLError):
                        if cached_result:
                            result = cached_result
                            log_utils.log('Temporary Trakt Error (%s). Using Cached Page Instead' % (str(e)), log_utils.LOGWARNING)
                            break
                        else:
                            raise TransientTraktError('Temporary Trakt Error: ' + str(e))
                    else:
                        raise TraktError('Trakt Error: ' + str(e))
                except:
                    raise

        try:
            js_data = json.loads(result)
            if 'x-sort-by' in res_headers and 'x-sort-how' in res_headers:
                js_data = utils2.sort_list(res_headers['x-sort-by'], res_headers['x-sort-how'], js_data)
        except ValueError:
            js_data = ''
            if result:
                log_utils.log('Invalid JSON Trakt API Response: %s - |%s|' % (url, js_data), log_utils.LOGERROR)

        # log_utils.log('Trakt Response: %s' % (response), xbmc.LOGDEBUG)
        return js_data
Ejemplo n.º 50
0
def perform_auto_conf(responses):
    length = len(responses)
    TOTAL = 12
    if length < TOTAL:
        responses += [True] * (TOTAL - length)
        
    if responses[0]: kodi.set_setting('trakt_timeout', '60')
    if responses[1]: kodi.set_setting('calendar-day', '-1')
    if responses[2]: kodi.set_setting('calendar_time', '2')
    if responses[3]: kodi.set_setting('source_timeout', '20')
    if responses[4]: kodi.set_setting('include_watchlist_next', 'true')
    if responses[5]: kodi.set_setting('filter_direct', 'true')
    if responses[6]: kodi.set_setting('filter_unusable', 'true')
    if responses[7]: kodi.set_setting('show_debrid', 'true')
    if responses[8]: kodi.set_setting('source_results', '0')
    if responses[9]:
        kodi.set_setting('enable_sort', 'true')
        kodi.set_setting('sort1_field', '2')
        kodi.set_setting('sort2_field', '5')
        kodi.set_setting('sort3_field', '6')
        kodi.set_setting('sort4_field', '1')
        kodi.set_setting('sort5_field', '3')
        kodi.set_setting('sort6_field', '4')

    if responses[10]:
        tiers = ['Local', 'Furk.net', 'Premiumize.me', 'EasyNews', 'DD.tv', 'NoobRoom',
                 ['WatchHD', 'IFlix', 'MoviesPlanet', 'CyberReel', '9Movies', '123Movies', 'niter.tv', 'ororo.tv'],
                 ['movietv.to', 'StreamLord', 'tunemovie', 'afdah.org', 'xmovies8', 'xmovies8.v2', 'alluc.com'],
                 ['torba.se', 'IzlemeyeDeger', 'Rainierland', 'zumvo.com', 'PutMV', 'MiraDeTodo', 'beinmovie'],
                 ['SezonLukDizi', 'Dizimag', 'Dizilab', 'Dizigold', 'Diziay', 'Dizipas', 'OneClickTVShows'],
                 ['DDLValley', 'ReleaseBB', 'MyVideoLinks.eu', 'OCW', 'RLSSource.net', 'TVRelease.Net'],
                 ['IceFilms', 'PrimeWire', 'Flixanity', 'wso.ch', 'WatchSeries', 'UFlix.org', 'Putlocker', 'MovieHut'],
                 ['funtastic-vids', 'WatchFree.to', 'pftv', 'streamallthis.is', 'Movie4K', 'afdah', 'SolarMovie', 'yify-streaming'],
                 ['CouchTunerV2', 'CouchTunerV1', 'Watch8Now', 'yshows', 'TwoMovies.us', 'iWatchOnline', 'vidics.ch', 'pubfilm'],
                 ['OnlineMoviesIs', 'OnlineMoviesPro', 'ViewMovies', 'movie25', 'viooz.ac', 'view47', 'MoviesHD', 'wmo.ch'],
                 ['ayyex', 'stream-tv.co', 'clickplay.to', 'MintMovies', 'MovieNight', 'cmz', 'ch131', 'filmikz.ch'],
                 ['MovieTube', 'LosMovies', 'FilmStreaming.in', 'moviestorm.eu', 'MerDB'],
                 'MoviesOnline7']
    
        sso = []
        random_sso = kodi.get_setting('random_sso') == 'true'
        for tier in tiers:
            if isinstance(tier, basestring):
                sso.append(tier)
            else:
                if random_sso:
                    random.shuffle(tier)
                sso += tier
        kodi.set_setting('source_sort_order', '|'.join(sso))
    
    if responses[11]: reset_base_url()
    kodi.set_setting('filter-unknown', 'false')
    kodi.notify(msg=i18n('auto_conf_complete'))
Ejemplo n.º 51
0
def do_auto_config():
    ACTION_PREVIOUS_MENU = 10
    ACTION_BACK = 92
    CONTINUE_BUTTON = 200
    CANCEL_BUTTON = 201

    starty = 60
    posx = 30
    gap = 35
    RADIO_BUTTONS = [
        i18n('set_trakt_timeout'),
        i18n('set_cal_start'),
        i18n('set_cal_airtime'),
        i18n('set_scraper_timeout'),
        i18n('set_wl_mne'),
        i18n('set_test_direct'),
        i18n('set_filter_unusable'),
        i18n('set_show_debrid'),
        i18n('set_no_limit'),
        i18n('set_source_sort'),
        i18n('set_sso'),
        i18n('set_reset_url'),
        i18n('select_all_none')]
    
    class AutoConfDialog(xbmcgui.WindowXMLDialog):
        def onInit(self):
            log_utils.log('onInit:', log_utils.LOGDEBUG)
            self.OK = False
            self.radio_buttons = []
            posy = starty
            for label in RADIO_BUTTONS:
                self.radio_buttons.append(self.__get_radio_button(posx, posy, label))
                posy += gap
            
            try: responses = json.loads(kodi.get_setting('prev_responses'))
            except: responses = [True] * len(self.radio_buttons)
            if len(responses) < len(self.radio_buttons):
                responses += [True] * (len(self.radio_buttons) - len(responses))
            
            self.addControls(self.radio_buttons)
            last_button = None
            for response, radio_button in zip(responses, self.radio_buttons):
                radio_button.setSelected(response)
                if last_button is not None:
                    radio_button.controlUp(last_button)
                    radio_button.controlLeft(last_button)
                    last_button.controlDown(radio_button)
                    last_button.controlRight(radio_button)
                last_button = radio_button

            continue_ctrl = self.getControl(CONTINUE_BUTTON)
            cancel_ctrl = self.getControl(CANCEL_BUTTON)
            self.radio_buttons[0].controlUp(cancel_ctrl)
            self.radio_buttons[0].controlLeft(cancel_ctrl)
            self.radio_buttons[-1].controlDown(continue_ctrl)
            self.radio_buttons[-1].controlRight(continue_ctrl)
            continue_ctrl.controlUp(self.radio_buttons[-1])
            continue_ctrl.controlLeft(self.radio_buttons[-1])
            cancel_ctrl.controlDown(self.radio_buttons[0])
            cancel_ctrl.controlRight(self.radio_buttons[0])
            
        def __get_radio_button(self, x, y, label):
            kwargs = {'font': 'font12', 'focusTexture': 'button-focus2.png', 'noFocusTexture': 'button-nofocus.png', 'focusOnTexture': 'radiobutton-focus.png',
                      'noFocusOnTexture': 'radiobutton-focus.png', 'focusOffTexture': 'radiobutton-nofocus.png', 'noFocusOffTexture': 'radiobutton-nofocus.png'}
            temp = xbmcgui.ControlRadioButton(x, y, 450, 30, label, **kwargs)
            return temp
            
        def onAction(self, action):
            # log_utils.log('Action: %s' % (action.getId()), log_utils.LOGDEBUG)
            if action == ACTION_PREVIOUS_MENU or action == ACTION_BACK:
                self.close()

        def onControl(self, control):
            # log_utils.log('onControl: %s' % (control), log_utils.LOGDEBUG)
            pass

        def onFocus(self, control):
            # log_utils.log('onFocus: %s' % (control), log_utils.LOGDEBUG)
            pass

        def onClick(self, control):
            # log_utils.log('onClick: %s' % (control), log_utils.LOGDEBUG)
            focus_button = self.getControl(control)
            if focus_button == self.radio_buttons[-1]:
                all_status = focus_button.isSelected()
                for button in self.radio_buttons:
                    button.setSelected(all_status)
            
            if control == CONTINUE_BUTTON:
                self.OK = True
                
            if control == CANCEL_BUTTON:
                self.OK = False

            if control == CONTINUE_BUTTON or control == CANCEL_BUTTON:
                self.close()
        
        def get_responses(self):
            return [bool(button.isSelected()) for button in self.radio_buttons]

    dialog = AutoConfDialog('AutoConfDialog.xml', kodi.get_path())
    dialog.doModal()
    if dialog.OK:
        responses = dialog.get_responses()
        kodi.set_setting('prev_responses', json.dumps(responses))
        perform_auto_conf(responses)
    del dialog
Ejemplo n.º 52
0
	def _authorize(self, pin=None):
		if kodi.get_setting('debug') == "true":
			print "Attempting to login/refresh Trakt Account"
		uri = '/oauth/token'
		data = {'client_id': CLIENT_ID, 'client_secret': SECRET_ID, 'redirect_uri': REDIRECT_URI}
		if pin:
			data['code'] = pin
			data['grant_type'] = 'authorization_code'
		else:
			refresh_token = kodi.get_setting('trakt_refresh_token')
			if refresh_token:
				data['refresh_token'] = refresh_token
				data['grant_type'] = 'refresh_token'
			else:
				kodi.set_setting('trakt_oauth_token', '')
				kodi.set_setting('trakt_refresh_token', '')
				kodi.set_setting('trakt_authorized', 'false')
				return False
		if self.token is None: self.token = False
		response = self._call(uri, data, auth=False)
		if response is False or response is None:
			return False
		if 'access_token' in response.keys() and 'refresh_token' in response.keys():
			kodi.set_setting('trakt_oauth_token', response['access_token'])
			kodi.set_setting('trakt_refresh_token', response['refresh_token'])
			kodi.set_setting('trakt_authorized', "true")
			self.token = response['access_token']
			if kodi.get_setting('debug') == "true":
				print "YOU JUST AUTHORIZED TRAKT"
				#kodi.notify('TRAKT ','Account Authorized You may continue','5000','')
			return True
Ejemplo n.º 53
0
def accumulate_setting(setting, addend=1):
    cur_value = kodi.get_setting(setting)
    cur_value = int(cur_value) if cur_value else 0
    kodi.set_setting(setting, cur_value + addend)
Ejemplo n.º 54
0
def perform_auto_conf(responses):
    length = len(responses)
    TOTAL = 12
    if length < TOTAL:
        responses += [True] * (TOTAL - length)

    if responses[0]: kodi.set_setting('trakt_timeout', '60')
    if responses[1]: kodi.set_setting('calendar-day', '-1')
    if responses[2]: kodi.set_setting('calendar_time', '2')
    if responses[3]: kodi.set_setting('source_timeout', '20')
    if responses[4]: kodi.set_setting('include_watchlist_next', 'true')
    if responses[5]: kodi.set_setting('filter_direct', 'true')
    if responses[6]: kodi.set_setting('filter_unusable', 'true')
    if responses[7]: kodi.set_setting('show_debrid', 'true')
    if responses[8]: kodi.set_setting('source_results', '0')
    if responses[9]:
        kodi.set_setting('enable_sort', 'true')
        kodi.set_setting('sort1_field', '2')
        kodi.set_setting('sort2_field', '5')
        kodi.set_setting('sort3_field', '6')
        kodi.set_setting('sort4_field', '1')
        kodi.set_setting('sort5_field', '3')
        kodi.set_setting('sort6_field', '4')

    if responses[10]:
        tiers = [
            'Local', 'Premiumize.V2', 'Premiumize.me', 'Furk.net', 'EasyNews',
            'DD.tv', 'NoobRoom',
            [
                'WatchHD', 'IFlix', 'MoviesPlanet', 'TVWTVS', 'MWM', '9Movies',
                '123Movies', 'niter.tv', 'HDMovie14', 'ororo.tv', 'm4ufree'
            ],
            [
                'StreamLord', 'CyberReel', 'MovCav', 'tunemovie', 'MovieMax',
                'afdah.org', 'xmovies8', 'xmovies8.v2', 'MovieXK'
            ],
            [
                'Rainierland', 'DayT.se', 'FardaDownload', 'zumvo.com',
                'PutMV', 'vivo.to', 'MiraDeTodo', 'beinmovie', 'FireMoviesHD'
            ],
            [
                'IzlemeyeDeger', 'SezonLukDizi', 'Dizimag', 'Dizilab',
                'Dizigold', 'Dizibox', 'Diziay', 'Dizipas', 'OneClickTVShows',
                'OnlineDizi'
            ],
            [
                'DDLValley', '2DDL', 'ReleaseBB', 'MyVideoLinks.eu', 'OCW',
                'TheExtopia', 'RLSSource.net', 'TVRelease.Net'
            ],
            [
                'IceFilms', 'WatchEpisodes', 'PrimeWire', 'tvonline',
                'SantaSeries', 'Flixanity', 'wso.ch', 'WatchSeries',
                'UFlix.org', 'Putlocker'
            ],
            [
                'MovieWatcher', 'alluc.com', 'VKFlix', 'WatchFree.to', 'pftv',
                'streamallthis.is', 'Movie4K', 'afdah', 'SolarMovie'
            ],
            [
                'MysticLand', 'MovieSub', 'MovieHut', 'CouchTunerV2',
                'CouchTunerV1', 'Watch8Now', 'yshows', 'iWatchOnline'
            ],
            [
                'Ganool', 'vidics.ch', 'pubfilm', 'eMovies.Pro',
                'OnlineMoviesPro', 'movie25', 'viooz.ac', 'view47', 'MoviesHD'
            ],
            [
                'wmo.ch', 'stream-tv.co', 'clickplay.to', 'MintMovies',
                'MovieNight', 'cmz', 'ch131', 'filmikz.ch'
            ],
            [
                'MovieTube', 'LosMovies', 'FilmStreaming.in', 'moviestorm.eu',
                'MerDB'
            ]
        ]

        sso = []
        random_sso = kodi.get_setting('random_sso') == 'true'
        for tier in tiers:
            if isinstance(tier, basestring):
                sso.append(tier)
            else:
                if random_sso:
                    random.shuffle(tier)
                sso += tier
        kodi.set_setting('source_sort_order', '|'.join(sso))

    if responses[11]: reset_base_url()
    trigger = [
        False, True, False, True, False, True, True, False, True, False, False,
        False
    ]
    if all([t == r for t, r in zip(trigger, responses)]):
        kodi.set_setting('scraper_download', 'true')

    kodi.notify(msg=i18n('auto_conf_complete'))
Ejemplo n.º 55
0
def perform_auto_conf(responses):
    length = len(responses)
    TOTAL = 13
    if length < TOTAL:
        responses += [True] * (TOTAL - length)
        
    if responses[0]: kodi.set_setting('trakt_timeout', '60')
    if responses[1]: kodi.set_setting('calendar-day', '-1')
    if responses[2]: kodi.set_setting('calendar_time', '2')
    if responses[3]: kodi.set_setting('source_timeout', '20')
    if responses[4]: kodi.set_setting('include_watchlist_next', 'true')
    if responses[5]: kodi.set_setting('filter_direct', 'true')
    if responses[6]: kodi.set_setting('filter_unusable', 'true')
    if responses[7]: kodi.set_setting('show_debrid', 'true')
    if responses[8]: kodi.set_setting('source_results', '0')
    if responses[9]:
        kodi.set_setting('enable_sort', 'true')
        kodi.set_setting('sort1_field', '2')
        kodi.set_setting('sort2_field', '5')
        kodi.set_setting('sort3_field', '6')
        kodi.set_setting('sort4_field', '1')
        kodi.set_setting('sort5_field', '3')
        kodi.set_setting('sort6_field', '4')

    if responses[10]:
        tiers = ['Local', 'Premiumize.V2', 'Premiumize.me', 'Furk.net', 'EasyNews', 'DD.tv', 'NoobRoom',
                 ['IFlix', 'torba.se', 'MoviesPlanet', 'TVWTVS', 'MWM', '9Movies', '123Movies', 'niter.tv', 'HDMovie14', 'ororo.tv', 'm4ufree'],
                 ['StreamLord', 'CyberReel', 'tunemovie', 'MovieLocker', 'fmovie.co', 'afdah.org', 'xmovies8', 'xmovies8.v2', 'KiwiHD'],
                 ['MovieXK', 'Stage66', 'PelisPedia', 'DayT.se', 'FardaDownload', 'vu45', 'PutMV', 'PirateJunkies', 'FireMoviesHD', 'SeriesWatch'],
                 ['HEVCBluRay', 'SezonLukDizi', 'Dizimag', 'Dizilab', 'Dizigold', 'Dizibox', 'Diziay', 'Dizipas', 'OneClickTVShows', 'OnlineDizi'],
                 ['vivo.to', 'CloudMovie', 'DDLValley', '2DDL', 'DDLSeries', 'ReleaseBB', 'MyVideoLinks.eu', 'OCW', 'RLSSource.net'],
                 ['IceFilms', 'Flixanity', 'Watch5s', 'Rainierland', 'WatchEpisodes', 'PrimeWire', 'alluc.com', 'tvonline', 'SantaSeries', 'WatchSeries'],
                 ['RLSeries', 'Putlocker', 'Ganool', 'MovieWatcher', 'VKFlix', 'WatchFree.to', 'pftv', 'streamallthis.is', 'Movie4K', 'afdah', 'SolarMovie'],
                 ['MiraDeTodo', 'Filmovizija', 'UFlix.org', 'wso.ch', 'MovieSub', 'MovieHut', 'CouchTunerV1', 'Watch8Now', 'yshows', 'iWatchOnline'],
                 ['vidics.ch', 'pubfilm', 'eMovies.Pro', 'OnlineMoviesPro', 'movie25', 'viooz.ac', 'view47', 'MoviesHD', 'LosMovies'],
                 ['wmo.ch', 'stream-tv.co', 'MintMovies', 'MovieNight', 'cmz', 'ch131', 'filmikz.ch', 'moviestorm.eu', 'clickplay.to'],
                 ['MovieTube', 'FilmStreaming.in']]
    
        sso = []
        random_sso = kodi.get_setting('random_sso') == 'true'
        for tier in tiers:
            if isinstance(tier, basestring):
                sso.append(tier)
            else:
                if random_sso:
                    random.shuffle(tier)
                sso += tier
        kodi.set_setting('source_sort_order', '|'.join(sso))
    
    if responses[11]: reset_base_url()
    if responses[12]: kodi.set_setting('mne_time', '2')
    trigger = [False, True, False, True, False, True, True, False, True, False, False, False]
    if all([t == r for t, r in zip(trigger, responses)]):
        kodi.set_setting('scraper_download', 'true')
        
    kodi.notify(msg=i18n('auto_conf_complete'))
Ejemplo n.º 56
0
def do_auto_config():
    ACTION_PREVIOUS_MENU = 10
    ACTION_BACK = 92
    CONTINUE_BUTTON = 200
    CANCEL_BUTTON = 201

    starty = 60
    posx = 30
    gap = 35
    RADIO_BUTTONS = [
        i18n('set_trakt_timeout'),
        i18n('set_cal_start'),
        i18n('set_cal_airtime'),
        i18n('set_scraper_timeout'),
        i18n('set_wl_mne'),
        i18n('set_test_direct'),
        i18n('set_filter_unusable'),
        i18n('set_show_debrid'),
        i18n('set_no_limit'),
        i18n('set_source_sort'),
        i18n('set_sso'),
        i18n('set_reset_url'),
        i18n('select_all_none')
    ]

    class AutoConfDialog(xbmcgui.WindowXMLDialog):
        def onInit(self):
            log_utils.log('onInit:', log_utils.LOGDEBUG)
            self.OK = False
            self.radio_buttons = []
            posy = starty
            for label in RADIO_BUTTONS:
                self.radio_buttons.append(
                    self.__get_radio_button(posx, posy, label))
                posy += gap

            try:
                responses = json.loads(kodi.get_setting('prev_responses'))
            except:
                responses = [True] * len(self.radio_buttons)
            if len(responses) < len(self.radio_buttons):
                responses += [True
                              ] * (len(self.radio_buttons) - len(responses))

            self.addControls(self.radio_buttons)
            last_button = None
            for response, radio_button in zip(responses, self.radio_buttons):
                radio_button.setSelected(response)
                if last_button is not None:
                    radio_button.controlUp(last_button)
                    radio_button.controlLeft(last_button)
                    last_button.controlDown(radio_button)
                    last_button.controlRight(radio_button)
                last_button = radio_button

            continue_ctrl = self.getControl(CONTINUE_BUTTON)
            cancel_ctrl = self.getControl(CANCEL_BUTTON)
            self.radio_buttons[0].controlUp(cancel_ctrl)
            self.radio_buttons[0].controlLeft(cancel_ctrl)
            self.radio_buttons[-1].controlDown(continue_ctrl)
            self.radio_buttons[-1].controlRight(continue_ctrl)
            continue_ctrl.controlUp(self.radio_buttons[-1])
            continue_ctrl.controlLeft(self.radio_buttons[-1])
            cancel_ctrl.controlDown(self.radio_buttons[0])
            cancel_ctrl.controlRight(self.radio_buttons[0])

        def __get_radio_button(self, x, y, label):
            kwargs = {
                'font': 'font12',
                'focusTexture': 'button-focus2.png',
                'noFocusTexture': 'button-nofocus.png',
                'focusOnTexture': 'radiobutton-focus.png',
                'noFocusOnTexture': 'radiobutton-focus.png',
                'focusOffTexture': 'radiobutton-nofocus.png',
                'noFocusOffTexture': 'radiobutton-nofocus.png'
            }
            temp = xbmcgui.ControlRadioButton(x, y, 450, 30, label, **kwargs)
            return temp

        def onAction(self, action):
            # log_utils.log('Action: %s' % (action.getId()), log_utils.LOGDEBUG)
            if action == ACTION_PREVIOUS_MENU or action == ACTION_BACK:
                self.close()

        def onControl(self, control):
            # log_utils.log('onControl: %s' % (control), log_utils.LOGDEBUG)
            pass

        def onFocus(self, control):
            # log_utils.log('onFocus: %s' % (control), log_utils.LOGDEBUG)
            pass

        def onClick(self, control):
            # log_utils.log('onClick: %s' % (control), log_utils.LOGDEBUG)
            focus_button = self.getControl(control)
            if focus_button == self.radio_buttons[-1]:
                all_status = focus_button.isSelected()
                for button in self.radio_buttons:
                    button.setSelected(all_status)

            if control == CONTINUE_BUTTON:
                self.OK = True

            if control == CANCEL_BUTTON:
                self.OK = False

            if control == CONTINUE_BUTTON or control == CANCEL_BUTTON:
                self.close()

        def get_responses(self):
            return [bool(button.isSelected()) for button in self.radio_buttons]

    dialog = AutoConfDialog('AutoConfDialog.xml', kodi.get_path())
    dialog.doModal()
    if dialog.OK:
        responses = dialog.get_responses()
        kodi.set_setting('prev_responses', json.dumps(responses))
        perform_auto_conf(responses)
    del dialog