Example #1
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), xbmc.LOGDEBUG)
Example #2
0
def choose_list(Trakt_API, translations, username=None):
    i18n = translations.i18n
    trakt_api = Trakt_API(kodi.get_setting('trakt_oauth_token'),
                          kodi.get_setting('use_https') == 'true',
                          timeout=int(kodi.get_setting('trakt_timeout')))
    lists = trakt_api.get_lists(username)
    if username is None:
        lists.insert(0, {'name': 'watchlist', 'ids': {'slug': WATCHLIST_SLUG}})
    if lists:
        dialog = xbmcgui.Dialog()
        index = dialog.select(i18n('pick_a_list'),
                              [list_data['name'] for list_data in lists])
        if index > -1:
            return lists[index]['ids']['slug'], lists[index]['name']
    else:
        kodi.notify(msg=i18n('no_lists_for_user') % (username), duration=5000)
def searchDecide(url):
    search_on_off = kodi.get_setting("search_setting")

    if search_on_off == "true":
        name = "null"
        url = "2|SPLIT|" + url
        searchHistory(name, url)
    else:
        url = "null|SPLIT|" + url
        mainSearch(url)
Example #4
0
def getHistory():
    history_on_off = kodi.get_setting("history_setting")

    if history_on_off == "true":

        lst = [
            ('Clear History', None, 21, history_icon, False)
            ,
            ('Disable History', None, 22, history_icon, False)
            ,
            ('-------------------------------------', None, 999, history_icon, False)
        ]

        conn = sqlite3.connect(historydb)
        conn.text_factory = str
        c = conn.cursor()
        c.execute("SELECT * FROM history ORDER BY ID DESC")

        for (ID, date, time, title, url, site, iconimage) in c.fetchall():
            try:
                if site == 'Local File':
                    lst += [('[%s | %s - %s] - %s' % (kodi.giveColor(site, 'pink'), date, time, title), url + 'site=' + site + 'typeid=history', 801, iconimage, False)]
                else:
                    lst += [('[%s | %s - %s] - %s' % (kodi.giveColor(site, 'pink'), date, time, title), url + 'site=' + site + 'typeid=history', 801, iconimage, True)]
            except:
                pass
        conn.close()

        if len(lst) < 4:
            lst += [('No History Found', None, 999, history_icon, False)]
    else:
        lst = [
            ('Enable History Monitoring', None, 22, history_icon, False)
            ,
            ('-------------------------------------', None, 22, history_icon, False)
            ,
            ('History monitoring is currently disabled.', None, 22, history_icon, False)
        ]

    dirlst = []
    for i in lst:
        if not i[3]:
            icon = kodi.addonicon
        else:
            icon = i[3]
        fanart = kodi.addonfanart
        dirlst.append(
            {
                'name': kodi.giveColor(i[0], 'white'), 'url': i[1], 'mode': i[2], 'icon': icon, 'fanart': fanart,
                'folder': False, 'isDownloadable': i[4]
            }
        )

    buildDirectory(dirlst)
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()
Example #6
0
def parentalCheck():
    timestamp = None
    password = None

    conn = sqlite3.connect(parentaldb)
    conn.text_factory = str
    c = conn.cursor()
    c.execute("SELECT * FROM parental")

    for (passwd, timest) in c.fetchall():
        timestamp = timest
        password = passwd
    conn.close()

    session_time = int(kodi.get_setting('session_time'))

    if password:
        try:
            now = time.time()
            check = now - 60 * session_time
            if (not timestamp): timestamp = 0
        except:
            now = time.time()
            check = now - 60 * session_time
            timestamp = 0
    else:
        return

    if (timestamp < check):

        input = kodi.get_keyboard(
            'Please Enter Your Password - %s' % kodi.giveColor(
                '(%s Minute Session)' % str(session_time), 'red', True),
            hidden=True)
        if (not input):
            sys.exit(0)

        pass_one = hashlib.sha256(input).hexdigest()

        if password != pass_one:
            kodi.dialog.ok(kodi.get_name(),
                           "Sorry, the password you entered was incorrect.")
            sys.exit(0)
        else:
            delEntry(password)
            addEntry(password, now)
            kodi.dialog.ok(
                kodi.get_name(), 'Login successful!',
                'You now have a %s minute session before you will be asked for the password again.'
                % str(session_time))
    return
Example #7
0
def log(msg, level=xbmc.LOGDEBUG, component=None):
    req_level = level
    # override message level to force logging when addon logging turned on
    if kodi.get_setting('addon_debug') == 'true' and level == xbmc.LOGDEBUG:
        level = xbmc.LOGNOTICE

    try:
        if isinstance(msg, unicode):
            msg = '%s (ENCODED)' % (msg.encode('utf-8'))

        if req_level != xbmc.LOGDEBUG or (enabled_comp is None or component in enabled_comp):
            kodi._log('%s: %s' % (name, msg), level)

    except Exception as e:
        try:
            kodi._log('Logging Failure: %s' % (e), level)
        except:
            pass  # just give up
Example #8
0
class Logger(object):
    __loggers = {}
    __name = kodi.get_name()
    __addon_debug = kodi.get_setting('addon_debug') == 'true'
    __debug_on = _is_debugging()
    __disabled = set()

    @staticmethod
    def get_logger(name=None):
        if name not in Logger.__loggers:
            Logger.__loggers[name] = Logger()

        return Logger.__loggers[name]

    def disable(self):
        if self not in Logger.__disabled:
            Logger.__disabled.add(self)

    def enable(self):
        if self in Logger.__disabled:
            Logger.__disabled.remove(self)

    def log(self, msg, level=xbmc.LOGDEBUG):
        # if debug isn't on, skip disabled loggers unless addon_debug is on
        if not self.__debug_on:
            if self in self.__disabled:
                return
            elif level == xbmc.LOGDEBUG:
                if self.__addon_debug:
                    level = xbmc.LOGNOTICE
                else:
                    return

        try:
            if isinstance(msg, unicode):
                msg = '%s (ENCODED)' % (msg.encode('utf-8'))

            kodi._log('%s: %s' % (self.__name, msg), level)

        except Exception as e:
            try:
                kodi._log('Logging Failure: %s' % (e), level)
            except:
                pass  # just give up
Example #9
0
from __future__ import absolute_import
import time
from packlib import kodi
import cProfile
import pstats
from kodi_six import xbmc
import six

# Moved attributes found on six library
basestring = six.string_types
unicode = six.text_type
StringIO = six.StringIO

name = kodi.get_name()
enabled_comp = kodi.get_setting('enabled_comp')
if enabled_comp:
    enabled_comp = enabled_comp.split(',')
else:
    enabled_comp = None


def log(msg, level=xbmc.LOGDEBUG, component=None):
    req_level = level
    # override message level to force logging when addon logging turned on
    if kodi.get_setting('addon_debug') == 'true' and level == xbmc.LOGDEBUG:
        level = xbmc.LOGNOTICE

    try:
        if isinstance(msg, unicode):
            msg = '%s (ENCODED)' % (msg.encode('utf-8'))
    add_plugin_dirs(xbmc.translatePath(xxx_plugins_path))

download_icon = xbmc.translatePath(
    os.path.join(
        'special://home/addons/script.adultflix.artwork/resources/art/main',
        'downloads.png'))


class MyOpener(URLopener):
    version = 'python-requests/2.9.1'


myopener = MyOpener()
urlretrieve = MyOpener().retrieve
urlopen = MyOpener().open
download_location = kodi.get_setting("download_location")
download_folder = xbmc.translatePath(download_location)

databases = xbmc.translatePath(os.path.join(kodi.datafolder, 'databases'))
downloaddb = xbmc.translatePath(os.path.join(databases, 'downloads.db'))

if not os.path.exists(databases):
    os.makedirs(databases)
conn = sqlite3.connect(downloaddb)
c = conn.cursor()
try:
    c.executescript("CREATE TABLE IF NOT EXISTS downloads (name, url, image);")
except:
    pass
conn.close()
Example #11
0
def download_media(url, path, file_name, translations, progress=None):
    try:
        if progress is None:
            progress = int(kodi.get_setting('down_progress'))

        i18n = translations.i18n
        active = not progress == PROGRESS.OFF
        background = progress == PROGRESS.BACKGROUND

        with kodi.ProgressDialog(kodi.get_name(),
                                 i18n('downloading') % (file_name),
                                 background=background,
                                 active=active) as pd:
            try:
                headers = dict([
                    item.split('=') for item in (url.split('|')[1]).split('&')
                ])
                for key in headers:
                    headers[key] = unquote(headers[key])
            except:
                headers = {}
            if 'User-Agent' not in headers: headers['User-Agent'] = BROWSER_UA
            request = Request(url.split('|')[0], headers=headers)
            response = urlopen(request)
            if 'Content-Length' in response.info():
                content_length = int(response.info()['Content-Length'])
            else:
                content_length = 0

            file_name += '.' + get_extension(url, response)
            full_path = os.path.join(path, file_name)
            logger.log('Downloading: %s -> %s' % (url, full_path),
                       xbmc.LOGDEBUG)

            path = kodi.translate_path(xbmc.makeLegalFilename(path))
            try:
                try:
                    xbmcvfs.mkdirs(path)
                except:
                    os.makedirs(path)
            except Exception as e:
                logger.log('Path Create Failed: %s (%s)' % (e, path),
                           xbmc.LOGDEBUG)

            if not path.endswith(os.sep): path += os.sep
            if not xbmcvfs.exists(path):
                raise Exception(i18n('failed_create_dir'))

            file_desc = xbmcvfs.File(full_path, 'w')
            total_len = 0
            cancel = False
            while True:
                data = response.read(CHUNK_SIZE)
                if not data:
                    break

                if pd.is_canceled():
                    cancel = True
                    break

                total_len += len(data)
                if not file_desc.write(data):
                    raise Exception(i18n('failed_write_file'))

                percent_progress = total_len * 100 / content_length if content_length > 0 else 0
                logger.log(
                    'Position : %s / %s = %s%%' %
                    (total_len, content_length, percent_progress),
                    xbmc.LOGDEBUG)
                pd.update(percent_progress)

            file_desc.close()

        if not cancel:
            kodi.notify(msg=i18n('download_complete') % (file_name),
                        duration=5000)
            logger.log('Download Complete: %s -> %s' % (url, full_path),
                       xbmc.LOGDEBUG)

    except Exception as e:
        logger.log(
            'Error (%s) during download: %s -> %s' % (str(e), url, file_name),
            xbmc.LOGERROR)
        kodi.notify(msg=i18n('download_error') % (str(e), file_name),
                    duration=5000)
def setView(name):
    list_mode = int(kodi.get_setting("list_view"))
    thumb_mode = int(kodi.get_setting("thumb_view"))
    search_mode = int(kodi.get_setting("search_view"))
    picture_mode = int(kodi.get_setting("picture_view"))
    chaturbate_mode = int(kodi.get_setting("chaturbate_view"))

    kodi_name = kodi.kodiVersion()

    if list_mode == 0:
        if kodi_name == "Jarvis":
            list_mode = '50'
        elif kodi_name == "Krypton":
            list_mode = '55'
        else:
            list_mode = '50'

    if thumb_mode == 0:
        if kodi_name == "Jarvis":
            thumb_mode = '500'
        elif kodi_name == "Krypton":
            thumb_mode = '53'
        else:
            thumb_mode = '500'

    if search_mode == 0:
        if kodi_name == "Jarvis":
            search_mode = '500'
        elif kodi_name == "Krypton":
            search_mode = '500'
        else:
            search_mode = '500'

    if picture_mode == 0:
        if kodi_name == "Jarvis":
            picture_mode = '500'
        elif kodi_name == "Krypton":
            picture_mode = '500'
        else:
            picture_mode = '500'

    if chaturbate_mode == 0:
        if kodi_name == "Jarvis":
            chaturbate_mode = '50'
        elif kodi_name == "Krypton":
            chaturbate_mode = '54'
        else:
            chaturbate_mode = '50'

    if name == 'list':
        xbmc.executebuiltin('Container.SetViewMode(%s)' % list_mode)
    elif name == 'thumbs':
        xbmc.executebuiltin('Container.SetViewMode(%s)' % thumb_mode)
    elif name == 'search':
        xbmc.executebuiltin('Container.SetViewMode(%s)' % search_mode)
    elif name == 'pictures':
        xbmc.executebuiltin('Container.SetViewMode(%s)' % picture_mode)
    elif name == 'chaturbate':
        xbmc.executebuiltin('Container.SetViewMode(%s)' % chaturbate_mode)
    else:
        xbmc.executebuiltin('Container.SetViewMode(%s)' % list_mode)
Example #13
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")
Example #14
0
def play(url, name, iconimage=None, ref=None, site=None):
    try:
        kodi.busy()

        if not site:
            if 'site=' in url:
                url, site = url.split('site=')
            else:
                site = 'Unknown'
        if not name: name = 'Unknown'
        if not iconimage: iconimage = kodi.addonicon
        name = re.sub(r'(\[.+?\])', '', name)
        name = name.lstrip()
        if '] - ' in name: name = name.split('] - ')[-1]

        chatur = False

        if ref:
            if 'chaturbate.com' in ref:
                chatur = True
        else:
            ref = ''
        if 'chaturbate.com' in url:
            chatur = True
            ref = url
            url = adultresolver.resolve(url)
        if (isinstance(url, list)):
            try:
                url = multilinkselector(url)
            except:
                pass

        history_on_off = kodi.get_setting("history_setting")
        if history_on_off == "true":
            web_checks = ['http:', 'https:', 'rtmp:']
            locak_checks = ['.mp4']
            try:
                if any(f for f in web_checks if f in url):
                    site = site.title()
                elif any(f for f in locak_checks if f in url):
                    site = 'Local File'
                else:
                    site = 'Unknown'
            except:
                site = site.title()

            # if chatur:
            history.delEntry(ref)
            history.addHistory(name, ref, site.title(), iconimage)
            # else:
            #    history.delEntry(url)
            #    history.addHistory(name, url, site.title(), iconimage)

        kodi.idle()

        if 'chaturbate.com' in ref:
            if kodi.get_setting("mobile_mode") == 'true':
                url = url.replace('_fast_aac', '_aac')
            else:
                bandwidth = kodi.get_setting("chaturbate_band")
                if bandwidth == '0':
                    url = url.replace('_fast_aac', '_aac')
                elif bandwidth == '2':
                    choice = kodi.dialog.select("[COLOR white][B]" + name + "[/B][/COLOR]", ['[COLOR white]Play High Bandwidth Stream[/COLOR]', '[COLOR white]Play Low Bandwidth Stream[/COLOR]'])
                    if choice == 1:
                        url = url.replace('_fast_aac', '_aac')
                    elif choice == 0:
                        pass
                    else:
                        quit()

            liz = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
            xbmc.executebuiltin("Dialog.Close(busydialog)")
            xbmc.Player().play(url, liz, False)

            if kodi.get_setting("chaturbate_subject") == "true":
                sleeper = kodi.get_setting("chaturbate_subject_refresh")
                i = 0

                while not xbmc.Player().isPlayingVideo():
                    time.sleep(1)
                    i += 1
                    if i == 30: quit()
                while xbmc.Player().isPlayingVideo():
                    try:
                        r = client.request(ref)
                        subject = re.compile('default_subject:\s\"([^,]+)",').findall(r)[0]
                        subject = unquote_plus(subject)
                        kodi.notify(msg=subject, duration=8500, sound=True, icon_path=iconimage)
                    except:
                        pass
                    time.sleep(int(sleeper))
        else:
            liz = xbmcgui.ListItem(name, iconImage=iconimage, thumbnailImage=iconimage)
            xbmc.Player().play(url, liz, False)
    except:
        kodi.idle()
        kodi.notify(msg='Error playing %s' % name)
def mainSearch(url):
    if '|SPLIT|' in url: url, site = url.split('|SPLIT|')
    term = url
    if term == "null":  term = kodi.get_keyboard('Search %s' % kodi.get_name())

    if term:
        search_on_off = kodi.get_setting("search_setting")
        if search_on_off == "true":
            delTerm(term)
            addTerm(term)

        display_term = term
        term = quote_plus(term)
        term = term.lower()

        if site == 'all':
            sources = __all__
            search_sources = []
            for i in sources:
                try:
                    if eval(i + ".search_tag") == 1: search_sources.append(i)
                except:
                    pass

            if search_sources:
                i = 0
                source_num = 0
                failed_list = ''
                line1 = kodi.giveColor('Searching: ', 'white') + kodi.giveColor('%s', 'dodgerblue')
                line2 = kodi.giveColor('Found: %s videos', 'white')
                line3 = kodi.giveColor('Source: %s of ' + str(len(search_sources)), 'white')

                kodi.dp.create(kodi.get_name(), '', line2, '')
                xbmc.executebuiltin('Dialog.Close(busydialog)')
                for u in sorted(search_sources):
                    if kodi.dp.iscanceled(): break
                    try:
                        i += 1
                        progress = 100 * int(i) / len(search_sources)
                        kodi.dp.update(progress, line1 % u.title(), line2 % str(source_num), line3 % str(i))
                        search_url = eval(u + ".search_base") % term
                        try:
                            source_n = eval(u + ".content('%s',True)" % search_url)
                        except:
                            source_n = 0
                        try:
                            source_n = int(source_n)
                        except:
                            source_n = 0
                        if not source_n:
                            if failed_list == '':
                                failed_list += str(u).title()
                            else:
                                failed_list += ', %s' % str(u).title()
                        else:
                            source_num += int(source_n)
                    except:
                        pass
                kodi.dp.close()
                if failed_list != '':
                    kodi.notify(msg='%s failed to return results.' % failed_list, duration=4000, sound=True)
                    log_utils.log('Scrapers failing to return search results are :: : %s' % failed_list,
                                  xbmc.LOGERROR)
                else:
                    kodi.notify(msg='%s results found.' % str(source_num), duration=4000, sound=True)
                xbmcplugin.setContent(kodi.syshandle, 'movies')
                xbmcplugin.endOfDirectory(kodi.syshandle, cacheToDisc=True)
                local_utils.setView('search')
        else:
            search_url = eval(site + ".search_base") % term
            eval(site + ".content('%s')" % search_url)
    else:
        kodi.notify(msg='Blank searches are not allowed.')
        quit()
Example #16
0
from kodi_six import xbmcaddon, xbmc, xbmcvfs
from six import moves

pickle = moves.cPickle

try:
    from sqlite3 import dbapi2 as db, OperationalError
except ImportError:
    from pysqlite2 import dbapi2 as db, OperationalError

logger = log_utils.Logger.get_logger(__name__)
logger.disable()
addonInfo = xbmcaddon.Addon().getAddonInfo
cache_path = kodi.translate_path(os.path.join(kodi.get_profile(), 'cache'))
cache_enabled = kodi.get_setting('use_cache') == 'true'

try:
    if not os.path.exists(cache_path):
        os.makedirs(cache_path)
except Exception as e:
    logger.log('Failed to create cache: %s: %s' % (cache_path, e),
               xbmc.LOGWARNING)


def reset_cache():
    try:
        shutil.rmtree(cache_path)
        return True
    except Exception as e:
        logger.log('Failed to Reset Cache: %s' % (e), xbmc.LOGWARNING)
    def generic(self, url, pattern=None):

        try:
            r = client.request(url)
            if pattern:
                s = re.findall(r'%s' % pattern, r)
            else:
                patterns = [
                    r'''\s*=\s*[\'\"](http.+?)[\'\"]''',
                    r'''\s*=\s*['"](http.+?)['"]''',
                    r'''['"][0-9_'"]+:\s[\'\"]([^'"]+)''',
                    r'''\(\w+\([\'\"]([^\'\"]*)''',
                    r'''[\'\"]\w+[\'\"]:['"]([^'"]*)''',
                    r'''\s*=\s*[\'\"](http.+?)[\'\"]''',
                    r'''\s*:\s*[\'\"](//.+?)[\'\"]''',
                    r'''\:[\'\"](\.+?)[\'\"]''',
                    r'''\s*\(\s*[\'\"](http.+?)[\'\"]''',
                    r'''\s*=\s*[\'\"](//.+?)[\'\"]''',
                    r'''\w*:\s*[\'\"](http.+?)[\'\"]''',
                    r'''\w*=[\'\"]([^\'\"]*)''',
                    r'''\w*\s*=\s*[\'\"]([^\'\"]*)''',
                    r'''(?s)<file>([^<]*)''',
                ]

                s = []
                for pattern in patterns:
                    l = re.findall(pattern, r)
                    s += [
                        i for i in l if urlparse(i).path.strip('/').split('/')
                        [-1].split('.')[-1] in ['mp4', 'flv', 'm3u8']
                    ]

                if s:
                    s = [
                        i for i in s if (urlparse(i).path).strip('/').split(
                            '/')[-1].split('.')[-1] in ['mp4', 'flv', 'm3u8']
                    ]
                else:
                    s = client.parseDOM(r,
                                        'source',
                                        ret='src',
                                        attrs={'type': 'video.+?'})

                if not s:
                    raise Exception

                s = ['http:' + i if i.startswith('//') else i for i in s]
                s = [
                    urljoin(url, i) if not i.startswith('http') else i
                    for i in s
                ]
                s = [x for y, x in enumerate(s) if x not in s[:y]]

            self.u = []

            def request(i):
                try:
                    i = i.replace(' ', '%20')
                    c = client.request(i, output='headers', referer=url)
                    checks = ['video', 'mpegurl', 'html']
                    if any(f for f in checks if f in c['Content-Type']):
                        self.u.append((i, int(c['Content-Length'])))
                except:
                    pass

            threads = []
            for i in s:
                threads.append(workers.Thread(request, i))
            [i.start() for i in threads]
            [i.join() for i in threads]

            u = sorted(self.u, key=lambda x: x[1])[::-1]

            mobile_mode = kodi.get_setting('mobile_mode')
            if mobile_mode == 'true':
                u = client.request(u[-1][0], output='geturl', referer=url)
            else:
                u = client.request(u[0][0], output='geturl', referer=url)
            log_utils.log('Returning %s from AdultFlix Resolver' % str(u),
                          xbmc.LOGNOTICE)
            return u
        except Exception as e:
            log_utils.log('Error resolving %s :: Error: %s' % (url, str(e)),
                          xbmc.LOGERROR)