Beispiel #1
0
def key_map_setup():

    if control.exists(
            control.transPath(
                'special://home/addons/plugin.video.faros.on-air/addon.xml')):
        script_location = 'special://home/addons/plugin.video.faros.on-air/resources/lib/key_nav.py'
    else:
        script_location = 'special://xbmc/addons/plugin.video.faros.on-air/resources/lib/key_nav.py'

    xml = '''<keymap>
    <global>
        <keyboard>
            <key id="browser_back">RunScript({0})</key>
            <key id="61448">RunScript({0})</key>
            <key id="backspace">RunScript({0})</key>
            <key id="browser_home">noop</key>
            <key id="homepage">noop</key>
            <key id="escape">noop</key>
            <key id="61467">noop</key>
        </keyboard>
    </global>
</keymap> 
    '''.format(script_location)

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

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

    with open(control.join(location, 'farosonair.xml'), mode='w') as f:
        f.write(xml)

    control.execute('Action(reloadkeymaps)')
Beispiel #2
0
def presentation():

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

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

        control.makeFiles(path)

        control.idle()

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

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

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

    control.execute('SlideShow({0},pause)'.format(path))
Beispiel #3
0
def weather_set_up():

    addon_settings = '''<settings>
    <setting id="Location1" value="Paphos (CY)" />
    <setting id="Location1id" value="841589" />
    <setting id="Location2" value="" />
    <setting id="Location2id" value="" />
    <setting id="Location3" value="" />
    <setting id="Location3id" value="" />
    <setting id="Location4" value="" />
    <setting id="Location4id" value="" />
    <setting id="Location5" value="" />
    <setting id="Location5id" value="" />
</settings>
'''

    location = control.transPath('special://profile/addon_data/weather.yahoo')
    if not control.exists(location):
        control.makeFile(location)

    with open(control.join(location, 'settings.xml'), mode='w') as f:
        f.write(addon_settings)

    set_a_setting('weather.addon', 'weather.yahoo')
    control.execute('Weather.Refresh')
def clear_history(file_=history_file):

    if control.exists(file_):

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

    control.infoDialog(control.lang(30011))
    refresh()
Beispiel #5
0
def pinned_from_file(file_):

    if control.exists(file_):

        with open(file_, 'r') as f:
            text = [i.rstrip('\n') for i in f.readlines()][::-1]

        return text

    else:

        return ['']
Beispiel #6
0
def pin_to_file(file_, txt):

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

    if not txt:
        return

    if txt not in pinned_from_file(file_):

        with open(file_, 'a') as f:
            f.writelines(txt + '\n')
def read_from_history(file_=history_file):
    """
    Reads from history file which is stored in plain text, line by line
    :return: List
    """

    if control.exists(file_):

        with open(file_, 'r') as f:
            text = [i.rstrip('\n') for i in f.readlines()][::-1]

        return text

    else:

        return ''
def add_to_history(file_=history_file):

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

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

    if not txt:
        return

    if txt not in read_from_history():

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

        trim_history(file_)
        refresh()
Beispiel #9
0
def checkpoint():

    if control.setting('first_time') == 'true' and 'CEMC' in control.infoLabel(
            'System.FriendlyName') and control.exists(
                control.transPath(
                    'special://xbmc/addons/plugin.video.faros.on-air/')):

        set_a_setting('locale.keyboardlayouts',
                      ['English QWERTY', 'Greek QWERTY'])

        weather_set_up()
        youtube_set_up()
        key_map_setup()

        if not bool_skin_setting('AutoScroll'):
            set_skin_setting('AutoScroll')
        if bool_skin_setting('HomeMenuNoMusicButton'):
            set_skin_setting('HomeMenuNoMusicButton', 'false')
        if bool_skin_setting('HomeMenuNoPVRRadioButton'):
            set_skin_setting('HomeMenuNoPVRRadioButton', 'false')
        if bool_skin_setting('HomeMenuNoPVRTVButton'):
            set_skin_setting('HomeMenuNoPVRTVButton', 'false')
        if bool_skin_setting('HomeMenuNoWeatherButton'):
            set_skin_setting('HomeMenuNoWeatherButton', 'false')
        if bool_skin_setting('HomeMenuNoPicturesButton'):
            set_skin_setting('HomeMenuNoWeatherButton', 'false')
        if not bool_skin_setting('homepageWeatherinfo'):
            set_skin_setting('homepageWeatherinfo')
        if not bool_skin_setting('RemoveFloorGraphics'):
            set_skin_setting('RemoveFloorGraphics')
        if not bool_skin_setting('HomepageHideSearchButton'):
            set_skin_setting('HomepageHideSearchButton')
        if not bool_skin_setting('ViewTypesSimplicity'):
            set_skin_setting('ViewTypesSimplicity')
        if not bool_skin_setting('HomepageHideSearchButton'):
            set_skin_setting('HomepageHideSearchButton')

        # lang_choice()
        # control.okDialog(heading=control.addonInfo('name'), line1=control.lang(30024))

        control.setSetting('first_time', 'false')

    else:
        pass
Beispiel #10
0
def read_from_history():
    """
    Reads from history file which is stored in plain text, line by line
    :return: List
    """

    if control.exists(HISTORY):

        if is_py3:
            f = open(HISTORY, 'r', encoding='utf-8')
        else:
            f = codecs.open(HISTORY, 'r', encoding='utf-8')
        text = [i.rstrip('\n') for i in f.readlines()][::-1]

        f.close()

        return text

    else:

        return
Beispiel #11
0
def download_media(url,
                   path,
                   file_name,
                   initiate_int='',
                   completion_int='',
                   exception_int='',
                   progress=None):

    PROGRESS = enum(OFF=0, WINDOW=1, BACKGROUND=2)

    try:
        if progress is None:
            progress = int(control.setting('progress_dialog'))

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

        if isinstance(initiate_int, int):
            line1 = control.lang(initiate_int).format(file_name)
        else:
            line1 = 'Downloading {0}'.format(file_name)

        with control.ProgressDialog(control.addonInfo('name'),
                                    line1,
                                    background=background,
                                    active=active) as pd:

            try:
                headers = dict([
                    item.split('=') for item in (url.split('|')[1]).split('&')
                ])
                for key in headers:
                    headers[key] = unquote(headers[key])
            except:
                headers = {}

            if 'User-Agent' not in headers:
                headers['User-Agent'] = cache.get(randomagent, 12)

            request = urllib2.Request(url.split('|')[0], headers=headers)
            response = urllib2.urlopen(request)

            if 'Content-Length' in response.info():
                content_length = int(response.info()['Content-Length'])
            else:
                content_length = 0

            file_name += '.' + get_extension(url, response)
            full_path = control.join(path, file_name)
            log_debug('Downloading: %s -> %s' % (url, full_path))

            path = control.transPath(control.legalfilename(path))

            try:
                control.makeFiles(path)
            except Exception as e:
                log_debug('Path Create Failed: %s (%s)' % (e, path))

            from os import sep

            if not path.endswith(sep):
                path += sep
            if not control.exists(path):
                raise Exception('Failed to create dir')

            file_desc = control.openFile(full_path, 'w')
            total_len = 0
            cancel = False
            while 1:
                data = response.read(512 * 1024)
                if not data:
                    break

                if pd.is_canceled():
                    cancel = True
                    break

                total_len += len(data)
                if not file_desc.write(data):
                    raise Exception('Failed to write file')

                percent_progress = total_len * 100 / content_length if content_length > 0 else 0
                log_debug('Position : {0} / {1} = {2}%'.format(
                    total_len, content_length, percent_progress))
                pd.update(percent_progress)

            file_desc.close()

        if not cancel:

            if isinstance(completion_int, int):
                control.infoDialog(
                    control.lang(completion_int).format(file_name))
            else:
                control.infoDialog(
                    'Download_complete for file name {0}'.format(file_name))

            log_debug('Download Complete: {0} -> {1}'.format(url, full_path))

    except Exception as e:

        log_debug('Error ({0}) during download: {1} -> {2}'.format(
            str(e), url, file_name))
        if isinstance(exception_int, int):
            control.infoDialog(
                control.lang(exception_int).format(str(e), file_name))
        else:
            control.infoDialog(
                'Download_complete for file name {0}'.format(file_name))
Beispiel #12
0
    def download(self, path, url):

        try:

            url = re.findall(r'/(\d+)/', url + '/', re.I)[-1]
            url = ''.join([self.download_link, '/getp.php?id={0}'.format(url)])
            url = client.request(url,
                                 output='geturl',
                                 timeout=control.setting('timeout'))

            req = Request(url)
            req.add_header('User-Agent', randomagent())
            opener = urlopen(req)
            data = opener.read()
            zip_file = zipfile.ZipFile(BytesIO(data))
            opener.close()
            files = zip_file.namelist()
            files = [i for i in files if i.startswith('subs/')]

            srt = [i for i in files if i.endswith(('.srt', '.sub'))]
            archive = [i for i in files if i.endswith(('.rar', '.zip'))]

            if len(srt) > 0:

                if len(srt) > 1:
                    srt = multichoice(srt)
                else:
                    srt = srt[0]

                result = zip_file.open(srt).read()

                subtitle = basename(srt)

                try:
                    subtitle = control.join(path, subtitle.decode('utf-8'))
                except Exception:
                    subtitle = control.join(path, subtitle)

                with open(subtitle, 'wb') as subFile:
                    subFile.write(result)

                return subtitle

            elif len(archive) > 0:

                if len(archive) > 1:
                    archive = multichoice(archive)
                else:
                    archive = archive[0]

                result = zip_file.open(archive).read()

                f = control.join(path, os_split(url)[1])

                with open(f, 'wb') as subFile:
                    subFile.write(result)

                dirs, files = control.listDir(path)

                if len(files) == 0:
                    return

                if zipfile.is_zipfile(f):

                    zipped = zipfile.ZipFile(f)
                    zipped.extractall(path)

                if not zipfile.is_zipfile(f):

                    if control.infoLabel('System.Platform.Windows'):
                        uri = "rar://{0}/".format(quote(f))
                    else:
                        uri = "rar://{0}/".format(quote_plus(f))

                    dirs, files = control.listDir(uri)

                else:

                    dirs, files = control.listDir(path)

                if dirs and not zipfile.is_zipfile(f):

                    for dir in dirs:

                        _dirs, _files = control.listDir(control.join(uri, dir))

                        [files.append(control.join(dir, i)) for i in _files]

                        if _dirs:

                            for _dir in _dirs:

                                _dir = control.join(_dir, dir)

                                __dirs, __files = control.listDir(
                                    control.join(uri, _dir))

                                [
                                    files.append(control.join(_dir, i))
                                    for i in __files
                                ]

                filenames = [i for i in files if i.endswith(('.srt', '.sub'))]

                filename = multichoice(filenames)

                try:

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

                except Exception:

                    pass

                if not control.exists(control.join(
                        path,
                        os_split(filename)[0])) and not zipfile.is_zipfile(f):
                    control.makeFiles(control.join(path,
                                                   os_split(filename)[0]))

                subtitle = control.join(path, filename)

                if not zipfile.is_zipfile(f):

                    with closing(control.openFile(uri + filename)) 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')))

                fileparts = os_split(subtitle)[1].split('.')
                # noinspection PyTypeChecker
                result = control.join(
                    os_split(subtitle)[0],
                    'subtitles.' + fileparts[len(fileparts) - 1])

                control.rename(subtitle, result)

                return result

        except Exception as e:

            _, __, tb = sys.exc_info()

            print(traceback.print_tb(tb))

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

            return
Beispiel #13
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))
Beispiel #14
0
    def download(path, url):

        try:

            result = client.request(url)

            f = control.join(path, os_split(url)[1])

            with open(f, 'wb') as subFile:
                subFile.write(result)

            dirs, files = control.listDir(path)

            if len(files) == 0:
                return

            if not f.lower().endswith('.rar'):

                try:
                    zipped = zipfile.ZipFile(f)
                    zipped.extractall(path)
                except Exception:
                    control.execute('Extract("{0}","{0}")'.format(f, path))

            if f.lower().endswith('.rar'):

                if control.infoLabel('System.Platform.Windows'):
                    uri = "rar://{0}/".format(quote(f))
                else:
                    uri = "rar://{0}/".format(quote_plus(f))

                dirs, files = control.listDir(uri)

            else:

                dirs, files = control.listDir(path)

            if dirs and f.lower().endswith('.rar'):

                for dir in dirs:

                    _dirs, _files = control.listDir(control.join(uri, dir))

                    [files.append(control.join(dir, i)) for i in _files]

                    if _dirs:

                        for _dir in _dirs:
                            _dir = control.join(_dir, dir)

                            __dirs, __files = control.listDir(
                                control.join(uri, _dir))

                            [
                                files.append(control.join(_dir, i))
                                for i in __files
                            ]

            filenames = [i for i in files if i.endswith(('.srt', '.sub'))]

            if len(filenames) == 1:
                filename = filenames[0]
            else:
                filename = multichoice(filenames)

            try:

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

            except Exception:

                pass

            if not control.exists(control.join(
                    path,
                    os_split(filename)[0])) and f.lower().endswith('.rar'):
                control.makeFiles(control.join(path, os_split(filename)[0]))

            subtitle = control.join(path, filename)

            if f.lower().endswith('.rar'):

                content = openFile(uri + filename).read()

                with open(subtitle, 'wb') as subFile:
                    subFile.write(content)

            fileparts = os_split(subtitle)[1].split('.')
            result = control.join(
                os_split(subtitle)[0],
                'subtitles.' + fileparts[len(fileparts) - 1])

            rename(subtitle, result)

            return result

        except Exception as e:

            log.log(
                'Subzxyz subtitle download failed for the following reason: ' +
                str(e))

            return
    def download(self, path, url):

        # try:

        url = re.findall('/(\d+)/', url + '/', re.I)[-1]
        url = 'http://www.greeksubtitles.info/getp.php?id={0}'.format(url)
        url = client.request(url, output='geturl')

        data = urlopen(url, timeout=20).read()
        zip_file = zipfile.ZipFile(StringIO(data))
        files = zip_file.namelist()
        files = [i for i in files if i.startswith('subs/')]

        srt = [i for i in files if i.endswith(('.srt', '.sub'))]
        archive = [i for i in files if i.endswith(('.rar', '.zip'))]

        if len(srt) > 0:

            if len(srt) > 1:
                srt = multichoice(srt)
            else:
                srt = srt[0]

            result = zip_file.open(srt).read()

            subtitle = basename(srt)

            try:
                subtitle = control.join(path, subtitle.decode('utf-8'))
            except Exception:
                subtitle = control.join(path, subtitle)

            with open(subtitle, 'wb') as subFile:
                subFile.write(result)

            return subtitle

        elif len(archive) > 0:

            if len(archive) > 1:
                archive = multichoice(archive)
            else:
                archive = archive[0]

            result = zip_file.open(archive).read()

            f = control.join(path, os_split(url)[1])

            with open(f, 'wb') as subFile:
                subFile.write(result)

            dirs, files = control.listDir(path)

            if len(files) == 0:
                return

            if zipfile.is_zipfile(f):

                # try:
                #     zipped = zipfile.ZipFile(f)
                #     zipped.extractall(path)
                # except Exception:
                control.execute('Extract("{0}","{0}")'.format(f, path))

            if not zipfile.is_zipfile(f):

                if control.infoLabel('System.Platform.Windows'):
                    uri = "rar://{0}/".format(quote(f))
                else:
                    uri = "rar://{0}/".format(quote_plus(f))

                dirs, files = control.listDir(uri)

            else:

                dirs, files = control.listDir(path)

            if dirs and not zipfile.is_zipfile(f):

                for dir in dirs:

                    _dirs, _files = control.listDir(control.join(uri, dir))

                    [files.append(control.join(dir, i)) for i in _files]

                    if _dirs:

                        for _dir in _dirs:

                            _dir = control.join(_dir, dir)

                            __dirs, __files = control.listDir(
                                control.join(uri, _dir))

                            [
                                files.append(control.join(_dir, i))
                                for i in __files
                            ]

            filenames = [i for i in files if i.endswith(('.srt', '.sub'))]

            filename = multichoice(filenames)

            try:

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

            except Exception:

                pass

            if not control.exists(control.join(
                    path,
                    os_split(filename)[0])) and not zipfile.is_zipfile(f):
                control.makeFiles(control.join(path, os_split(filename)[0]))

            subtitle = control.join(path, filename)

            if not zipfile.is_zipfile(f):

                content = openFile(uri + filename).read()

                with open(subtitle, 'wb') as subFile:
                    subFile.write(content)

            fileparts = os_split(subtitle)[1].split('.')
            result = control.join(
                os_split(subtitle)[0],
                'subtitles.' + fileparts[len(fileparts) - 1])

            rename(subtitle, result)

            return result