def text_box(text):

    if control.setting('text.box') == 'true':

        window = TextDisplay(control.name(), text=text)
        window.doModal()
        del window

    else:

        control.dialog.textviewer(control.name(), text=text)
Exemplo n.º 2
0
        def seq():

            string_start = '<keymap><slideshow><mouse>'
            string_end = '</mouse></slideshow></keymap>'
            string_for_left = '<leftclick>NextPicture</leftclick>'
            string_for_right = '<rightclick>PreviousPicture</rightclick>'
            string_for_middle = '<middleclick>Rotate</middleclick>'
            string_for_up = '<wheelup>ZoomIn</wheelup>'
            string_for_down = '<wheeldown>ZoomOut</wheeldown>'

            classes = [
                string_for_left, string_for_right, string_for_middle,
                string_for_up, string_for_down
            ]

            map_left = control.lang(30241)
            map_right = control.lang(30242)
            map_middle = control.lang(30243)
            map_up = control.lang(30244)
            map_down = control.lang(30245)

            keys = [
                map_left, map_right, map_middle, map_up, map_down
            ]

            control.okDialog(control.name(), control.lang(30240))

            indices = control.dialog.multiselect(control.name(), keys)

            if not indices:

                control.infoDialog(control.lang(30246))

            else:

                finalized = []

                for i in indices:
                    finalized.append(classes[i])

                joined = ''.join(finalized)

                to_write = string_start + joined + string_end

                try:
                    with open(location, mode='w', encoding='utf-8') as f:
                        f.write(to_write)
                except Exception:
                    with open(location, 'w') as f:
                        f.write(to_write)

                control.execute('Action(reloadkeymaps)')
Exemplo n.º 3
0
def lang_choice():

    selections = [
        control.lang(30217),
        control.lang(30218),
        control.lang(30312),
        control.lang(30327)
    ]

    dialog = control.selectDialog(selections)

    if dialog == 0:
        control.execute('Addon.Default.Set(kodi.resource.language)')
    elif dialog == 1:
        languages = [control.lang(30286), control.lang(30299)]
        layouts = ['English QWERTY', 'Greek QWERTY']
        indices = control.dialog.multiselect(control.name(), languages)
        control.set_gui_setting('locale.keyboardlayouts',
                                [layouts[i] for i in indices])
    elif dialog == 2:
        control.set_gui_setting('locale.charset', 'CP1253')
        control.set_gui_setting('subtitles.charset', 'CP1253')
    elif dialog == 3:
        control.execute('ActivateWindow(interfacesettings)')
    else:
        control.execute('Dialog.Close(all)')
def view_text(text, title=None):

    try:

        data = json.loads(text)

    except (TypeError, ValueError):

        data = None

    if isinstance(data, dict):

        public = data['public_description']
        full = data['description']
        title = data['title']

        text = public + '\n' * 4 + full

    if not title:

        title = control.name()

    if control.setting('text.box') == 'true':

        window = TextDisplay(title, text=text)
        window.doModal()
        del window

    else:

        control.dialog.textviewer(title, text=text)
Exemplo n.º 5
0
def presentation():

    path = control.transPath(
        'special://profile/addon_data/{0}/slideshow/'.format(
            control.addonInfo('id')))

    if not control.exists(control.join(path, '01.jpg')):

        control.makeFiles(path)

        control.idle()

        dp = control.ProgressDialog(heading=control.name())

        for i in range(1, 25):
            dp.update((i + 1) * 4, line1=control.lang(30038))
            client.retriever(
                'http://mediaportal.anacon.org/faros/{0}.jpg'.format(
                    str(i) if len(str(i)) >= 2 else str('0' + str(i))),
                control.join(
                    path, (str(i) if len(str(i)) >= 2 else str('0' + str(i))) +
                    '.jpg'))

        control.execute('Dialog.Close(progressdialog)')

    control.execute('SlideShow({0},pause)'.format(path))
Exemplo n.º 6
0
def user_agent():

    UA = '{0}, {1}: {2}:v{3} (by /u/TwilightZer0)'.format(
        platform.version(), platform.release(), control.name(),
        control.version())

    return UA
Exemplo n.º 7
0
def manual_auth(tell=True):

    if tell:
        control.okDialog(control.name(),
                         control.lang(30146).format(short_link))

    if control.setting('ip.address') == '0.0.0.0':
        ip_address_set()

    auth_token = control.dialog.input(heading=control.lang(30082))

    if not auth_token:
        control.okDialog(control.name(), control.lang(30083))
        return
    else:
        control.setSetting('auth.token', auth_token)
        get_tokens(code=auth_token)
def authorize():

    control.setSetting('get.toggle', 'true')

    choices = [
        control.lang(30063),
        control.lang(30080),
        control.lang(30149),
        control.lang(30081)
    ]

    choice = control.selectDialog(choices, control.lang(30061))

    if choice == 0:

        control.open_web_browser(authorization_link())
        reddit_server()

    elif choice == 1:

        window = QR_display(control.name())

        window.doModal()

        del window

    elif choice == 2:

        kodi_auth()

    elif choice == 3:

        control.okDialog(control.name(),
                         control.lang(30146).format(QR_display.link))

        if control.setting('ip.address') == '0.0.0.0':
            ip_address_set()

        auth_token = control.dialog.input(heading=control.lang(30082))

        if not auth_token:
            control.okDialog(control.name(), control.lang(30083))
            return
        else:
            control.setSetting('auth.token', auth_token)
            get_tokens(code=auth_token)
Exemplo n.º 9
0
def stream_picker(qualities, urls):

    choice = control.selectDialog(heading=control.name(), list=qualities)

    if choice <= len(qualities) and not choice == -1:

        popped = urls[choice]

        return popped
Exemplo n.º 10
0
def check_stream(stream_list,
                 shuffle_list=False,
                 start_from=0,
                 show_pd=False,
                 cycle_list=True):

    if not stream_list:
        return

    if shuffle_list:
        shuffle(stream_list)

    for (c, (h, stream)) in list(enumerate(stream_list[start_from:])):

        if stream.endswith('blank.mp4'):
            return stream

        if show_pd:
            pd = control.progressDialog
            pd.create(control.name(),
                      ''.join([control.lang(30459),
                               h.partition(': ')[2]]))

        try:
            resolved = conditionals(stream)
        except Exception:
            resolved = None

        if resolved is not None:
            if show_pd:
                pd.close()
            return resolved
        elif show_pd and pd.iscanceled():
            return
        elif c == len(stream_list[start_from:]) and not resolved:
            control.infoDialog(control.lang(30411))
            if show_pd:
                pd.close()
        elif resolved is None:
            if cycle_list:
                log_debug('Removing unplayable stream: {0}'.format(stream))
                stream_list.remove((h, stream))
                return check_stream(stream_list)
            else:
                if show_pd:
                    _percent = percent(c, len(stream_list[start_from:]))
                    pd.update(
                        _percent,
                        ''.join([control.lang(30459),
                                 h.partition(': ')[2]]))
                control.sleep(1000)
                continue
Exemplo n.º 11
0
def reddit_page(authorized=False, token=''):

    auth_page = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>{name}</title>
    </head>
    <body>
        <div style="text-align: center;">
            <h1>{name}, {version}</h1>
            {line1}!<br>
            {token}<br>
            {line2}
        </div>
    </body>
</html>
    """

    if authorized:
        html = auth_page.format(
            name=control.name(),
            version=control.lang(30070).format(
                control.version()).encode('utf-8'),
            token=control.lang(30069).format(token).encode('utf-8'),
            line1=control.lang(30402).encode('utf-8'),
            line2=control.lang(30065).encode('utf-8'))
    else:
        html = auth_page.format(name=control.name(),
                                version=control.lang(30070).format(
                                    control.version()).encode('utf-8'),
                                token='',
                                line1=control.lang(30067).encode('utf-8'),
                                line2=control.lang(30068).encode('utf-8'))

    return html
def add_to_history(file_=history_file):

    if not control.exists(file_):
        control.makeFiles(control.dataPath)

    txt = control.dialog.input(control.name())

    if not txt:
        return

    if txt not in read_from_history():

        with open(file_, 'a') as f:
            f.writelines(txt + '\n')

        trim_history(file_)
        refresh()
Exemplo n.º 13
0
def add(items,
        cacheToDisc=True,
        content=None,
        mediatype=None,
        infotype='video',
        argv=None,
        as_playlist=False,
        pd_heading=None,
        pd_message='',
        clear_first=True,
        progress=False,
        category=None):

    if argv is None:

        from tulip.init import sysaddon, syshandle

    else:

        sysaddon = argv[0]
        syshandle = int(argv[1])

    if items is None or len(items) == 0:
        return

    # sysicon = control.join(control.addonInfo('path'), 'resources', 'media')
    sysimage = control.addonInfo('icon')
    sysfanart = control.addonInfo('fanart')

    if progress:

        pd = control.progressDialogGB
        pd.create(heading=control.name() if not pd_heading else pd_heading,
                  message=pd_message)

    else:

        pd = None

    if as_playlist and clear_first:

        control.playlist(1 if infotype == 'video' else 0).clear()

    meta_tags = [
        'count', 'size', 'date', 'genre', 'country', 'year', 'episode',
        'season', 'sortepisode', 'sortseason', 'episodeguide', 'showlink',
        'top250', 'setid', 'tracknumber', 'rating', 'userrating', 'watched',
        'playcount', 'overlay', 'cast', 'castandrole', 'director', 'mpaa',
        'plot', 'plotoutline', 'title', 'originaltitle', 'sorttitle',
        'duration', 'studio', 'tagline', 'writer', 'tvshowtitle', 'premiered',
        'status', 'set', 'gameclient', 'setoverview', 'tag', 'imdbnumber',
        'code', 'aired', 'credits', 'lastplayed', 'album', 'artist', 'votes',
        'path', 'trailer', 'dateadded', 'mediatype', 'dbid', 'tracknumber',
        'discnumber', 'lyrics', 'listeners', 'musicbrainztrackid', 'comment',
        'picturepath', 'platform', 'genres', 'publisher', 'developer',
        'overview'
    ]

    for c, i in list(enumerate(items)):

        try:

            if progress:

                p = control.per_cent(c, len(items))
                pd.update(p)

            try:
                label = control.lang(i['title']).encode('utf-8')
            except Exception:
                label = i['title']

            if 'label' in i and not i['label'] == '0':
                label = i['label']

            if 'image' in i and not i['image'] == '0':
                image = i['image']
            elif 'poster' in i and not i['poster'] == '0':
                image = i['poster']
            elif 'icon' in i and not i['icon'] == '0':
                image = control.addonmedia(i['icon'])
            else:
                image = sysimage

            if 'banner' in i and not i['banner'] == '0':
                banner = i['banner']
            elif 'fanart' in i and not i['fanart'] == '0':
                banner = i['fanart']
            else:
                banner = image

            fanart = i['fanart'] if 'fanart' in i and not i[
                'fanart'] == '0' else sysfanart

            isFolder = False if 'isFolder' in i and not i[
                'isFolder'] == '0' else True

            try:
                is_play_boolean = i.get('isPlayable') in [
                    'True', 'true', '1', 'yes', 'Yes'
                ]
            except Exception:
                is_play_boolean = False

            isPlayable = True if not isFolder and 'isPlayable' not in i else is_play_boolean

            if isPlayable:

                isFolder = False

            try:
                action = '{0}?action={1}'.format(sysaddon, i['action'])
            except KeyError:
                return

            try:
                url = 'url={0}'.format(quote_plus(i['url']))
            except Exception:
                url = None

            try:
                title = 'title={0}'.format(quote_plus(i['title']))
            except KeyError:
                try:
                    title = 'title={0}'.format(
                        quote_plus(i['title'].encode('utf-8')))
                except KeyError:
                    title = None
            except Exception:
                title = None

            try:
                icon = 'image={0}'.format(quote_plus(i['image']))
            except KeyError:
                try:
                    icon = 'image={0}'.format(
                        quote_plus(i['image'].encode('utf-8')))
                except KeyError:
                    icon = None
            except Exception:
                icon = None
            try:
                name = 'name={0}'.format(quote_plus(i['name']))
            except KeyError:
                try:
                    name = 'name={0}'.format(
                        quote_plus(i['name'].encode('utf-8')))
                except KeyError:
                    name = None
            except Exception:
                name = None
            try:
                year = 'year={0}'.format(quote_plus(i['year']))
            except Exception:
                year = None
            try:
                plot = 'plot={0}'.format(quote_plus(i['plot']))
            except KeyError:
                try:
                    plot = 'plot={0}'.format(
                        quote_plus(i['plot'].encode('utf-8')))
                except KeyError:
                    plot = None
            except Exception:
                plot = None
            try:
                genre = 'genre={0}'.format(quote_plus(i['genre']))
            except KeyError:
                try:
                    genre = 'genre={0}'.format(
                        quote_plus(i['genre'].encode('utf-8')))
                except KeyError:
                    genre = None
            except Exception:
                genre = None
            try:
                dash = 'dash={0}'.format(quote_plus(i['dash']))
            except Exception:
                dash = None
            try:
                query = 'query={0}'.format(quote_plus(i['query']))
            except Exception:
                query = None

            parts = [
                foo for foo in [
                    action, url, title, icon, name, year, plot, genre, dash,
                    query
                ] if foo
            ]

            uri = '&'.join(parts)

            cm = []
            menus = i['cm'] if 'cm' in i else []

            for menu in menus:

                try:

                    try:
                        tmenu = control.lang(menu['title']).encode('utf-8')
                    except Exception:
                        tmenu = menu['title']
                    try:
                        qmenu = urlencode(menu['query'])
                    except Exception:
                        qmenu = urlencode(
                            dict((k, v.encode('utf-8'))
                                 for k, v in menu['query'].items()))
                    cm.append(
                        (tmenu, 'RunPlugin({0}?{1})'.format(sysaddon, qmenu)))

                except Exception:

                    pass

            meta = dict((k, v) for k, v in iteritems(i)
                        if k in meta_tags and (not v == '0' or v is None))

            if mediatype is not None:
                meta['mediatype'] = mediatype

            item = control.item(label=label)

            item.setArt({
                'icon': image,
                'thumb': image,
                'poster': image,
                'tvshow.poster': image,
                'season.poster': image,
                'banner': banner,
                'tvshow.banner': banner,
                'season.banner': banner,
                'fanart': fanart
            })

            item.addContextMenuItems(cm)
            item.setInfo(
                type=infotype if 'infotype' not in i else i['infotype'],
                infoLabels=meta)

            if isPlayable:

                if not i['action'] == 'pvr_client':
                    item.setProperty('IsPlayable', 'true')
                else:
                    item.setProperty('IsPlayable', 'false')

                if not i['action'] == 'pvr_client':
                    if 'streaminfo' not in i and infotype == 'video':
                        item.addStreamInfo(infotype, {'codec': 'h264'})
                    else:
                        item.addStreamInfo(infotype, i.get('streaminfo'))

            if as_playlist and isPlayable:
                control.playlist(1 if infotype == 'video' else 0).add(
                    url=uri, listitem=item, index=c)
            else:
                control.addItem(handle=syshandle,
                                url=uri,
                                listitem=item,
                                isFolder=isFolder,
                                totalItems=len(items))

        except Exception as reason:
            log('Directory not added, reason of failure: ' + repr(reason))

    if progress:
        pd.update(100)
        pd.close()

    if as_playlist:

        control.openPlaylist(1 if infotype == 'video' else 0)

        return

    try:

        i = items[0]
        if i['next'] == '':
            raise Exception()

        url = '{0}?action={1}&url={2}'.format(sysaddon, i['nextaction'],
                                              quote_plus(i['next']))
        icon = i['nexticon'] if 'nexticon' in i else control.addonmedia(
            'next.png')
        fanart = i['nextfanart'] if 'nextfanart' in i else sysfanart

        try:
            label = control.lang(i['nextlabel']).encode('utf-8')
        except Exception:
            label = 'Next'

        item = control.item(label=label)

        item.setArt({
            'icon': icon,
            'thumb': icon,
            'poster': icon,
            'tvshow.poster': icon,
            'season.poster': icon,
            'banner': icon,
            'tvshow.banner': icon,
            'season.banner': icon,
            'fanart': fanart
        })

        control.addItem(handle=syshandle,
                        url=url,
                        listitem=item,
                        isFolder=True,
                        totalItems=len(items))

    except Exception:

        pass

    if content is not None:
        control.content(syshandle, content)

    if category is not None:
        control.setcategory(syshandle, category)

    control.directory(syshandle, cacheToDisc=cacheToDisc)
Exemplo n.º 14
0
def url_generator(query='',
                  media=True,
                  advanced=False,
                  history=False,
                  domain=False):

    search_link = base_link(
    ) + '/search{0}?q={1}' if not domain else base_link() + '/domain/{0}/{1}'
    sr_search_link = base_link() + '/subreddits/search{0}?q={1}'
    subreddit = 'subreddit:'  # find submissions in "subreddit"
    author = 'author:'  # find submissions by "username"

    site = 'site:'  # find submissions from "example.com"
    url = 'url:'  # search for "text" in url
    selftext = 'selftext:'  # search for "text" in self post contents
    self_search = 'self:{0}'  # Set to yes for text submissions, no otherwise. 1 and 0 are also supported.
    flair = 'flair:""'

    items_limit = '&limit=' + control.setting('items.limit')  # numbered string
    if domain:
        items_limit = items_limit.replace('&', '?')

    if control.setting('include.nsfw') == 'true' and control.setting(
            'access.token') and control.setting(
                'nsfw.toggle'
            ) == 'true':  # include (or exclude) results marked as NSFW
        nsfw = 'nsfw:1'
    else:
        nsfw = ''

    nsfw_query = ' ' + nsfw if nsfw else ''

    # Operators used by reddit:
    # OR = 'OR'
    # NOT = 'NOT'
    # AND = 'AND'

    if not media:

        if not query:

            query = control.dialog.input(control.name(), nsfw_query)

            if not query:
                return

        if control.setting('history.bool') == 'true' and not history:
            add_to_history(query, history_subrs)

        output = sr_search_link.format(dotjson,
                                       quote_plus(query) + items_limit)

        return output

    else:

        if advanced:

            choices = [
                control.lang(30014),
                control.lang(30019),
                control.lang(30020),
                control.lang(30022),
                control.lang(30052),
                control.lang(30119),
                control.lang(30053),
                control.lang(30054 if control.setting('add.hosts') ==
                             'true' else 30021)
            ]

            generate = [
                nsfw, subreddit, author, url,
                self_search.format('no'), flair, selftext, site
            ]

            if control.setting('include.nsfw') == 'false':
                del choices[0]
                del generate[0]

            indices = control.dialog.multiselect(control.lang(30018), choices)

            if not indices or indices == [-1]:

                return

            else:

                generated = [generate[i] for i in indices]

                joined = ' '.join(generated)

                if control.setting('add.hosts') == 'true':
                    joined = joined.replace('site:', '')

                q = control.dialog.input(control.name(), ' ' + joined)

                if not q or q == ' ':
                    return

                if control.setting('add.hosts') == 'true' and 7 in indices:
                    q += ' ' + site + available_domains()

                output = search_link.format(dotjson,
                                            quote_plus(q) + items_limit)

                if control.setting('history.bool') == 'true':
                    add_to_history(q, history_media)

                return output

        else:

            if not query:

                query = control.dialog.input(control.name())

                if not query:
                    return

            if not domain:

                if 'self:yes' in query or 'self:1' in query:
                    self = self_search.format('yes')
                else:
                    self = self_search.format('no')

                if control.setting('add.hosts') == 'true':
                    query += ' ' + self + nsfw_query + ' ' + site + available_domains(
                    )
                else:
                    query += ' ' + self + nsfw_query

                if control.setting('history.bool') == 'true' and not history:
                    add_to_history(query, history_media)

                output = search_link.format(dotjson,
                                            quote_plus(query) + items_limit)

                return output

            else:

                output = search_link.format(query + items_limit)

                return output
Exemplo n.º 15
0
def kodi_auth():

    aspect_ratio = control.infoLabel('Skin.AspectRatio')

    def obtain_authorization(_cookie, _uh):

        data = {
            'authorize': 'Allow',
            'state': state,
            'redirect_uri': redirect_uri,
            'response_type': 'code',
            'client_id': client_id,
            'duration': 'permanent',
            'scope': ' '.join(scope),
            'uh': _uh
        }

        headers = client.request(api_link('authorize'),
                                 cookie=_cookie,
                                 post=data,
                                 redirect=False,
                                 output='headers')

        geturl = dict([
            line.partition(': ')[::2] for line in str(headers).splitlines()
        ]).get('location')

        token = dict(parse_qsl(urlparse(geturl).query)).get('code')

        if not token:

            return

        get_tokens(code=token)

    class Prompt(pyxbmct.AddonDialogWindow):

        pyxbmct.skin.estuary = control.setting('pyxbmct.estuary') == 'true'

        if aspect_ratio == '4:3':
            geometry = (506, 380, 5, 5)
        else:
            geometry = (676, 380, 5, 5)

        def __init__(self, title, description, _cookie, _uh):

            super(Prompt, self).__init__(title)
            self.allow_button = None
            self.deny_button = None
            self.text_box = None
            self.text = description
            self.cookie = _cookie
            self.uh = _uh
            self.setGeometry(*self.geometry)
            self.set_controls()
            self.set_navigation()
            self.connect(pyxbmct.ACTION_NAV_BACK, self.close)

        def set_controls(self):

            # Text box
            self.text_box = pyxbmct.TextBox()
            self.placeControl(self.text_box, 0, 0, 4, 5)
            self.text_box.setText(self.text)
            self.text_box.autoScroll(1000, 1000, 1000)
            # Allow
            self.allow_button = pyxbmct.Button(control.lang(30150))
            self.placeControl(self.allow_button, 4, 1)
            self.connect(self.allow_button, lambda: self.authorize())
            # Deny
            self.deny_button = pyxbmct.Button(control.lang(30151))
            self.placeControl(self.deny_button, 4, 3)
            self.connect(self.deny_button, self.close)

        def set_navigation(self):

            self.allow_button.controlRight(self.deny_button)
            self.deny_button.controlLeft(self.allow_button)
            self.setFocus(self.allow_button)

        def authorize(self):

            obtain_authorization(self.cookie, self.uh)
            self.close()

    class UserPass(pyxbmct.AddonDialogWindow):

        pyxbmct.skin.estuary = control.setting('pyxbmct.estuary') == 'true'

        if aspect_ratio == '4:3':
            geometry = (341, 296, 6, 1)
        else:
            geometry = (455, 296, 6, 1)

        def __init__(self, title):

            super(UserPass, self).__init__(title)
            self.username_label = None
            self.user_input = None
            self.password_label = None
            self.pass_input = None
            self.submit_button = None
            self.cancel_button = None
            self.setGeometry(*self.geometry)
            self.set_controls()
            self.set_navigation()
            self.connect(pyxbmct.ACTION_NAV_BACK, self.close)

        def set_controls(self):

            # Username label
            self.username_label = pyxbmct.Label(control.lang(30152))
            self.placeControl(self.username_label, 0, 0)
            # Username input
            self.user_input = pyxbmct.Edit(control.lang(30152))
            self.placeControl(self.user_input, 1, 0)
            # Password label
            self.password_label = pyxbmct.Label(control.lang(30153))
            self.placeControl(self.password_label, 2, 0)
            # Password input
            self.pass_input = pyxbmct.Edit(control.lang(30153),
                                           isPassword=True)
            self.placeControl(self.pass_input, 3, 0)
            # Submit button
            self.submit_button = pyxbmct.Button(control.lang(30154))
            self.placeControl(self.submit_button, 4, 0)
            self.connect(self.submit_button, lambda: self.submit(True))
            # Cancel button
            self.cancel_button = pyxbmct.Button(control.lang(30064))
            self.placeControl(self.cancel_button, 5, 0)
            self.connect(self.cancel_button, self.close)

        def set_navigation(self):

            self.user_input.controlDown(self.pass_input)
            self.pass_input.controlUp(self.user_input)
            self.pass_input.controlDown(self.submit_button)
            self.submit_button.controlUp(self.pass_input)
            self.submit_button.controlDown(self.cancel_button)
            self.cancel_button.controlUp(self.submit_button)
            self.setFocus(self.user_input)

        def credentials(self):

            return self.user_input.getText(), self.pass_input.getText()

        def submit(self, _submitted=False):

            if _submitted:

                self.close()

                return True

    userpass_window = UserPass(control.name())
    userpass_window.doModal()

    username, password = userpass_window.credentials()

    if not username or not password:

        return

    login_url = base_link(True) + '/api/login/' + username

    data = {
        'form_is_compact': 'true',
        'dest': authorization_link(True),
        'passwd': password,
        'user': username,
        'rem': 'on',
        'api_type': 'json',
        'op': 'login'
    }

    del userpass_window

    cookie = client.request(login_url, close=False, post=data, output='cookie')

    html = client.request(authorization_link(True), cookie=cookie)

    try:

        uh = client.parseDOM(html, 'input', attrs={'name': 'uh'},
                             ret='value')[0]

        permissions = client.parseDOM(html,
                                      'div',
                                      attrs={'class': 'access-permissions'})[0]
        notice = client.parseDOM(html, 'p', attrs={'class': 'notice'})[0]

        text = client.replaceHTMLCodes(
            client.stripTags(permissions + '[CR]' + notice))

        text = substitute(r'([.:]) ?', r'\1[CR]', text).partition('[CR]')

        prompt_window = Prompt(title=text[0],
                               description=text[2],
                               _cookie=cookie,
                               _uh=uh)
        prompt_window.doModal()

        del prompt_window

    except IndexError:

        control.okDialog(control.name(), control.lang(30114))
Exemplo n.º 16
0
def setup_various_keymaps(keymap):

    keymap_settings_folder = control.transPath('special://profile/keymaps')

    if not path.exists(keymap_settings_folder):
        control.makeFile(keymap_settings_folder)

    if keymap == 'previous':

        location = control.join(keymap_settings_folder, 'alivegr_tvguide.xml')

        lang_int = 30025

        def seq():

            previous_keymap = """<keymap>
    <tvguide>
        <keyboard>
            <key id="61448">previousmenu</key>
        </keyboard>
    </tvguide>
    <tvchannels>
        <keyboard>
            <key id="61448">previousmenu</key>
        </keyboard>
    </tvchannels>
</keymap>
"""

            with open(location, 'w') as f:
                f.write(previous_keymap)

    elif keymap == 'mouse':

        location = control.transPath(control.join('special://profile', 'keymaps', 'alivegr_mouse.xml'))

        lang_int = 30238

        def seq():

            string_start = '<keymap><slideshow><mouse>'
            string_end = '</mouse></slideshow></keymap>'
            string_for_left = '<leftclick>NextPicture</leftclick>'
            string_for_right = '<rightclick>PreviousPicture</rightclick>'
            string_for_middle = '<middleclick>Rotate</middleclick>'
            string_for_up = '<wheelup>ZoomIn</wheelup>'
            string_for_down = '<wheeldown>ZoomOut</wheeldown>'

            classes = [
                string_for_left, string_for_right, string_for_middle,
                string_for_up, string_for_down
            ]

            map_left = control.lang(30241)
            map_right = control.lang(30242)
            map_middle = control.lang(30243)
            map_up = control.lang(30244)
            map_down = control.lang(30245)

            keys = [
                map_left, map_right, map_middle, map_up, map_down
            ]

            control.okDialog(control.name(), control.lang(30240))

            indices = control.dialog.multiselect(control.name(), keys)

            if not indices:

                control.infoDialog(control.lang(30246))

            else:

                finalized = []

                for i in indices:
                    finalized.append(classes[i])

                joined = ''.join(finalized)

                to_write = string_start + joined + string_end

                with open(location, 'w') as f:
                    f.write(to_write)

    elif keymap == 'remote_slideshow':

        location = control.transPath(control.join('special://profile', 'keymaps', 'alivegr_remote_slideshow.xml'))

        lang_int = 30238

        def seq():

            string_start = '<keymap><slideshow><keyboard>'
            ok_button = ''
            long_ok_button = ''
            next_pic = ''
            previous_pic = ''
            context = ''
            string_end = '</keyboard></slideshow></keymap>'

            yes_clicked = control.yesnoDialog(control.lang(30026))

            if yes_clicked:

                to_write = string_start + ok_button + long_ok_button + next_pic + previous_pic + context + string_end

            else:

                to_write = string_start + ok_button + long_ok_button + context + string_end

            with open(location, 'w') as f:
                f.write(to_write)

    yes = control.yesnoDialog(control.lang(lang_int))

    if yes:

        if path.exists(location):

            choices = [control.lang(30248), control.lang(30249)]

            choice = control.selectDialog(choices, heading=control.lang(30247))

            if choice == 0:

                seq()
                control.execute('Action(reloadkeymaps)')
                control.okDialog(control.name(), control.lang(30027) + ', ' + (control.lang(30028)))
                control.infoDialog(control.lang(30402))

            elif choice == 1:

                control.deleteFile(location)
                control.execute('Action(reloadkeymaps)')
                control.infoDialog(control.lang(30402))

            else:

                control.infoDialog(control.lang(30403))

        else:

            seq()
            control.okDialog(control.name(), control.lang(30027) + ', ' + (control.lang(30028)))
            control.infoDialog(control.lang(30402))

    else:

        control.infoDialog(control.lang(30403))
Exemplo n.º 17
0
    def live_tv(self, zapping=False, query=None):

        if control.setting('live_tv_mode') == '1' and query is None:
            zapping = True

        if control.setting('debug') == 'false':
            live_data = cache.get(self.live, 8)
        else:
            live_data = cache.get(self.live,
                                  int(control.setting('cache_period')))

        self.list = live_data[0]

        if self.list is None:
            log_debug('Live channels list did not load successfully')
            return

        if zapping and control.setting('live_group_switcher') != '0':

            value = int(control.setting('live_group_switcher')) - 1

            group = str(live_groups.values()[value])

            self.list = [item for item in self.list if item['group'] == group]

        elif control.setting('show_live_switcher') == 'true':

            if control.setting('live_group') != 'ALL' and query is None:

                self.list = [
                    item for item in self.list
                    if item['group'] == control.setting('live_group')
                ]

        elif not zapping:

            if control.setting('live_group_switcher') != '0' and query is None:

                value = int(control.setting('live_group_switcher')) - 1

                group = str(live_groups.values()[value])

                self.list = [
                    item for item in self.list if item['group'] == group
                ]

        if control.setting('show_alt') == 'false':

            self.list = [
                item for item in self.list if not any([
                    'BUP' in item['title'],
                    re.search(r'\(\d\)', item['title'])
                ])
            ]

        year = datetime.now().year

        for count, item in list(enumerate(self.list, start=1)):

            item.update({
                'action':
                'play_resolved'
                if zapping and control.setting('preresolve_streams') == 'true'
                else 'play',
                'isFolder':
                'False',
                'year':
                year,
                'duration':
                None,
                'code':
                str(count)
            })

        for item in self.list:

            # bookmark = dict((k, v) for k, v in iteritems(item) if not k == 'next')
            # bookmark['bookmark'] = item['url']
            #
            # bookmark_cm = {'title': 30080, 'query': {'action': 'addBookmark', 'url': json.dumps(bookmark)}}
            if not zapping:
                r_and_c_cm = {
                    'title': 30082,
                    'query': {
                        'action': 'refresh_and_clear'
                    }
                }
            else:
                r_and_c_cm = None
            pvr_client_cm = {
                'title': 30084,
                'query': {
                    'action': 'pvr_client',
                    'query': 'true'
                }
            }
            if item['website'] != 'None':
                web_cm = {
                    'title': 30316,
                    'query': {
                        'action': 'open_link',
                        'url': item['website']
                    }
                }
            else:
                web_cm = None

            if control.condVisibility('Pvr.HasTVChannels'):
                item.update({'cm': [r_and_c_cm, pvr_client_cm, web_cm]})
            else:
                item.update({'cm': [r_and_c_cm, web_cm]})

        if control.setting(
                'show_live_switcher') == 'true' and zapping is False:

            switch = {
                'title':
                control.lang(30047).format(
                    control.lang(30048) if control.setting('live_group') ==
                    'ALL' else control.lang(int(control.setting('live_group'))
                                            )),
                'image':
                iconname('switcher'),
                'action':
                'live_switcher',
                'plot':
                control.lang(30034) + '\n' + control.lang(30035) +
                live_data[2],
                'isFolder':
                'False',
                'isPlayable':
                'False'
            }

            self.list.insert(0, switch)

        if control.setting('preresolve_streams') == 'true':

            from resources.lib.modules.player import conditionals

            pd = control.progressDialogGB
            pd.create(control.name())

            for item in self.list:

                try:
                    percent = control.per_cent(int(item['code']),
                                               len(self.list))
                    pd.update(percent)
                    item.update(
                        {'url': conditionals(item['url'], params=self.params)})
                except Exception as e:
                    log_debug('Failed to resolve ' + item['title'] +
                              ' , reason: ' + repr(e))
                    continue

            pd.update(100)
            pd.close()

        if query:

            self.list = [i for i in self.list if query in i['title'].lower()]

            return self.list

        if not zapping:

            control.sortmethods('production_code')
            control.sortmethods('title')
            control.sortmethods('genre')

        directory.add(self.list,
                      content='movies',
                      argv=self.argv,
                      as_playlist=zapping,
                      progress=len(self.list) >= 100)
def readme():

    text = control.addonInfo('disclaimer')

    control.dialog.textviewer(control.name(), text=text)
Exemplo n.º 19
0
def setup_various_keymaps(keymap):

    keymap_settings_folder = control.transPath('special://profile/keymaps')

    if not path.exists(keymap_settings_folder):
        control.makeFile(keymap_settings_folder)

    if keymap == 'previous':

        location = control.join(keymap_settings_folder, 'alivegr_tvguide.xml')

        lang_int = 30022

        def seq():

            previous_keymap = """<keymap>
    <tvguide>
        <keyboard>
            <key id="61448">previousmenu</key>
        </keyboard>
    </tvguide>
    <tvchannels>
        <keyboard>
            <key id="61448">previousmenu</key>
        </keyboard>
    </tvchannels>
</keymap>
"""

            with open(location, 'w') as f:
                f.write(previous_keymap)

    elif keymap == 'mouse':

        location = control.transPath(
            control.join('special://profile', 'keymaps', 'alivegr_mouse.xml'))

        lang_int = 30238

        def seq():

            string_start = '<keymap><slideshow><mouse>'
            string_end = '</mouse></slideshow></keymap>'
            string_for_left = '<leftclick>NextPicture</leftclick>'
            string_for_right = '<rightclick>PreviousPicture</rightclick>'
            string_for_middle = '<middleclick>Rotate</middleclick>'
            string_for_up = '<wheelup>ZoomIn</wheelup>'
            string_for_down = '<wheeldown>ZoomOut</wheeldown>'

            classes = [
                string_for_left, string_for_right, string_for_middle,
                string_for_up, string_for_down
            ]

            map_left = control.lang(30241)
            map_right = control.lang(30242)
            map_middle = control.lang(30243)
            map_up = control.lang(30244)
            map_down = control.lang(30245)

            keys = [map_left, map_right, map_middle, map_up, map_down]

            control.okDialog(control.name(), control.lang(30240))

            indices = control.dialog.multiselect(control.name(), keys)

            if not indices:

                control.infoDialog(control.lang(30246))

            else:

                finalized = []

                for i in indices:
                    finalized.append(classes[i])

                joined = ''.join(finalized)

                to_write = string_start + joined + string_end

                with open(location, 'w') as f:
                    f.write(to_write)

                control.execute('Action(reloadkeymaps)')

    elif keymap == 'samsung':

        string = '''<keymap>
    <global>
        <keyboard>
            <key id="61670">contextmenu</key>
        </keyboard>
    </global>
    <fullscreenvideo>
        <keyboard>
            <key id="61670">osd</key>
        </keyboard>
    </fullscreenvideo>
    <visualisation>
        <keyboard>
            <key id="61670">osd</key>
        </keyboard>
    </visualisation>
</keymap>'''

        location = control.join(keymap_settings_folder, 'samsung.xml')

        lang_int = 30022

        def seq():

            with open(location, 'w') as f:
                f.write(string)

    elif keymap == 'stop_playback':

        string = '''<keymap>
    <fullscreenvideo>
        <keyboard>
            <key id="61448">stop</key>
        </keyboard>
        <keyboard>
            <key id="61448" mod="longpress">back</key>
        </keyboard>
    </fullscreenvideo>
    <visualisation>
        <keyboard>
            <key id="61448">stop</key>
        </keyboard>
        <keyboard>
            <key id="61448" mod="longpress">back</key>
        </keyboard>
    </visualisation>
</keymap>'''

        location = control.join(keymap_settings_folder, 'stop_playback.xml')

        lang_int = 30022

        def seq():

            with open(location, 'w') as f:
                f.write(string)

    yes = control.yesnoDialog(control.lang(lang_int))

    if yes:

        if path.exists(location):

            choices = [control.lang(30248), control.lang(30249)]

            _choice = control.selectDialog(choices,
                                           heading=control.lang(30247))

            if _choice == 0:

                seq()
                control.okDialog(
                    control.name(),
                    control.lang(30027) + ', ' + (control.lang(30028)))
                control.infoDialog(control.lang(30402))
                control.execute('Action(reloadkeymaps)')

            elif _choice == 1:

                control.deleteFile(location)
                control.infoDialog(control.lang(30402))
                control.execute('Action(reloadkeymaps)')

            else:

                control.infoDialog(control.lang(30403))

        else:

            seq()
            control.okDialog(
                control.name(),
                control.lang(30027) + ', ' + (control.lang(30028)))
            control.infoDialog(control.lang(30402))

            control.execute('Action(reloadkeymaps)')

    else:

        control.infoDialog(control.lang(30403))
    def search(self, media=True, override=False, query=None):

        if media:
            choices = [
                control.lang(30003),
                control.lang(30005),
                control.lang(30155),
                control.lang(30010)
            ]
        else:
            choices = [
                control.lang(30003),
                control.lang(30005),
                control.lang(30010)
            ]

        if control.setting('history.bool') == 'false':
            del choices[-1]

        if control.setting('window.action') == '0' or override:

            if media:

                if not override:
                    choice = control.selectDialog(choices)
                else:
                    choice = None

                if choice == 0 or query == 'quick':

                    search_link = url_generator()

                elif choice == 1 or query == 'advanced':

                    search_link = url_generator(advanced=True)

                elif choice == 2 or query == 'domain':

                    q = control.dialog.input(control.name())

                    search_link = url_generator(query=q)

                elif choice == 3 or query == 'history':

                    if not read_from_history(history_media):
                        return

                    queries = read_from_history(history_media)

                    if control.setting('window.action') == '0':

                        choice = control.selectDialog(queries)

                        if choice <= len(read_from_history(
                                history_media)) and not choice == -1:
                            search_link = url_generator(
                                read_from_history(history_media)[choice],
                                history=True)
                        else:
                            control.execute('Dialog.Close(all)')
                            return

                    else:

                        self.list = [{
                            'title': q,
                            'url': url_generator(q, history=True),
                            'action': 'search',
                            'query': q,
                            'isFolder': 'False',
                            'isPlayable': 'False'
                        } for q in queries]

                        for i in self.list:

                            bookmark = dict((k, v) for k, v in iteritems(i)
                                            if not k == 'next')
                            bm_object = json.dumps(bookmark)
                            add_bm_cm = {
                                'title': 30023,
                                'query': {
                                    'action': 'addBookmark',
                                    'url': bm_object
                                }
                            }
                            i.update({'cm': [add_bm_cm]})

                        directory.add(self.list)
                        return

                elif query:

                    # Can convert a query directly to listing for display

                    search_link = url_generator(query, history=True)

                else:

                    control.execute('Dialog.Close(all)')
                    return

                directory.run_builtin(action='listing', url=search_link)

            else:

                if not override:
                    del choices[1]
                    choice = control.selectDialog(choices)
                else:
                    choice = None

                if choice == 0 or query == 'quick':

                    search_link = url_generator(media=False)

                elif choice == 1 or query == 'history':

                    if not read_from_history(history_subrs):
                        return

                    queries = read_from_history(history_subrs)

                    if control.setting('window.action') == '0':

                        choice = control.selectDialog(queries)

                        if choice <= len(read_from_history(
                                history_media)) and not choice == -1:
                            search_link = url_generator(
                                read_from_history(history_subrs)[choice],
                                media=False,
                                history=True)
                        else:
                            control.execute('Dialog.Close(all)')
                            return

                    else:

                        self.list = [{
                            'title':
                            q,
                            'url':
                            url_generator(q, media=False, history=True),
                            'action':
                            'search',
                            'query':
                            q,
                            'isFolder':
                            'False',
                            'isPlayable':
                            'False'
                        } for q in queries]

                        directory.add(self.list)
                        return

                elif query:

                    # Can convert a query directly to listing for display

                    search_link = url_generator(query=query,
                                                media=False,
                                                history=True)

                else:

                    control.execute('Dialog.Close(all)')
                    return

                directory.run_builtin(action='listing', url=search_link)

        else:

            self.list = [{
                'title': control.lang(30003),
                'action': 'search',
                'query': 'quick',
                'url': 'media' if media else 'subreddits'
            }]

            if media:

                self.list.append({
                    'title': control.lang(30005),
                    'action': 'search',
                    'query': 'advanced',
                    'url': 'media'
                })

                self.list.append({
                    'title': control.lang(30155),
                    'action': 'search',
                    'query': 'domain',
                    'url': 'media'
                })

            for i in self.list:
                i.update({'isFolder': 'False', 'isPlayable': 'False'})

            if control.setting('history.bool') == 'true':

                self.list.append({
                    'title': control.lang(30010),
                    'action': 'search',
                    'query': 'history',
                    'url': 'media' if media else 'subreddits'
                })

        directory.add(self.list)
Exemplo n.º 21
0
    def resolve(self, url):

        _url = url

        if 'radiostreaming' in url:

            return url

        elif 'youtube' in url or len(url) == 11:

            if url.startswith('plugin://'):
                url = url[-11:]

            return self.yt_session(url)

        else:

            html = client.request(url)

            if 'iframe' in html:

                iframe = parseDOM(html, 'iframe', ret='src')[0]

            else:

                availability = parseDOM(html, 'strong')[-1]
                control.okDialog(control.name(), availability)

                return 'https://static.adman.gr/inpage/blank.mp4'

            if 'youtube' in iframe:

                return self.resolve(iframe)

            else:

                result = client.request(iframe)
                urls = re.findall(r'(?:var )?(?:HLSLink|stream)(?:ww)?\s+=\s+[\'"](.+?)[\'"]', result)

                if urls:

                    if control.setting('debug') == 'false':
                        geo = cache.get(self._geo_detect, 192)
                    else:
                        geo = self._geo_detect()

                    if len(urls) >= 2:

                        if _url.endswith('-live/'):

                            if not geo:
                                return urls[-1]
                            else:
                                return urls[0]

                        else:

                            url = [i for i in urls if 'dvrorigingr' in i][0]

                            try:
                                video_ok = client.request(url, timeout=3)
                            except Exception:
                                video_ok = None

                            if video_ok:

                                return url

                            else:

                                url = [i for i in urls if 'dvrorigin' in i][0]

                                return url

                    else:

                        if 'youtube' in urls[0]:
                            return self.resolve(urls[0])
                        else:
                            return urls[0]

                else:

                    iframes = parseDOM(result, 'iframe', ret='src')

                    try:
                        return self.resolve(iframes[-1])
                    except YouTubeException:
                        return self.resolve(iframes[0])