예제 #1
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
            if control.kodi_version() >= 18.0:
                self.pass_input = pyxbmct.Edit(control.lang(30153))
                self.placeControl(self.pass_input, 3, 0)
                self.pass_input.setType(6, control.lang(30153))
            else:
                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))
    def root(self):

        self.list = [{
            'title': control.lang(30001),
            'action': 'live_tv',
            'icon': iconname('monitor'),
            'boolean': control.setting('show_live') == 'true'
        }, {
            'title': control.lang(30036),
            'action': 'pvr_client',
            'icon': iconname('guide'),
            'boolean': control.setting('show_pvr') == 'true',
            'isFolder': 'False',
            'isPlayable': 'False'
        }, {
            'title': control.lang(30008),
            'action': 'networks',
            'icon': iconname('networks'),
            'boolean': control.setting('show_networks') == 'true'
        }, {
            'title': control.lang(30123),
            'action': 'news',
            'icon': iconname('news'),
            'boolean': control.setting('show_news') == 'true'
        }, {
            'title': control.lang(30031),
            'action': 'movies',
            'icon': iconname('movies'),
            'boolean': control.setting('show_movies') == 'true'
        }, {
            'title': control.lang(30083),
            'action': 'short_films',
            'icon': iconname('short'),
            'boolean': control.setting('show_short_films') == 'true'
        }, {
            'title': control.lang(30030),
            'action': 'series',
            'icon': iconname('series'),
            'boolean': control.setting('show_series') == 'true'
        }, {
            'title': control.lang(30063),
            'action': 'shows',
            'icon': iconname('shows'),
            'boolean': control.setting('show_shows') == 'true'
        }, {
            'title': control.lang(30068),
            'action': 'theater',
            'icon': iconname('theater'),
            'boolean': control.setting('show_theater') == 'true'
        }, {
            'title': control.lang(30079),
            'action': 'listing',
            'url': 'http://greek-movies.com/movies.php?g=6&y=&l=&p=',
            'icon': iconname('documentaries'),
            'boolean': control.setting('show_docs') == 'true'
        }, {
            'title': control.lang(30094),
            'action': 'sports',
            'icon': iconname('sports'),
            'boolean': control.setting('show_sports') == 'true'
        }, {
            'title': control.lang(30032),
            'action': 'kids',
            'icon': iconname('kids'),
            'boolean': control.setting('show_kids') == 'true'
        }, {
            'title': control.lang(30012),
            'action': 'miscellany',
            'icon': iconname('miscellany'),
            'boolean': control.setting('show_misc') == 'true'
        }, {
            'title': control.lang(30002),
            'action': 'radio',
            'icon': iconname('radios'),
            'boolean': control.setting('show_radio') == 'true'
        }, {
            'title': control.lang(30125),
            'action': 'music',
            'icon': iconname('music'),
            'boolean': control.setting('show_music') == 'true'
        }, {
            'title': control.lang(30095).partition(' ')[0],
            'action': 'search',
            'icon': iconname('search'),
            'boolean': control.setting('show_search') == 'true'
        }, {
            'title': control.lang(30055),
            'action': 'bookmarks',
            'icon': iconname('bookmarks'),
            'boolean': control.setting('show_bookmarks') == 'true'
        }, {
            'title':
            control.lang(30137),
            'action':
            'openSettings&query=0.0'
            if control.setting('old_settings') == 'true' else 'settings',
            'icon':
            iconname('settings'),
            'boolean':
            control.setting('show_settings') == 'true'
        }, {
            'title': control.lang(30288),
            'action': 'quit',
            'icon': iconname('quit'),
            'boolean': control.setting('show_quit') == 'true',
            'isFolder': 'False',
            'isPlayable': 'False'
        }]

        self.menu = [i for i in self.list if i['boolean']]

        for item in self.menu:

            if item['action'] == 'live_tv' and control.setting(
                    'live_tv_mode') == '1':
                item.update({'isFolder': 'False', 'isPlayable': 'False'})

            refresh = {'title': 30054, 'query': {'action': 'refresh'}}
            cache_clear = {'title': 30056, 'query': {'action': 'cache_clear'}}
            reset_idx = {
                'title': 30134,
                'query': {
                    'action': 'reset_idx',
                    'query': 'force'
                }
            }
            settings = {'title': 30011, 'query': {'action': 'openSettings'}}
            go_to_audio = {
                'title': 30321,
                'query': {
                    'action': 'activate_audio_addon',
                    'url': 'plugin.video.AliveGR'
                }
            }
            tools = {'title': 30137, 'query': {'action': 'tools_menu'}}
            ii_cm = {'title': 30255, 'query': {'action': 'call_info'}}
            item.update({
                'cm': [
                    ii_cm, refresh, cache_clear, reset_idx, settings,
                    go_to_audio, tools
                ]
            })

        if control.setting('reset_idx') == 'true':
            reset(notify=False)

        directory.add(self.menu)
예제 #3
0
    def root(self):

        self.list = [
            {
                'title': control.lang(30001),
                'action': 'channels',
                'icon': 'channels.jpg'
            }
            ,
            {
                'title': control.lang(30002),
                'action': 'recent',
                'icon': 'recent.jpg'
            }
            ,
            {
                'title': control.lang(30015),
                'action': 'youtube',
                'icon': 'youtube.jpg',
                'url': ''.join(
                    ['plugin://plugin.video.youtube/channel/', self.channel_id, '/?addon_id=', control.addonInfo('id')]
                ),
                'isFolder': 'False', 'isPlayable': 'False'
            }
            ,
            {
                'title': control.lang(30011),
                'action': 'index',
                'icon': 'index.jpg'
            }
            ,
            {
                'title': control.lang(30004),
                'action': 'listing',
                'url': self.news_link,
                'icon': 'news.jpg'
            }
            ,
            {
                'title': control.lang(30049),
                'action': 'listing',
                'icon': 'movies.jpg',
                'url': self.movies_link
            }
            ,
            {
                'title': control.lang(30020),
                'action': 'shows',
                'icon': 'shows.jpg'
            }
            ,
            {
                'title': control.lang(30038),
                'action': 'series',
                'icon': 'series.jpg'
            }
            ,
            {
                'title': control.lang(30003),
                'action': 'listing',
                'url': self.sports_link,
                'icon': 'sports.jpg'
            }
            ,
            {
                'title': control.lang(30009),
                'action': 'listing',
                'icon': 'kids.jpg',
                'url': self.cartoons_link
            }
            ,
            {
                'title': control.lang(30055),
                'action': 'listing',
                'url': self.archive_link,
                'icon': 'archive.jpg'
            }
            ,
            {
                'title': control.lang(30013),
                'action': 'search',
                'icon': 'search.jpg',
                'isFolder': 'False', 'isPlayable': 'False'
            }
            ,
            {
                'title': control.lang(30012),
                'action': 'bookmarks',
                'icon': 'bookmarks.jpg'
            }
            ,
            {
                'title': control.lang(30026),
                'action': 'radios',
                'icon': 'radio.jpg'
            }
        ]

        settings_menu = {
                'title': control.lang(30044),
                'action': 'settings',
                'icon': 'settings.jpg',
                'isFolder': 'False', 'isPlayable': 'False'
            }

        if control.setting('settings_boolean') == 'true':
            self.list.append(settings_menu)

        for item in self.list:

            cache_clear = {'title': 30036, 'query': {'action': 'cache_clear'}}
            settings = {'title': 30039, 'query': {'action': 'settings'}}
            item.update({'cm': [cache_clear, settings]})

        directory.add(self.list, content='videos')
예제 #4
0
def player(url, params, do_not_resolve=False):

    if url is None:
        log_debug('Nothing playable was found')
        return

    url = url.replace('&', '&')

    log_debug('Attempting to play this url: ' + url)

    if 'ustream' in url:

        log_debug('Opening browser window for this url: {0}'.format(url))

        control.open_web_browser(url)

        while not control.wait(1):

            if control.condVisibility('Window.IsActive(okdialog)'):
                control.execute('Dialog.Close(all)')
                break

            return

    if do_not_resolve:
        stream = url
    else:
        stream = conditionals(url, params)

    if not stream or (len(stream) == 2 and not stream[0]):

        log_debug('Failed to resolve this url: {0}'.format(url))
        control.execute('Dialog.Close(all)')

        return

    plot = None

    try:

        if isinstance(stream, tuple):

            plot = stream[1]
            stream = stream[0]

        else:

            try:
                plot = params.get('plot').encode('latin-1')
            except (UnicodeEncodeError, UnicodeDecodeError, AttributeError):
                plot = params.get('plot')

    except TypeError:

        pass

    else:

        log_debug('Plot obtained')

    dash, m3u8_dash, mimetype, manifest_type = dash_conditionals(stream)

    if not m3u8_dash and control.setting('m3u8_quality_picker') in [
            '1', '2'
    ] and '.m3u8' in stream:

        try:

            stream = m3u8_loader.m3u8_picker(stream)

        except TypeError:

            pass

    if isinstance(stream, OrderedDict):

        try:

            try:
                args = stream['best'].args
            except Exception:
                args = None

            try:
                json_dict = json.loads(stream['best'].json)
            except Exception:
                json_dict = None

            for h in args, json_dict:

                if 'headers' in h:
                    headers = h['headers']
                    break
                else:
                    headers = None

            if headers:

                try:
                    del headers['Connection']
                    del headers['Accept-Encoding']
                    del headers['Accept']
                except KeyError:
                    pass

                append = ''.join(['|', urlencode(headers)])

            else:

                append = ''

        except AttributeError:

            append = ''

        if control.setting('sl_quality_picker') == '0' or len(stream) == 3:

            stream = stream['best'].to_url() + append

        else:

            keys = stream.keys()[::-1]
            values = [u.to_url() + append for u in stream.values()][::-1]

            stream = stream_picker(keys, values)

        dash, m3u8_dash, mimetype, manifest_type = dash_conditionals(stream)

    if stream != url:

        log_debug('Stream has been resolved: ' + stream)

    if '|' in stream or '|' in url:

        from tulip.compat import parse_qsl

        log_debug('Appending custom headers: ' +
                  repr(dict(parse_qsl(stream.rpartition('|')[2]))))

    try:

        image = params.get('image').encode('latin-1')
        title = params.get('title').encode('latin-1')

    except (UnicodeEncodeError, UnicodeDecodeError, AttributeError):

        image = params.get('image')
        title = params.get('title')

    meta = {'title': title}

    if plot:

        meta.update({'plot': plot})

    try:
        directory.resolve(stream,
                          meta=meta,
                          icon=image,
                          dash=dash,
                          manifest_type=manifest_type,
                          mimetype=mimetype)
    except:
        control.execute('Dialog.Close(all)')
        control.infoDialog(control.lang(30112))
예제 #5
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()

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

        try:

            if progress:

                p = control.percent(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 not (k == 'cm' or k == 'streaminfo') 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, 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)
예제 #6
0
    def news(self):

        items = [{
            'title': control.lang(30230),
            'icon':
            'https://www.iconexperience.com/_img/v_collection_png/256x256/shadow/newspaper.png',
            'url': '{0}?action=papers'.format(sysaddon),
            'fanart': control.addonInfo('fanart')
        }, {
            'title':
            control.lang(30118),
            'icon':
            control.addonmedia(addonid=ART_ID,
                               theme='networks',
                               icon='ert_icon.png',
                               media_subfolder=False),
            'url':
            'plugin://plugin.video.ert.gr/?action=categories&url=https%3A%2F%2Fwww.ertflix.gr%2Fshow%2Fnews',
            'fanart':
            control.addonmedia(addonid=ART_ID,
                               theme='networks',
                               icon='ert_fanart.jpg',
                               media_subfolder=False)
        }, {
            'title':
            control.lang(30119),
            'icon':
            control.addonmedia(addonid=ART_ID,
                               theme='networks',
                               icon='ant1_icon.png',
                               media_subfolder=False),
            'url':
            'plugin://plugin.video.antenna.gr/?action=videos&url=https%3a%2f%2fwww.ant1news.gr%2fvideos',
            'fanart':
            control.addonmedia(addonid=ART_ID,
                               theme='networks',
                               icon='ant1_fanart.jpg',
                               media_subfolder=False)
        }, {
            'title':
            control.lang(30120),
            'icon':
            control.addonmedia(addonid=ART_ID,
                               theme='networks',
                               icon='star_icon.png',
                               media_subfolder=False),
            'url':
            'plugin://plugin.video.star.gr/?action=news',
            'fanart':
            control.addonmedia(addonid=ART_ID,
                               theme='networks',
                               icon='star_fanart.jpg',
                               media_subfolder=False)
        }, {
            'title':
            control.lang(30122),
            'icon':
            control.addonmedia(addonid=ART_ID,
                               theme='networks',
                               icon='alpha_icon.png',
                               media_subfolder=False),
            'url':
            'plugin://plugin.video.alphatv.gr/?action=news&url=https%3a%2f%2fwww.alphatv.gr%2fnews',
            'fanart':
            control.addonmedia(addonid=ART_ID,
                               theme='networks',
                               icon='alpha_fanart.jpg',
                               media_subfolder=False)
        }, {
            'title':
            control.lang(30121),
            'icon':
            control.addonmedia(addonid=ART_ID,
                               theme='networks',
                               icon='skai_icon.png',
                               media_subfolder=False),
            'url':
            'plugin://plugin.video.skai.gr/?action=news',
            'fanart':
            control.addonmedia(addonid=ART_ID,
                               theme='networks',
                               icon='skai_fanart.jpg',
                               media_subfolder=False)
        }]

        for item in items:

            list_item = control.item(label=item['title'])
            list_item.setArt({'icon': item['icon'], 'fanart': item['fanart']})
            url = item['url']
            isFolder = True if 'papers' not in item['url'] else False
            self.list.append((url, list_item, isFolder))

        control.addItems(syshandle, self.list)
        control.directory(syshandle)
예제 #7
0
def gm_source_maker(url):

    if 'episode' in url:

        html = client.request(url=url.partition('?')[0],
                              post=url.partition('?')[2])
        links = client.parseDOM(html, 'a', ret='href')
        links = [urljoin(base_link, link) for link in links]
        hl = client.parseDOM(html, 'a')
        hosts = [
            host.replace(u'προβολή στο ', control.lang(30015)) for host in hl
        ]

        return 'episode', hosts, links

    elif 'view' in url:

        html = client.request(url)
        link = client.parseDOM(html,
                               'a',
                               ret='href',
                               attrs={"class": "btn btn-primary"})[0]

        return 'view', link

    elif 'music' in url:

        html = client.request(url)
        link = client.parseDOM(html,
                               'iframe',
                               ret='src',
                               attrs={"class": "embed-responsive-item"})[0]
        return 'music', link

    else:

        html = client.request(url)

        try:
            info = client.parseDOM(html,
                                   'h4',
                                   attrs={'style': 'text-indent:10px;'})
            if ',' in info[1]:
                genre = info[1].lstrip(u'Είδος:').split(',')
                genre = random.choice(genre)
                genre = genre.strip()
            else:
                genre = info[1].lstrip(u'Είδος:').strip()
        except:
            genre = control.lang(30147)

        links = client.parseDOM(html,
                                'a',
                                ret='href',
                                attrs={"class": "btn btn-primary"})
        hl = client.parseDOM(html, 'a', attrs={"class": "btn btn-primary"})
        if not links or not hl:
            buttons = client.parseDOM(html,
                                      'div',
                                      attrs={"class": "btn-group"})
            hl = [
                client.stripTags(
                    client.parseDOM(h, 'button', attrs={"type": "button"
                                                        })[0]).strip('"') + p
                for h in buttons
                for p in client.parseDOM(h, 'a', attrs={'target': '_blank'})
            ]
            links = [
                l for b in buttons for l in client.parseDOM(b, 'a', ret='href')
            ]
        links = [urljoin(base_link, link) for link in links]

        hosts = [
            host.replace(u'προβολή στο ', control.lang(30015)).replace(
                u'προβολή σε ',
                control.lang(30015)).replace(u'μέρος ',
                                             ', ' + control.lang(30225))
            for host in hl
        ]

        if 'text-align: justify' in html:
            plot = client.parseDOM(html,
                                   'p',
                                   attrs={'style': 'text-align: justify'})[0]
        elif 'text-justify' in html:
            plot = client.parseDOM(html, 'p', attrs={'class':
                                                     'text-justify'})[0]
        else:
            plot = control.lang(30085)

        code = None
        imdb_code = re.search('imdb.+?/title/([\w]+?)/', html)
        if imdb_code:
            code = imdb_code.group(1)

        return 'movies', hosts, links, plot, genre, code
예제 #8
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))
예제 #9
0
    def wizard():

        control.addon('plugin.video.youtube').setSetting('kodion.setup_wizard', 'false')
        control.addon('plugin.video.youtube').setSetting('youtube.language', 'el')
        control.addon('plugin.video.youtube').setSetting('youtube.region', 'GR')
        control.infoDialog(message=control.lang(30402), time=3000)
예제 #10
0
    def run(self, url, source):

        log_debug('Source selected: {0}'.format(source))

        path = control.join(control.dataPath, 'temp')

        try:

            path = path.decode('utf-8')

        except Exception:

            pass

        control.deleteDir(control.join(path, ''), force=True)
        control.makeFile(control.dataPath)
        control.makeFile(path)

        if control.setting('keep_subs') == 'true' or control.setting(
                'keep_zips') == 'true':

            if not control.get_info_label('ListItem.Path').startswith(
                    'plugin://') and control.setting('destination') == '0':
                output_path = control.get_info_label('Container.FolderPath')
            elif control.setting('output_folder').startswith('special://'):
                output_path = control.transPath(
                    control.setting('output_folder'))
            else:
                output_path = control.setting('output_folder')

            if not exists(output_path):
                control.makeFile(output_path)

        if source == 'subtitlesgr':

            subtitle = subtitlesgr.Subtitlesgr().download(path, url)

        elif source == 'xsubstv':

            subtitle = xsubstv.Xsubstv().download(path, url)

        elif source == 'podnapisi':

            subtitle = podnapisi.Podnapisi().download(path, url)

        elif source == 'vipsubs':

            subtitle = vipsubs.Vipsubs().download(path, url)

        else:

            subtitle = None

        if subtitle is not None:

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

                # noinspection PyUnboundLocalVariable
                try:
                    if control.setting('destination') in ['0', '2']:
                        if control.infoLabel('{0}.Title'.format(
                                infolabel_prefix)).startswith('plugin://'):
                            copy(
                                subtitle,
                                control.join(output_path,
                                             os_split(subtitle)[1]))
                            log_debug(
                                'Item currently selected is not a local file, cannot save subtitle next to it'
                            )
                        else:
                            output_filename = control.join(
                                output_path, ''.join([
                                    splitext(
                                        control.infoLabel('ListItem.FileName'))
                                    [0],
                                    splitext(os_split(subtitle)[1])[1]
                                ]))
                            if exists(output_filename):
                                yesno = control.yesnoDialog(
                                    control.lang(30015))
                                if yesno:
                                    copy(subtitle, output_filename)
                            else:
                                copy(subtitle, output_filename)
                            if control.setting('destination') == '2':
                                if control.setting('output_folder').startswith(
                                        'special://'):
                                    output_path = control.transPath(
                                        control.setting('output_folder'))
                                else:
                                    output_path = control.setting(
                                        'output_folder')
                                copy(
                                    subtitle,
                                    control.join(output_path,
                                                 os_split(subtitle)[1]))
                    else:
                        copy(subtitle,
                             control.join(output_path,
                                          os_split(subtitle)[1]))
                    control.infoDialog(control.lang(30008))
                except Exception:
                    control.infoDialog(control.lang(30013))

            item = control.item(label=subtitle)
            control.addItem(handle=self.syshandle,
                            url=subtitle,
                            listitem=item,
                            isFolder=False)

        control.directory(self.syshandle)
예제 #11
0
    def run(self, query=None):

        if 'Greek' not in str(self.langs).split(','):

            control.directory(self.syshandle)
            control.infoDialog(control.lang(30002))

            return

        dup_removal = False

        if not query:

            title = match_title = control.infoLabel(
                '{0}.Title'.format(infolabel_prefix))

            with concurrent_futures.ThreadPoolExecutor(5) as executor:

                if re.search(r'[^\x00-\x7F]+', title) is not None:

                    title = control.infoLabel(
                        '{0}.OriginalTitle'.format(infolabel_prefix))

                title = unicodedata.normalize('NFKD',
                                              title).encode('ascii', 'ignore')
                title = py3_dec(title)
                year = control.infoLabel('{0}.Year'.format(infolabel_prefix))
                tvshowtitle = control.infoLabel(
                    '{0}.TVshowtitle'.format(infolabel_prefix))
                season = control.infoLabel(
                    '{0}.Season'.format(infolabel_prefix))

                if len(season) == 1:

                    season = '0' + season

                episode = control.infoLabel(
                    '{0}.Episode'.format(infolabel_prefix))

                if len(episode) == 1:
                    episode = '0' + episode

                if 's' in episode.lower():
                    season, episode = '0', episode[-1:]

                if tvshowtitle != '':  # episode

                    title_query = '{0} {1}'.format(tvshowtitle, title)
                    season_episode_query = '{0} S{1} E{2}'.format(
                        tvshowtitle, season, episode)
                    season_episode_query_nospace = '{0} S{1}E{2}'.format(
                        tvshowtitle, season, episode)

                    threads = [
                        executor.submit(self.subtitlesgr,
                                        season_episode_query_nospace),
                        executor.submit(self.xsubstv, season_episode_query),
                        executor.submit(self.podnapisi, season_episode_query),
                        executor.submit(self.vipsubs, season_episode_query)
                    ]

                    dup_removal = True

                    log_debug('Dual query used for subtitles search: ' +
                              title_query + ' / ' + season_episode_query)

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

                        threads.extend([
                            executor.submit(self.subtitlesgr, title_query),
                            executor.submit(self.vipsubs, title_query),
                            executor.submit(self.podnapisi, title_query),
                            executor.submit(self.subtitlesgr,
                                            season_episode_query)
                        ])

                elif year != '':  # movie

                    query = '{0} ({1})'.format(title, year)

                    threads = [
                        executor.submit(self.subtitlesgr, query),
                        executor.submit(self.xsubstv, query),
                        executor.submit(self.vipsubs, query),
                        executor.submit(self.podnapisi, query)
                    ]

                else:  # file

                    query, year = control.cleanmovietitle(title)

                    if year != '':

                        query = '{0} ({1})'.format(query, year)

                    threads = [
                        executor.submit(self.subtitlesgr, query),
                        executor.submit(self.xsubstv, query),
                        executor.submit(self.vipsubs, query),
                        executor.submit(self.podnapisi, query)
                    ]

                for future in concurrent_futures.as_completed(threads):

                    item = future.result()

                    if not item:
                        continue

                    self.list.extend(item)

                if not dup_removal:

                    log_debug('Query used for subtitles search: ' + query)

                self.query = query

                self.query = py3_dec(self.query)

        else:  # Manual query

            with concurrent_futures.ThreadPoolExecutor(5) as executor:

                query = match_title = py3_dec(query)

                threads = [
                    executor.submit(self.subtitlesgr, query),
                    executor.submit(self.xsubstv, query),
                    executor.submit(self.vipsubs, query),
                    executor.submit(self.podnapisi, query)
                ]

                for future in concurrent_futures.as_completed(threads):

                    item = future.result()

                    if not item:
                        continue

                    self.list.extend(item)

        if len(self.list) == 0:

            control.directory(self.syshandle)

            return

        f = []

        # noinspection PyUnresolvedReferences
        f += [i for i in self.list if i['source'] == 'xsubstv']
        f += [i for i in self.list if i['source'] == 'subtitlesgr']
        f += [i for i in self.list if i['source'] == 'podnapisi']
        f += [i for i in self.list if i['source'] == 'vipsubs']

        self.list = f

        if dup_removal:

            self.list = [
                dict(t) for t in {tuple(d.items())
                                  for d in self.list}
            ]

        for i in self.list:

            try:

                if i['source'] == 'xsubstv':
                    i['name'] = u'[xsubstv] {0}'.format(i['name'])
                elif i['source'] == 'podnapisi':
                    i['name'] = u'[podnapisi] {0}'.format(i['name'])
                elif i['source'] == 'vipsubs':
                    i['name'] = u'[vipsubs] {0}'.format(i['name'])

            except Exception:

                pass

        if control.setting('sorting') == '1':
            key = 'source'
        elif control.setting('sorting') == '2':
            key = 'downloads'
        elif control.setting('sorting') == '3':
            key = 'rating'
        else:
            key = 'title'

        self.list = sorted(self.list,
                           key=lambda k: k[key].lower(),
                           reverse=control.setting('sorting')
                           in ['1', '2', '3'])

        for i in self.list:

            u = {'action': 'download', 'url': i['url'], 'source': i['source']}
            u = '{0}?{1}'.format(self.sysaddon, urlencode(u))
            item = control.item(label='Greek', label2=i['name'])
            item.setArt({'icon': str(i['rating'])[:1], 'thumb': 'el'})
            if ratio(
                    splitext(i['title'].lower())[0],
                    splitext(match_title)[0]) >= int(
                        control.setting('sync_probability')):
                item.setProperty('sync', 'true')
            else:
                item.setProperty('sync', 'false')
            item.setProperty('hearing_imp', 'false')

            control.addItem(handle=self.syshandle,
                            url=u,
                            listitem=item,
                            isFolder=False)

        control.directory(self.syshandle)
    def download(self, path, url):

        if url.startswith('http'):

            log_debug('Vipsubs.gr: Attempting downloading from this url ~ {0}'.
                      format(url))

            _filename = '.'.join(urlparse(url).path.split('/')[3:5])
            filename = control.join(path, _filename)

        else:

            filename = control.join(path, url)

        try:

            if url.startswith('http'):

                if 'dropbox' in url:
                    url = client.request(url,
                                         output='geturl',
                                         timeout=control.setting('timeout'))
                if is_py3:  # Kodi 19+
                    client.retriever(url, filename)
                    zip_file = zipfile.ZipFile(filename)
                    data = None
                else:
                    req = Request(url)
                    req.add_header('User-Agent', randomagent())
                    opener = urlopen(req)
                    data = opener.read()
                    zip_file = zipfile.ZipFile(BytesIO(data))
                    opener.close()

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

                    if control.setting('output_folder').startswith(
                            'special://'):
                        output_path = control.transPath(
                            control.setting('output_folder'))
                    else:
                        output_path = control.setting('output_folder')
                    if not os.path.exists(output_path):
                        control.makeFile(output_path)
                    # noinspection PyUnboundLocalVariable
                    output_filename = control.join(output_path, _filename)
                    if is_py3:  # Kodi 19+
                        control.copy(filename, output_filename)
                    else:
                        with open(output_filename, 'wb') as f:
                            f.write(data)

                    control.infoDialog(control.lang(30007))

            else:

                if zipfile.is_zipfile(filename):
                    zip_file = zipfile.ZipFile(filename)
                else:
                    log_debug(
                        'Failed to load zip with regular python library, attempting built-in method'
                    )
                    control.execute('Extract({0},{1})'.format(filename, path))
                    zip_file = None

            if zip_file:

                files = zip_file.namelist()
                subs = [
                    i for i in files if i.endswith(('.srt', '.sub', '.zip'))
                ]

            else:

                subs = []
                for root, _, file_ in os.walk(path):
                    for f in file_:
                        subs.append(os.path.join(root, f))

            subtitle = multichoice(subs)

            if not subtitle:
                return

            if zip_file:

                try:
                    zip_file.extract(subtitle, path)
                except Exception:
                    path = path.encode('utf-8')
                    zip_file.extract(subtitle, path)

            subtitle = control.join(path, subtitle)

            if subtitle.endswith('.zip'):

                return self.download(path, subtitle)

            else:

                try:

                    with closing(control.openFile(subtitle)) as fn:

                        try:
                            output = bytes(fn.readBytes())
                        except Exception:
                            output = bytes(fn.read())

                    content = output.decode('utf-16')

                    with closing(control.openFile(subtitle, 'w')) as subFile:
                        subFile.write(bytearray(content.encode('utf-8')))

                except Exception:
                    pass

                return subtitle

        except Exception as e:

            _, __, tb = sys.exc_info()

            print(traceback.print_tb(tb))

            log_debug(
                'Vipsubs.gr subtitle download failed for the following reason: '
                + str(e))

            return
예제 #13
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
예제 #14
0
def get_tokens(code=None, refresh=False):

    if not code:
        code = control.setting('auth.token')

    if refresh:
        post_data = {
            'grant_type': 'refresh_token',
            'refresh_token': control.setting('refresh.token')
        }
        if control.setting('debugging.toggle') == 'true':
            log_debug('Attempting to refresh access token...')
    else:
        post_data = {
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': redirect_uri
        }
        if control.setting('debugging.toggle') == 'true':
            log_debug('Attempting to retrieve access token...')

    if control.setting('debugging.toggle') == 'true':
        log_debug(post_data)

    headers = {'User-Agent': user_agent()}
    username, password = (client_id, '')
    result = client.request(api_link('access_token'),
                            post=post_data,
                            headers=headers,
                            username=username,
                            password=password)

    tokens = json.loads(result)

    if control.setting('debugging.toggle') == 'true':
        log_debug(tokens)

    if 'error' in tokens:
        try:
            log_debug('Authorization failed, reason: ' + tokens.get('error'))
        except TypeError:
            log_debug('Failure in general!')
        tokens_reset()
        return

    control.setSetting('access.token', tokens['access_token'])
    control.setSetting(
        'expiration.string',
        convert_date(int(time.time()) + int(tokens['expires_in'])))
    control.setSetting('expiration.stamp',
                       str(time.time() + float(tokens['expires_in'])))

    if not refresh:
        control.setSetting('access.scope', tokens['scope'].replace(' ', ', '))
        control.setSetting('refresh.token', tokens['refresh_token'])
        control.infoDialog(control.lang(30402))
        control.refresh()
    elif refresh and control.setting('notify.refresh') == 'true':
        control.infoDialog(control.lang(30145))

    control.setSetting('auth.toggle', 'false')
예제 #15
0
    def search_index(self):

        add_to_history_cm = {
            'title': 30486,
            'query': {
                'action': 'add_to_history'
            }
        }
        refresh_cm = {'title': 30054, 'query': {'action': 'refresh'}}

        self.list = [{
            'title': control.lang(30016),
            'action': 'search',
            'icon': iconname('search'),
            'isFolder': 'False',
            'isPlayable': 'False',
            'cm': [add_to_history_cm, refresh_cm]
        }]

        history = read_from_history()

        if history:

            search_history = [{
                'title':
                i.split(',')[1] + ' (' +
                control.lang(QUERY_MAP.get(i.split(',')[0])) + ')',
                'action':
                'search',
                'query':
                i,
                'cm': [
                    add_to_history_cm, {
                        'title': 30485,
                        'query': {
                            'action': 'delete_from_history',
                            'query': i
                        }
                    }, refresh_cm
                ]
            } for i in read_from_history()]

            for i in search_history:
                if i['query'].split(',')[0] == 'Live TV Channel':
                    i.update({'image': iconname('monitor')})
                elif i['query'].split(',')[0] == 'TV Serie':
                    i.update({'image': iconname('series')})
                elif i['query'].split(',')[0] == 'TV Show':
                    i.update({'image': iconname('shows')})
                elif i['query'].split(',')[0] == 'Movie':
                    i.update({'image': iconname('movies')})
                elif i['query'].split(',')[0] == 'Theater':
                    i.update({'image': iconname('theater')})
                elif i['query'].split(',')[0] == 'Cartoon':
                    i.update({'image': iconname('kids')})
                elif i['query'].split(',')[0] == 'Person':
                    i.update({'image': iconname('user')})

            self.list.extend(search_history)

        directory.add(self.list)
예제 #16
0
    def yt_mpd():

        control.addon('plugin.video.youtube').setSetting('kodion.video.quality.mpd', 'true')
        control.addon('plugin.video.youtube').setSetting('kodion.mpd.videos', 'true')
        control.addon('plugin.video.youtube').setSetting('kodion.mpd.live_streams', 'true')
        control.infoDialog(message=control.lang(30402), time=3000)
예제 #17
0
def add(items,
        cacheToDisc=True,
        content=None,
        mediatype=None,
        infotype='video',
        argv=None,
        as_playlist=False,
        auto_play=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:
        log('Directory not added, reason of failure: ' +
            'Empty or null list of items')
        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:

            _, __, tb = sys.exc_info()

            print(traceback.print_tb(tb))
            log('Directory not added, reason of failure: ' + repr(reason))

    if progress:

        pd.update(100)
        pd.close()

    if as_playlist:

        if not auto_play:
            control.openPlaylist(1 if infotype == 'video' else 0)
        else:
            control.execute('Action(Play)')

        return

    try:

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

        url = '{0}?action={1}&url={2}'.format(sysaddon, i['nextaction'],
                                              quote_plus(i['next']))
        if 'name' in i:
            url += '&name={0}'.format(quote_plus(i['name'].encode('utf-8')))
        if 'title' in i:
            url += '&title={0}'.format(quote_plus(i['title'].encode('utf-8')))
        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)
예제 #18
0
def setup_iptv():

    xbmc_path = control.join('special://xbmc', 'addons', 'pvr.iptvsimple')
    home_path = control.join('special://home', 'addons', 'pvr.iptvsimple')

    def install():

        if control.conditional_visibility('System.Platform.Linux') and not (path.exists(control.transPath(xbmc_path)) or path.exists(control.transPath(home_path))):

            control.okDialog(heading='AliveGR', line1=control.lang(30323))

            return False

        elif path.exists(control.transPath(xbmc_path)) or path.exists(control.transPath(home_path)):

            return True

        elif addon_version('xbmc.python') >= 2260 and not control.condVisibility('System.HasAddon(pvr.iptvsimple)'):

            control.execute('InstallAddon(pvr.iptvsimple)')

            return True

        elif control.condVisibility('System.HasAddon(pvr.iptvsimple)'):

            return 'enabled'

        else:

            return False

    def setup_client(apply=False):

        url = thgiliwt('=' + vtpi)

        if apply:

            xml = client.request(url)

            settings = re.findall(r'id="(\w*?)" value="(\S*?)"', xml)

            for k, v in settings:

                control.addon('pvr.iptvsimple').setSetting(k, v)

        else:

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

            client.retriever(url, control.join(iptv_folder, "settings.xml"))

    if path.exists(control.join(iptv_folder, 'settings.xml')):

        integer = 30021

    else:

        integer = 30023

    if control.yesnoDialog(line1=control.lang(integer), line2='', line3=control.lang(30022)):

        success = install()

        if success:

            setup_client(apply=success == 'enabled')
            control.infoDialog(message=control.lang(30024), time=2000)
            enable_iptv()
            enable_proxy_module()

        else:

            control.okDialog('AliveGR', control.lang(30410))

    else:

        control.infoDialog(message=control.lang(30029), time=2000)
예제 #19
0
elif action == 'playlist':

    playlist(url)

elif action == 'bookmarks':

    bm_list()

elif action == 'addBookmark':

    bookmarks.add(url)

elif action == 'deleteBookmark':

    bookmarks.delete(url)

elif action == 'settings':

    control.openSettings()

elif action == 'cache_clear':

    if control.yesnoDialog(line1=control.lang(30009), line2='', line3=''):

        cache.clear(withyes=False)

    else:

        control.infoDialog(control.lang(30011))
    def root(self):

        self.list = [{
            'title': control.lang(32001),
            'action': 'live',
            'isFolder': 'False',
            'icon': 'live.png'
        }, {
            'title': control.lang(32002),
            'action': 'videos',
            'url': self.top_link,
            'icon': 'top.png'
        }, {
            'title': control.lang(32003),
            'action': 'videos',
            'url': self.theme_link % '1',
            'icon': 'news.png'
        }, {
            'title': control.lang(32004),
            'action': 'videos',
            'url': self.theme_link % '8',
            'icon': 'sports.png'
        }, {
            'title': control.lang(32005),
            'action': 'videos',
            'url': self.theme_link % '7',
            'icon': 'business.png'
        }, {
            'title': control.lang(32006),
            'action': 'videos',
            'url': self.theme_link % '5',
            'icon': 'europe.png'
        }, {
            'title': control.lang(32007),
            'action': 'videos',
            'url': self.theme_link % '2',
            'icon': 'culture.png'
        }, {
            'title': control.lang(32008),
            'action': 'videos',
            'url': self.theme_link % '3',
            'icon': 'scitech.png'
        }, {
            'title': control.lang(32009),
            'action': 'videos',
            'url': self.theme_link % '21',
            'icon': 'travel.png'
        }, {
            'title': control.lang(32010),
            'action': 'programs',
            'icon': 'programs.png'
        }, {
            'title': control.lang(32221),
            'action': 'settings',
            'isFolder': 'False',
            'isPlayable': 'False'
        }]

        directory.add(self.list, content='videos')
예제 #21
0
def items_directory(url, params):

    sources = cache.get(gm_source_maker, 6, url)

    lists = zip(sources[1], sources[2])

    items = []

    try:
        description = sources[3]
    except IndexError:
        try:
            description = params.get('plot').encode('latin-1')
        except (UnicodeEncodeError, UnicodeDecodeError, AttributeError):
            description = params.get('plot')
        if not description:
            description = control.lang(30085)

    try:
        genre = sources[4]
    except IndexError:
        genre = control.lang(30147)

    separator = ' - ' if control.setting('wrap_labels') == '1' else '[CR]'

    for h, l in lists:

        html = client.request(l)
        button = client.parseDOM(html,
                                 'a',
                                 attrs={'role': 'button'},
                                 ret='href')[0]
        image = client.parseDOM(html,
                                'img',
                                attrs={'class': 'thumbnail img-responsive'},
                                ret='src')[0]
        image = urljoin(base_link, image)
        title = client.parseDOM(html, 'h3')[0]
        year = [
            y[-4:] for y in client.parseDOM(html, 'h4')
            if str(y[-4:]).isdigit()
        ][0]
        try:
            episode = client.stripTags(client.parseDOM(html, 'h4')[-1])
            if episode[-4:].isdigit():
                raise IndexError
            episode = episode.partition(': ')[2]
            label = title + ' - ' + episode + separator + h
            title = title + ' - ' + episode
        except IndexError:
            label = title + separator + h
        # plot = title + '[CR]' + control.lang(30090) + ': ' + year + '[CR]' + description

        data = dict(label=label,
                    title=title + ' ({})'.format(year),
                    url=button,
                    image=image,
                    plot=description,
                    year=int(year),
                    genre=genre,
                    name=title)

        items.append(data)

    return items
예제 #22
0
def root(url):

    root_list = []
    groups_list = []

    html = client.request(url)

    if url == SPORTS:

        sports_index = client.parseDOM(html, 'div', attrs={'class': 'col-xs-6 text-center'})[0]
        return sports_index

    elif url == MUSIC:

        music_index = client.parseDOM(html, 'div', attrs={'class': 'col-sm-5 col-md-4'})[0]
        return music_index

    else:

        result = client.parseDOM(html, 'div', attrs={'class': 'row', 'style': 'margin-bottom: 20px;'})[0]
        items = re.findall('(<option  ?value=.*?</option>)', result, re.U)

        groups = client.parseDOM(result, 'option', attrs={'selected value': '.+?'})

        for group in groups:
            if group == u'ΑΡΧΙΚΑ':
                group = group.replace(u'ΑΡΧΙΚΑ', '30213')
            elif group == u'ΕΤΟΣ':
                group = group.replace(u'ΕΤΟΣ', '30090')
            elif group == u'ΚΑΝΑΛΙ':
                group = group.replace(u'ΚΑΝΑΛΙ', '30211')
            elif group == u'ΕΙΔΟΣ':
                group = group.replace(u'ΕΙΔΟΣ', '30200')
            elif group == u'ΠΑΡΑΓΩΓΗ':
                group = group.replace(u'ΠΑΡΑΓΩΓΗ', '30212')
            groups_list.append(group)

        for item in items:

            name = client.parseDOM(item, 'option', attrs={'value': '.+?.php.+?'})[0]
            name = name.replace(u'σήμερα', control.lang(30268))
            title = name[0].capitalize() + name[1:]
            link = client.parseDOM(item, 'option', ret='value')[0]
            indexer = urlparse(link).query
            index = urljoin(GM_BASE, link)

            if indexer.startswith('l='):
                group = '30213'
            elif indexer.startswith('y='):
                group = '30090'
            elif indexer.startswith('c='):
                group = '30211'
            elif indexer.startswith('g='):
                group = '30200'
            elif indexer.startswith('p='):
                group = '30212'
            else:
                group = ''

            root_list.append({'title': title, 'group': group, 'url': index})

        return root_list, groups_list
예제 #23
0
    def search(self):

        choices = [
            control.lang(30096),
            control.lang(30031),
            control.lang(30030),
            control.lang(30063),
            control.lang(30068),
            control.lang(30097),
            control.lang(30101)  #, control.lang(30125)
        ]

        choice = control.selectDialog(heading=control.lang(30095),
                                      list=choices)

        if choice == 0:

            str_input = control.dialog.input(
                heading=control.lang(30095).partition(' ')[0] +
                control.lang(30100) + control.lang(30096))

            if not str_input:
                return

            self.list = live.Indexer().live_tv(zapping=False,
                                               query=str_input.lower())

            directory.add(self.list)

        elif choice == 1:

            str_input = control.dialog.input(
                heading=control.lang(30095).partition(' ')[0] +
                control.lang(30100) + control.lang(30031))

            try:
                str_input = cleantitle.strip_accents(str_input.decode('utf-8'))
            except (UnicodeEncodeError, UnicodeDecodeError, AttributeError):
                str_input = cleantitle.strip_accents(str_input)

            if not str_input:
                return

            self.list = self.wrapper(str_input, 'movies')

            directory.add(self.list, content='movies')

        elif choice == 2:

            str_input = control.dialog.input(
                heading=control.lang(30095).partition(' ')[0] +
                control.lang(30100) + control.lang(30030))

            if not str_input:

                return

            try:
                str_input = cleantitle.strip_accents(str_input.decode('utf-8'))
            except (UnicodeEncodeError, UnicodeDecodeError, AttributeError):
                str_input = cleantitle.strip_accents(str_input)

            self.list = self.wrapper(str_input, 'series')

            directory.add(self.list, content='tvshows')

        elif choice == 3:

            str_input = control.dialog.input(
                heading=control.lang(30095).partition(' ')[0] +
                control.lang(30100) + control.lang(30063))

            if not str_input:

                return

            try:
                str_input = cleantitle.strip_accents(str_input.decode('utf-8'))
            except (UnicodeEncodeError, UnicodeDecodeError, AttributeError):
                str_input = cleantitle.strip_accents(str_input)

            self.list = self.wrapper(str_input, 'shows')

            directory.add(self.list, content='tvshows')

        elif choice == 4:

            str_input = control.dialog.input(
                heading=control.lang(30095).partition(' ')[0] +
                control.lang(30100) + control.lang(30068))

            if not str_input:

                return

            try:
                str_input = cleantitle.strip_accents(str_input.decode('utf-8'))
            except (UnicodeEncodeError, UnicodeDecodeError, AttributeError):
                str_input = cleantitle.strip_accents(str_input)

            self.list = self.wrapper(str_input, 'theater')

            directory.add(self.list, content='tvshows')

        elif choice == 5:

            str_input = control.dialog.input(
                heading=control.lang(30095).partition(' ')[0] +
                control.lang(30100) + control.lang(30097))

            if not str_input:

                return

            try:
                str_input = cleantitle.strip_accents(str_input.decode('utf-8'))
            except (UnicodeEncodeError, UnicodeDecodeError, AttributeError):
                str_input = cleantitle.strip_accents(str_input)

            self.list = self.wrapper(str_input, 'animation')

            directory.add(self.list, content='tvshows')

        elif choice == 6:

            str_input = control.dialog.input(
                heading=control.lang(30095).partition(' ')[0] +
                control.lang(30100) + control.lang(30101))

            if not str_input:

                return

            try:
                str_input = cleantitle.strip_accents(str_input.decode('utf-8'))
            except (UnicodeEncodeError, UnicodeDecodeError, AttributeError):
                str_input = cleantitle.strip_accents(str_input)

            self.list = self.wrapper(str_input, 'person')

            directory.add(self.list)

        # elif choice == 7:
        #
        #     str_input = control.dialog.input(
        #         heading=control.lang(30095).partition(' ')[0] + control.lang(30100) + control.lang(30125)
        #     )
        #
        #     if not str_input:
        #
        #         return
        #
        #     try:
        #         str_input = cleantitle.strip_accents(str_input.decode('utf-8'))
        #     except (UnicodeEncodeError, UnicodeDecodeError, AttributeError):
        #         str_input = cleantitle.strip_accents(str_input)
        #
        #     self.list = cache.get(self.wrapper, 12, str_input, 'music')
        #
        #     directory.add(self.list)

        else:

            control.execute('ActivateWindow(videos,"{0}")'.format(sysaddon))
예제 #24
0
    def epeisodia(self, url):

        html = client.request(url)
        image = client.parseDOM(html, 'img', attrs={'class': 'thumbnail.*?'}, ret='src')[0]
        image = urljoin(GM_BASE, image)
        year = client.parseDOM(html, 'h4', attrs={'style': 'text-indent:10px;'})[0]
        year = int(re.search(r'(\d{4})', year).group(1))
        name = client.parseDOM(html, 'h2')[0]

        result = client.parseDOM(html, 'div', attrs={'style': 'margin:20px 0px 20px 0px;'})[0]

        episodes = re.findall(r'onclick="loadEpisode(.*?)">(.*?)</button>', result)

        if str('text-justify') in html:
            plot = client.parseDOM(html, 'p', attrs={'class': 'text-justify'})[0]
        else:
            plot = control.lang(30085)

        info = client.parseDOM(html, 'h4', attrs={'style': 'text-indent:10px;'})
        genre = info[1].lstrip(u'Είδος:').strip()

        dictionary = {
            u'Ιαν': '01', u'Φεβ': '02', u'Μάρ': '03',
            u'Απρ': '04', u'Μάι': '05', u'Ιούν': '06',
            u'Ιούλ': '07', 'Αύγ': '08', u'Σεπ': '09',
            u'Οκτ': '10', u'Νοέ': '11', u'Δεκ': '12'
        }

        for eid, title in episodes:

            link = re.search(r'\'([\w-]+)\', \'(\w{1,2})\'', eid)
            link = EPISODE.format(link.group(1), link.group(2))

            if '\'n\')' in eid:
                group = '1bynumber'
                if '.' in title:
                    try:
                        season = title.partition('.')[0]
                    except Exception:
                        season = title.partition('.')[0][0]
                    episode_num = title.partition('.')[2]
                    title = control.lang(30067) + ' ' + season + '.' + episode_num
                else:
                    title = control.lang(30067) + ' ' + title
            elif '\'d\')' in eid:
                group = '2bydate'
                row = result.split(eid)[0]
                y = re.findall(r'<h4.+?bold.+?(\d{4})', row, re.U)[-1]
                m = re.findall(r'width:50px..?>(.+?)<', row, re.U)[-1]
                m = dictionary[m]
                prefix = '0' + title if len(title) == 1 else title
                title = prefix + '-' + m + '-' + y
            else:
                group = '3bytitle'

            self.list.append(
                {
                    'label': name + SEPARATOR + title, 'title': name + ' - ' + title, 'url': link, 'group': group,
                    'name': name, 'image': image, 'plot': plot, 'year': year,
                    'genre': genre
                }
            )

        return self.list
예제 #25
0
    def main_menu(self):

        self.list = [
            {
                'title': 'NET Toronto',
                'action': 'play',
                'isFolder': 'False',
                'url': variables.NETV_Toronto_url,
                'icon': 'NET_Toronto.png',
                'boolean': control.setting('netv') == 'true',
                'plot': control.lang(30006),
                'genre': 'Live'
            },
            # {
            #     'title': 'Life HD',
            #     'action': 'play', 'isFolder': 'False',
            #     'url': variables.Life_url,
            #     'icon': 'LIFEHD.png',
            #     'boolean': control.setting('life') == 'true',
            #     'plot': control.lang(30008), 'genre': 'Pseudo-Live'
            # }
            # ,
            {
                'title': 'CANNALI Music',
                'action': 'play',
                'isFolder': 'False',
                'url': variables.Cannali_url,
                'icon': 'CANNALI.png',
                'boolean': control.setting('cannali') == 'true',
                'plot': control.lang(30007),
                'genre': 'Live'
            },
            {
                'title': 'BCI 24 News',
                'url': variables.NEWS_url,
                'icon': 'BCI_24_News.png',
                'action': 'play',
                'isFolder': 'False',
                'boolean': control.setting('news') == 'true',
                'genre': 'Live'
            },
            {
                'title': 'Food Channel',
                'url': variables.FOOD_url,
                'icon': 'FOOD.png',
                'action': 'play',
                'isFolder': 'False',
                'boolean': control.setting('food') == 'true',
                'genre': 'Live'
            },
            {
                'title': 'CETN (Canadian Ethnic TV Network)',
                'url': variables.CETN_url,
                'icon': 'CETN.png',
                'action': 'play',
                'isFolder': 'False',
                'boolean': control.setting('cetn') == 'true',
                'genre': 'Live'
            },
            {
                'title': 'Health Channel',
                'url': variables.HEALTH_url,
                'icon': 'HEALTH.png',
                'action': 'play',
                'isFolder': 'False',
                'boolean': control.setting('health') == 'true',
                'genre': 'Live'
            },
            {
                'title': 'RIK Sat',
                'url': variables.RIK_url,
                'icon': 'RIK_SAT.png',
                'action': 'play',
                'isFolder': 'False',
                'boolean': control.setting('rik') == 'true',
                'genre': 'Live'
            },
            {
                'title': 'RIK Proto',
                'url': variables.RIK_proto,
                'icon': 'RIK_PROTO.png',
                'action': 'play',
                'isFolder': 'False',
                'boolean': control.setting('rik') == 'true',
                'genre': 'Live'
            },
            {
                'title': 'RIK Trito',
                'url': variables.RIK_trito,
                'icon': 'RIK_TRITO.png',
                'action': 'play',
                'isFolder': 'False',
                'boolean': control.setting('rik') == 'true',
                'genre': 'Live'
            }
            # ,
            # {
            #     'title': 'Energy',
            #     'action': 'play', 'isFolder': 'False',
            #     'url': 'energy',
            #     'icon': 'ENERGY.png',
            #     'boolean': control.setting('energy') == 'true',
            #     'plot': control.lang(30041), 'genre': 'Live'
            # }
            ,
            {
                'title':
                'Youtube Channel',
                'action':
                'youtube_channel',
                'isFolder':
                'False',
                'isPlayable':
                'False',
                'url':
                'plugin://plugin.video.youtube/channel/{0}/?addon_id={1}'.
                format(variables.YT_Channel, control.addonInfo('id')),
                'boolean':
                control.setting('youtube') == 'true'
            },
            {
                'title': 'Radio Melodia Toronto',
                'url': variables.Melodia_url,
                'action': 'play',
                'isFolder': 'False',
                'icon': 'RADIO_MELODIA_TORONTO.png',
                'boolean': control.setting('melodia') == 'true',
                'plot': control.lang(30009),
                'genre': 'Live',
                'infotype': 'music'
            }
            # ,
            # {
            #     'title': 'Canadian Ethnic Web Radio',
            #     'url': variables.CEWR_url,
            #     'action': 'play', 'isFolder': 'False',
            #     'icon': 'CANADIAN_ETHNIC_WEB_RADIO.jpg',
            #     'boolean': control.setting('cewr') == 'true',
            #     'genre': 'Live',
            #     'infotype': 'music'
            # }
            ,
            {
                'title': 'Voice Life & Style Mag',
                'action': 'mags_addon',
                'isFolder': 'False',
                'isPlayable': 'False',
                'image': magazine_list()[1],
                'boolean': control.setting('voice') == 'true'
            },
            {
                'title': 'BCI Media Website',
                'url': 'https://www.bcimedia.net/',
                'action': 'open_url',
                'isFolder': 'False',
                'isPlayable': 'False',
                'boolean': control.setting('external') == 'true'
            }
        ]

        self.menu = [i for i in self.list if i['boolean']]

        self.menu.append({
            'title': control.lang(30001),
            'action': 'settings',
            'icon': 'settings.png',
            'isFolder': 'False',
            'isPlayable': 'False'
        })

        directory.add(self.menu, argv=self.argv, content='movies')
예제 #26
0
def gm_source_maker(url):

    if 'episode' in url:

        html = client.request(url=url.partition('?')[0], post=url.partition('?')[2])

    else:

        html = client.request(url)

    html = py2_uni(html)

    if 'episode' in url:

        episodes = re.findall(r'''(?:<a.+?/a>|<p.+?/p>)''', html)

        hl = []
        links = []

        for episode in episodes:

            if '<p style="margin-top:0px; margin-bottom:4px;">' in episode:

                host = client.parseDOM(episode, 'p')[0].split('<')[0]

                pts = client.parseDOM(episode, 'a')
                lks = client.parseDOM(episode, 'a', ret='href')

                for p in pts:
                    hl.append(u''.join([host, control.lang(30225), p]))

                for link_ in lks:
                    links.append(link_)

            else:

                pts = client.parseDOM(episode, 'a')
                lks = client.parseDOM(episode, 'a', ret='href')

                for p in pts:
                    hl.append(p)

                for link_ in lks:
                    links.append(link_)

        links = [urljoin(GM_BASE, link) for link in links]
        hosts = [host.replace(u'προβολή στο ', control.lang(30015)) for host in hl]

        links_list = list(zip(hosts, links))

        data = {'links': links_list}

        if '<p class="text-muted text-justify">' in html:

            plot = client.parseDOM(html, 'p')[0]
            data.update({'plot': plot})

        return data

    elif 'view' in url:

        link = client.parseDOM(html, 'a', ret='href', attrs={"class": "btn btn-primary"})[0]
        host = urlparse(link).netloc.replace('www.', '').capitalize()

        return {'links': [(''.join([control.lang(30015), host]), link)]}

    elif 'music' in url:

        title = re.search(r'''search\(['"](.+?)['"]\)''', html).group(1)

        link = list_search(query=title, limit=1)[0]['url']

        return {'links': [(''.join([control.lang(30015), 'Youtube']), link)]}

    else:

        try:

            info = client.parseDOM(html, 'h4', attrs={'style': 'text-indent:10px;'})

            if ',' in info[1]:

                genre = info[1].lstrip(u'Είδος:').split(',')
                genre = random.choice(genre)
                genre = genre.strip()

            else:

                genre = info[1].lstrip(u'Είδος:').strip()

        except:

            genre = control.lang(30147)

        div_tags = parsers.itertags(html, 'div')

        buttons = [i.text for i in list(div_tags) if 'margin: 0px 0px 10px 10px;' in i.attributes.get('style', '')]

        links = []
        hl = []

        for button in buttons:

            if 'btn btn-primary dropdown-toggle' in button:

                host = client.stripTags(client.parseDOM(button, 'button')[0]).strip()
                parts = client.parseDOM(button, 'li')

                for part in parts:

                    part_ = client.parseDOM(part, 'a')[0]
                    link = client.parseDOM(part, 'a', ret='href')[0]
                    hl.append(', '.join([host, part_]))
                    links.append(link)

            else:

                host = client.parseDOM(button, 'a')[0]
                link = client.parseDOM(button, 'a', ret='href')[0]

                hl.append(host)
                links.append(link)

        links = [urljoin(GM_BASE, link) for link in links]

        hosts = [host.replace(
            u'προβολή στο ', control.lang(30015)
        ).replace(
            u'προβολή σε ', control.lang(30015)
        ).replace(
            u'μέρος ', control.lang(30225)
        ) for host in hl]

        links_list = list(zip(hosts, links))

        data = {'links': links_list, 'genre': genre}

        if 'text-align: justify' in html:
            plot = client.parseDOM(html, 'p', attrs={'style': 'text-align: justify'})[0]
        elif 'text-justify' in html:
            plot = client.parseDOM(html, 'p', attrs={'class': 'text-justify'})[0]
        else:
            plot = control.lang(30085)

        data.update({'plot': plot})

        imdb_code = re.search(r'imdb.+?/title/([\w]+?)/', html)
        if imdb_code:
            code = imdb_code.group(1)
            data.update({'code': code})

        return data
예제 #27
0
def keymap_edit():

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

    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>'

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

        map_left = control.lang(30031)
        map_right = control.lang(30032)
        map_middle = control.lang(30033)
        map_up = control.lang(30034)
        map_down = control.lang(30035)

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

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

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

        if not indices:

            control.infoDialog(control.lang(30036))

        else:

            finalized = []

            for i in indices:
                finalized.append(strings[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)')

            control.infoDialog(control.lang(30015))

    yes = control.yesnoDialog(control.lang(30028), control.lang(30014))

    if yes:

        if control.exists(location):

            choices = [control.lang(30038), control.lang(30039)]

            choice = control.selectDialog(choices)

            if choice == 0:

                seq()

            elif choice == 1:

                control.deleteFile(location)
                control.execute('Action(reloadkeymaps)')

            else:

                control.infoDialog(control.lang(30016))

        else:

            seq()

    else:

        control.infoDialog(control.lang(30016))
예제 #28
0
    def search(self, action, query=None):

        if query is not None:
            choice = list(QUERY_MAP.keys()).index(query.split(',')[0])
            str_input = query.split(',')[1]
        else:
            choice = None
            str_input = None

        if choice is None:

            choices = [
                control.lang(30096),
                control.lang(30031),
                control.lang(30030),
                control.lang(30063),
                control.lang(30068),
                control.lang(30097),
                control.lang(30101)
            ]

            choice = control.selectDialog(heading=control.lang(30095),
                                          list=choices)

        if choice == 0:

            if str_input is None:

                str_input = control.dialog.input(
                    heading=control.lang(30095).partition(' ')[0] +
                    control.lang(30100) + control.lang(30096))

                if not str_input:
                    return

            add_to_history(u"Live TV Channel,{0}".format(str_input))

            if action == 'add_to_history':
                control.refresh()
                return

            self.list = live.Indexer().live_tv(zapping=False,
                                               query=str_input.lower())

            if query:
                directory.add(self.list)
            else:
                directory.run_builtin(action='generic_index',
                                      query=quote_plus(json.dumps(self.list)))

        elif choice == 1:

            if str_input is None:

                str_input = control.dialog.input(
                    heading=control.lang(30095).partition(' ')[0] +
                    control.lang(30100) + control.lang(30031))

                try:
                    str_input = cleantitle.strip_accents(
                        str_input.decode('utf-8'))
                except (UnicodeEncodeError, UnicodeDecodeError,
                        AttributeError):
                    str_input = cleantitle.strip_accents(str_input)

            if not str_input:
                return

            add_to_history(u"Movie,{0}".format(str_input))

            if action == 'add_to_history':
                control.refresh()
                return

            self.list = self.wrapper(str_input, 'movies')

            if query:
                directory.add(self.list, content='movies')
            else:
                directory.run_builtin(action='generic_index',
                                      query=quote_plus(json.dumps(self.list)))

        elif choice == 2:

            if str_input is None:

                str_input = control.dialog.input(
                    heading=control.lang(30095).partition(' ')[0] +
                    control.lang(30100) + control.lang(30030))

                if not str_input:

                    return

                try:
                    str_input = cleantitle.strip_accents(
                        str_input.decode('utf-8'))
                except (UnicodeEncodeError, UnicodeDecodeError,
                        AttributeError):
                    str_input = cleantitle.strip_accents(str_input)

            add_to_history(u"TV Serie,{0}".format(str_input))

            if action == 'add_to_history':
                control.refresh()
                return

            self.list = self.wrapper(str_input, 'series')

            if query is not None:
                directory.add(self.list, content='tvshows')
            else:
                directory.run_builtin(action='generic_index',
                                      query=quote_plus(json.dumps(self.list)))

        elif choice == 3:

            if not str_input:

                str_input = control.dialog.input(
                    heading=control.lang(30095).partition(' ')[0] +
                    control.lang(30100) + control.lang(30063))

                if not str_input:

                    return

                try:
                    str_input = cleantitle.strip_accents(
                        str_input.decode('utf-8'))
                except (UnicodeEncodeError, UnicodeDecodeError,
                        AttributeError):
                    str_input = cleantitle.strip_accents(str_input)

            add_to_history(u"TV Show,{0}".format(str_input))

            if action == 'add_to_history':
                control.refresh()
                return

            self.list = self.wrapper(str_input, 'shows')

            if query is not None:
                directory.add(self.list, content='tvshows')
            else:
                directory.run_builtin(action='generic_index',
                                      query=quote_plus(json.dumps(self.list)))

        elif choice == 4:

            if str_input is None:

                str_input = control.dialog.input(
                    heading=control.lang(30095).partition(' ')[0] +
                    control.lang(30100) + control.lang(30068))

                if not str_input:

                    return

                try:
                    str_input = cleantitle.strip_accents(
                        str_input.decode('utf-8'))
                except (UnicodeEncodeError, UnicodeDecodeError,
                        AttributeError):
                    str_input = cleantitle.strip_accents(str_input)

            add_to_history(u"Theater,{0}".format(str_input))

            if action == 'add_to_history':
                control.refresh()
                return

            self.list = self.wrapper(str_input, 'theater')

            if query is not None:
                directory.add(self.list, content='movies')
            else:
                directory.run_builtin(action='generic_index',
                                      query=quote_plus(json.dumps(self.list)))

        elif choice == 5:

            if str_input is None:
                str_input = control.dialog.input(
                    heading=control.lang(30095).partition(' ')[0] +
                    control.lang(30100) + control.lang(30097))

                if not str_input:

                    return

                try:
                    str_input = cleantitle.strip_accents(
                        str_input.decode('utf-8'))
                except (UnicodeEncodeError, UnicodeDecodeError,
                        AttributeError):
                    str_input = cleantitle.strip_accents(str_input)

            add_to_history(u"Cartoon,{0}".format(str_input))

            if action == 'add_to_history':
                control.refresh()
                return

            self.list = self.wrapper(str_input, 'animation')

            if query is not None:
                directory.add(self.list, content='tvshows')
            else:
                directory.run_builtin(action='generic_index',
                                      query=quote_plus(json.dumps(self.list)))

        elif choice == 6:

            if str_input is None:

                str_input = control.dialog.input(
                    heading=control.lang(30095).partition(' ')[0] +
                    control.lang(30100) + control.lang(30101))

                if not str_input:

                    return

                try:
                    str_input = cleantitle.strip_accents(
                        str_input.decode('utf-8'))
                except (UnicodeEncodeError, UnicodeDecodeError,
                        AttributeError):
                    str_input = cleantitle.strip_accents(str_input)

            add_to_history(u"Person,{0}".format(str_input))

            if action == 'add_to_history':
                control.refresh()
                return

            self.list = self.wrapper(str_input, 'person')

            if query is not None:
                directory.add(self.list)
            else:
                directory.run_builtin(action='generic_index',
                                      query=quote_plus(json.dumps(self.list)))

        else:

            control.close_all()
예제 #29
0
def check_updates():

    control.execute('UpdateAddonRepos')
    control.okDialog(heading=control.addonInfo('name'),
                     line1=control.lang(30402))
예제 #30
0
    def matches(self, query=None):

        def appender(events):

            _list = []

            for event in events:

                event_name = event['event_name']

                match_centers = event['match_centers']

                for match in match_centers:

                    team_a = match['team_a']
                    team_b = match['team_b']
                    score_a = str(match['score_a'])
                    score_b = str(match['score_b'])
                    desc = match['desc']
                    if not desc:
                        desc = control.lang(30011)
                    _date = str(match['date'])
                    url = ''.join([self.base_link, match['alias_url']])

                    title = ''.join(
                        [
                            event_name, u': ', team_a, u' - ', team_b, u'[CR]', control.lang(30004),
                            score_a, u' - ', score_b, u' (', desc, u' | ', _date, u')'
                        ]
                    )

                    data = {'title': title, 'url': url, 'action': 'event'}

                    _list.append(data)

            return _list

        if not query:
            date_ = bytes(date.today()).replace('-', '')
        else:
            date_ = bytes(query)

        result = client.request(self.matches_link.format(date=date_), output='json')

        if not result['events'] and not result['friendly']:

            self.list = [{'title': control.lang(30008), 'action': 'matches'}]

        else:

            if result['events']:

                self.list.extend(appender(result['events']))

            if result['friendly']:

                self.list.extend(appender(result['friendly']))

        previous_date = {
            'title': control.lang(30007),
            'action': 'matches',
            'query': bytes(int(date_) - 1)
        }

        next_date = {
            'title': control.lang(30006),
            'action': 'matches',
            'query': bytes(int(date_) + 1)
        }

        add_date = {
            'title': control.lang(30005),
            'action': 'add_date',
            'isFolder': 'False',
            'isPlayable': 'False'
        }

        go_to_root = {
            'title': control.lang(30012),
            'action': 'go_to_root',
            'isFolder': 'False',
            'isPlayable': 'False'
        }

        self.list.insert(0, previous_date)
        self.list.append(next_date)
        self.list.append(add_date)
        self.list.append(go_to_root)

        directory.add(self.list)