def onAVStarted(self):
        self._up_next = None
        self._callback = None
        self._playlist = None

        if self.isPlayingVideo():
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        else:
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)

        up_next = get_kodi_string('_slyguy_play_next')
        if up_next:
            set_kodi_string('_slyguy_play_next')
            up_next = json.loads(up_next)
            if up_next['playing_file'] == self.getPlayingFile():
                if up_next['next_file']:
                    self._playlist.remove(up_next['next_file'])
                    self._playlist.add(up_next['next_file'],
                                       index=self._playlist.getposition() + 1)

                if up_next['time']:
                    self._up_next = up_next

        callback = get_kodi_string('_slyguy_play_callback')
        if callback:
            set_kodi_string('_slyguy_play_callback')
            callback = json.loads(callback)
            if callback['playing_file'] == self.getPlayingFile(
            ) and callback['callback']:
                self._callback = callback

        if self._up_next or self._callback:
            self._thread = Thread(target=self.playback,
                                  args=(self.getPlayingFile(), ))
            self._thread.start()
Beispiel #2
0
    def _get_url(self, method):
        url = self.path.lstrip('/').strip('\\')
        log.debug('{} IN: {}'.format(method, url))

        self._headers = {}
        for header in self.headers:
            if header.lower() not in REMOVE_IN_HEADERS:
                self._headers[header.lower()] = self.headers[header]

        length = int(self._headers.get('content-length', 0))
        self._post_data = self.rfile.read(length) if length else None

        self._session = PROXY_GLOBAL['session']

        try:
            proxy_data = json.loads(get_kodi_string('_slyguy_quality'))
            if self._session.get('session_id') != proxy_data['session_id']:
                self._session = {}

            self._session.update(proxy_data)
            set_kodi_string('_slyguy_quality', '')
        except:
            pass

        PROXY_GLOBAL['session'] = self._session

        url = self._session.get('path_subs', {}).get(url) or url

        if url.lower().startswith('plugin'):
            url = self._update_urls(url, self._plugin_request(url))

        return url
Beispiel #3
0
    def onAVStarted(self):
        try:
            play_data = json.loads(get_kodi_string('_slyguy_play_data'))
        except:
            return

        set_kodi_string('_slyguy_play_data')

        self._callback = None
        self._play_skips = []
        self._playing_file = self.getPlayingFile()

        if play_data['playing_file'] != self._playing_file:
            return

        if self.isPlayingVideo():
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        else:
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)

        play_skips = play_data['skips']

        if play_data['next']['next_file']:
            self._playlist.remove(play_data['next']['next_file'])
            self._playlist.add(play_data['next']['next_file'],
                               index=self._playlist.getposition() + 1)

        #legacy
        if play_data['next']['time']:
            play_skips.append({'from': play_data['next']['time'], 'to': 0})

        for skip in play_skips:
            if not skip.get('to'):
                skip['to'] = int(self.getTotalTime()) + 1
            else:
                if skip['to'] < 0:
                    self.seekTime(self.getTotalTime() + skip['to'] - 3)
                    continue

                skip['to'] -= 3

            if not skip.get('from'):
                continue

            self._play_skips.append(skip)

        ## Workaround for suspect IA bug: https://github.com/xbmc/inputstream.adaptive/issues/821
        # if int(self.getTime()) < 0:
        #     self.seekTime(0)

        if play_data['callback']['callback']:
            self._callback = play_data['callback']

        if self._callback or self._play_skips:
            self._thread = Thread(target=self.playback)
            self._thread.start()
Beispiel #4
0
def _reload_service():
    database.close()

    with gui.progress(_.RELOAD_SERVICE, percent=100) as progress:
        set_kodi_string('_gpio_reload', '1')

        for i in range(5):
            xbmc.sleep(1000)
            if not get_kodi_string('_gpio_reload'):
                break
Beispiel #5
0
    def onAVStarted(self):
        self._up_next = None
        self._callback = None
        self._playlist = None

        if self.isPlayingVideo():
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        else:
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)

        up_next = get_kodi_string('_slyguy_play_next')
        if up_next:
            set_kodi_string('_slyguy_play_next')
            up_next = json.loads(up_next)
            if up_next['playing_file'] == self.getPlayingFile():
                if up_next['next_file']:
                    self._playlist.remove(up_next['next_file'])
                    self._playlist.add(up_next['next_file'], index=self._playlist.getposition()+1)

                if up_next['time']:
                    self._up_next = up_next

        callback = get_kodi_string('_slyguy_play_callback')
        if callback:
            set_kodi_string('_slyguy_play_callback')
            callback = json.loads(callback)
            if callback['playing_file'] == self.getPlayingFile() and callback['callback']:
                self._callback = callback

        if self._up_next or self._callback:
            self._thread = Thread(target=self.playback, args=(self.getPlayingFile(),))
            self._thread.start()

    # def onPlayBackEnded(self):
    #     vid_playlist   = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
    #     music_playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)
    #     position       = vid_playlist.getposition()+1

    #     if (vid_playlist.size() <= 1 or vid_playlist.size() == position) and (music_playlist.size() <= 1 or music_playlist.size() == position):
    #         self.onPlayBackStopped()

    # def onPlayBackStopped(self):
    #     set_kodi_string('_slyguy_last_quality')

    # def onPlayBackStarted(self):
    #     pass

    # def onPlayBackPaused(self):
    #     print("AV PAUSED")

    # def onPlayBackResumed(self):
    #     print("AV RESUME")

    # def onPlayBackError(self):
    #     self.onPlayBackStopped()
Beispiel #6
0
def setup_addon(addon_id, **kwargs):
    if not iptv_is_setup() and not _setup():
        return

    addon, data = merge_info(addon_id)

    if METHOD_PLAYLIST in data:
        playlist, created = Playlist.get_or_create(path=addon_id, defaults={'source_type': Playlist.TYPE_ADDON, 'enabled': True})
        if not playlist.enabled:
            playlist.enabled = True
            playlist.save()

    if METHOD_EPG in data:
        epg, created = EPG.get_or_create(path=addon_id, defaults={'source_type': EPG.TYPE_ADDON, 'enabled': True})
        if not epg.enabled:
            epg.enabled = True
            epg.save()

    set_kodi_string('_iptv_merge_force_run', '1')
    def _get_url(self):
        url = self.path.lstrip('/').strip('\\')

        self._headers = {}
        self._plugin_headers = {}
        for header in self.headers:
            if header.lower() not in REMOVE_IN_HEADERS:
                self._headers[header.lower()] = self.headers[header]

        self._headers['accept-encoding'] = 'gzip, deflate, br'

        length = int(self._headers.get('content-length', 0))
        self._post_data = self.rfile.read(length) if length else None

        self._session = PROXY_GLOBAL['session']

        try:
            proxy_data = json.loads(get_kodi_string('_slyguy_quality'))
            if self._session.get('session_id') != proxy_data['session_id']:
                self._session = {}

            self._session.update(proxy_data)
            set_kodi_string('_slyguy_quality', '')
        except:
            pass

        PROXY_GLOBAL['session'] = self._session

        url = self._session.get('path_subs', {}).get(url) or url

        if url.lower().startswith('plugin'):
            new_url = self._plugin_request(url)

            if url == self._session.get('license_url'):
                self._session['license_url'] = new_url

            url = new_url

        return url
    def onAVStarted(self):
        self._callback = None
        self._play_skips = []
        self._playing_file = self.getPlayingFile()

        if self.isPlayingVideo():
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        else:
            self._playlist = xbmc.PlayList(xbmc.PLAYLIST_MUSIC)

        play_skips = []
        up_next = get_kodi_string('_slyguy_play_next')
        if up_next:
            set_kodi_string('_slyguy_play_next')
            up_next = json.loads(up_next)
            if up_next['playing_file'] == self._playing_file:
                if up_next['next_file']:
                    self._playlist.remove(up_next['next_file'])
                    self._playlist.add(up_next['next_file'],
                                       index=self._playlist.getposition() + 1)

                #legacy
                if up_next['time']:
                    play_skips.append({'from': up_next['time'], 'to': 0})

        _skips = get_kodi_string('_slyguy_play_skips')
        if _skips:
            set_kodi_string('_slyguy_play_skips')
            data = json.loads(_skips)
            if data['playing_file'] == self._playing_file:
                play_skips.extend(data['skips'])

        for skip in play_skips:
            if not skip.get('to'):
                skip['to'] = int(self.getTotalTime()) + 1
            else:
                if skip['to'] < 0:
                    self.seekTime(self.getTotalTime() + skip['to'] - 3)
                    continue

                skip['to'] -= 3

            if not skip.get('from'):
                continue

            self._play_skips.append(skip)

        callback = get_kodi_string('_slyguy_play_callback')
        if callback:
            set_kodi_string('_slyguy_play_callback')
            callback = json.loads(callback)
            if callback['playing_file'] == self._playing_file and callback[
                    'callback']:
                self._callback = callback

        if self._callback or self._play_skips:
            self._thread = Thread(target=self.playback)
            self._thread.start()
Beispiel #9
0
def start():
    http = HTTP()

    monitor = xbmc.Monitor()
    restart_queued = False

    boot_merge = settings.getBool('boot_merge', False)
    set_kodi_string('_iptv_merge_force_run')

    while not monitor.waitForAbort(1):
        http.start() if settings.getBool('http_api', False) else http.stop()

        forced = get_kodi_string('_iptv_merge_force_run') or 0

        if forced or boot_merge or (settings.getBool('auto_merge', True) and time.time() - userdata.get('last_run', 0) > settings.getInt('reload_time_hours', 12) * 3600):
            set_kodi_string('_iptv_merge_force_run', '1')

            url = router.url_for('run_merge', forced=int(forced))
            dirs, files = xbmcvfs.listdir(url)
            result, msg = int(files[0][0]), unquote_plus(files[0][1:])
            if result:
                restart_queued = True

            userdata.set('last_run', int(time.time()))
            set_kodi_string('_iptv_merge_force_run')

        if restart_queued and settings.getBool('restart_pvr', False):
            if forced: progress = gui.progressbg(heading='Reloading IPTV Simple Client')

            if KODI_VERSION > 18:
                restart_queued = False
                try: xbmcaddon.Addon(IPTV_SIMPLE_ID).setSetting('m3uPathType', '0')
                except Exception as e: pass

            elif forced or (not xbmc.getCondVisibility('Pvr.IsPlayingTv') and not xbmc.getCondVisibility('Pvr.IsPlayingRadio')):
                restart_queued = False
                kodi_rpc('Addons.SetAddonEnabled', {'addonid': IPTV_SIMPLE_ID, 'enabled': False})

                wait_delay = 4
                for i in range(wait_delay):
                    if monitor.waitForAbort(1):
                        break
                    if forced: progress.update((i+1)*int(100/wait_delay))

                kodi_rpc('Addons.SetAddonEnabled', {'addonid': IPTV_SIMPLE_ID, 'enabled': True})

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

        boot_merge = False

    http.stop()
Beispiel #10
0
def merge(**kwargs):
    if get_kodi_string('_iptv_merge_force_run'):
        raise PluginError(_.MERGE_IN_PROGRESS)
    else:
        set_kodi_string('_iptv_merge_force_run', '1')
Beispiel #11
0
def _setup():
    addon = get_addon(IPTV_SIMPLE_ID, required=True, install=True)

    with gui.progress(_.SETTING_UP_IPTV) as progress:
        kodi_rpc('Addons.SetAddonEnabled', {'addonid': IPTV_SIMPLE_ID, 'enabled': False})

        output_dir = settings.get('output_dir', '').strip() or ADDON_PROFILE
        playlist_path = os.path.join(output_dir, PLAYLIST_FILE_NAME)
        epg_path = os.path.join(output_dir, EPG_FILE_NAME)

        ## IMPORT ANY CURRENT URL SOURCES ##
        cur_epg_url  = addon.getSetting('epgUrl')
        cur_epg_type = addon.getSetting('epgPathType')
        if cur_epg_url:
            epg = EPG(source_type=EPG.TYPE_URL, path=cur_epg_url, enabled=cur_epg_type == '1')
            try: epg.save()
            except: pass

        cur_m3u_url  = addon.getSetting('m3uUrl')
        cur_m3u_type = addon.getSetting('m3uPathType')
        start_chno = int(addon.getSetting('startNum') or 1)
        #user_agent = addon.getSetting('userAgent')
        if cur_m3u_url:
            playlist = Playlist(source_type=Playlist.TYPE_URL, path=cur_m3u_url, enabled=cur_m3u_type == '1')
            if start_chno != 1:
                playlist.use_start_chno = True
                playlist.start_chno = start_chno

            try: playlist.save()
            except: pass
        ################################

        addon.setSetting('epgPath', epg_path)
        addon.setSetting('m3uPath', playlist_path)
        addon.setSetting('epgUrl', '')
        addon.setSetting('m3uUrl', '')
        addon.setSetting('m3uPathType', '0')
        addon.setSetting('epgPathType', '0')

        monitor = xbmc.Monitor()

        progress.update(30)

        monitor.waitForAbort(2)
        kodi_rpc('Addons.SetAddonEnabled', {'addonid': IPTV_SIMPLE_ID, 'enabled': True})

        progress.update(60)

        monitor.waitForAbort(2)

        progress.update(100)

        set_kodi_setting('epg.futuredaystodisplay', 7)
      #  set_kodi_setting('epg.ignoredbforclient', True)
        set_kodi_setting('pvrmanager.syncchannelgroups', True)
        set_kodi_setting('pvrmanager.preselectplayingchannel', True)
        set_kodi_setting('pvrmanager.backendchannelorder', True)
        set_kodi_setting('pvrmanager.usebackendchannelnumbers', True)

    set_kodi_string('_iptv_merge_force_run', '1')

    gui.ok(_.SETUP_IPTV_COMPLETE)

    return True
    def _quality_select(self, qualities):
        def codec_rank(_codecs):
            highest = -1

            for codec in _codecs:
                for _codec in CODECS:
                    if codec.lower().startswith(
                            _codec[0].lower()) and _codec[1] in CODEC_RANKING:
                        rank = CODEC_RANKING.index(_codec[1])
                        if not highest or rank > highest:
                            highest = rank

            return highest

        def compare(a, b):
            if a['resolution'] and b['resolution']:
                if int(a['resolution'].split('x')[0]) > int(
                        b['resolution'].split('x')[0]):
                    return 1
                elif int(a['resolution'].split('x')[0]) < int(
                        b['resolution'].split('x')[0]):
                    return -1

            # Same resolution - compare codecs
            a_rank = codec_rank(a['codecs'])
            b_rank = codec_rank(b['codecs'])

            if a_rank > b_rank:
                return 1
            elif a_rank < b_rank:
                return -1

            # Same codec rank - compare bandwidth
            if a['bandwidth'] and b['bandwidth']:
                if a['bandwidth'] > b['bandwidth']:
                    return 1
                elif a['bandwidth'] < b['bandwidth']:
                    return -1

            # Same bandwidth - they are equal (could compare framerate)
            return 0

        def _stream_label(stream):
            try:
                fps = _(_.QUALITY_FPS, fps=float(stream['frame_rate']))
            except:
                fps = ''

            codec_string = ''
            for codec in stream['codecs']:
                for _codec in CODECS:
                    if codec.lower().startswith(_codec[0].lower()):
                        codec_string += ' ' + _codec[1]

            return _(_.QUALITY_BITRATE,
                     bandwidth=int((stream['bandwidth'] / 10000.0)) / 100.00,
                     resolution=stream['resolution'],
                     fps=fps,
                     codecs=codec_string.strip()).replace('  ', ' ')

        if self._session.get('selected_quality') is not None:
            if self._session['selected_quality'] in (QUALITY_DISABLED,
                                                     QUALITY_SKIP):
                return None
            else:
                return qualities[self._session['selected_quality']]

        quality_compare = cmp_to_key(compare)

        quality = int(self._session.get('quality', QUALITY_ASK))
        streams = sorted(qualities, key=quality_compare, reverse=True)

        if not streams:
            quality = QUALITY_DISABLED
        elif len(streams) < 2:
            quality = QUALITY_BEST

        if quality == QUALITY_ASK:
            options = []
            options.append([QUALITY_BEST, _.QUALITY_BEST])

            for x in streams:
                options.append([x, _stream_label(x)])

            options.append([QUALITY_LOWEST, _.QUALITY_LOWEST])
            options.append([QUALITY_SKIP, _.QUALITY_SKIP])

            values = [x[0] for x in options]
            labels = [x[1] for x in options]

            default = -1
            if PROXY_GLOBAL['last_quality'] in values:
                default = values.index(PROXY_GLOBAL['last_quality'])
            else:
                options = [streams[-1]]
                for stream in streams:
                    if PROXY_GLOBAL['last_quality'] >= stream['bandwidth']:
                        options.append(stream)

                default = values.index(
                    sorted(options, key=quality_compare, reverse=True)[0])

            index = gui.select(_.PLAYBACK_QUALITY,
                               labels,
                               preselect=default,
                               autoclose=5000)
            if index < 0:
                raise Exit('Cancelled quality select')

            quality = values[index]
            if index != default:
                PROXY_GLOBAL['last_quality'] = quality[
                    'bandwidth'] if quality in qualities else quality
                set_kodi_string('_slyguy_last_quality',
                                PROXY_GLOBAL['last_quality'])

        if quality in (QUALITY_DISABLED, QUALITY_SKIP):
            quality = quality
        elif quality == QUALITY_BEST:
            quality = streams[0]
        elif quality == QUALITY_LOWEST:
            quality = streams[-1]
        elif quality not in streams:
            options = [streams[-1]]
            for stream in streams:
                if quality >= stream['bandwidth']:
                    options.append(stream)
            quality = sorted(options, key=quality_compare, reverse=True)[0]

        if quality in qualities:
            self._session['selected_quality'] = qualities.index(quality)
            return qualities[self._session['selected_quality']]
        else:
            self._session['selected_quality'] = quality
            return None
Beispiel #13
0
    def get_li(self):
        if KODI_VERSION < 18:
            li = xbmcgui.ListItem()
        else:
            li = xbmcgui.ListItem(offscreen=True)

        if self.label:
            li.setLabel(self.label)
            if not self.info.get('plot'):
                self.info['plot'] = self.label

            if not self.info.get('title'):
                self.info['title'] = self.label

        if self.info:
            li.setInfo('video', self.info)

        if self.specialsort:
            li.setProperty('specialsort', self.specialsort)

        if self.video:
            li.addStreamInfo('video', self.video)

        if self.audio:
            li.addStreamInfo('audio', self.audio)

        if self.art:
            defaults = {
                'poster':    'thumb',
                'landscape': 'thumb',
                'icon':      'thumb',
            }

            for key in defaults:
                if key not in self.art:
                    self.art[key] = self.art.get(defaults[key])

            for key in self.art:
                if self.art[key] and self.art[key].lower().startswith('http'):
                    self.art[key] = self.art[key].replace(' ', '%20')

            li.setArt(self.art)

        if self.playable:
            li.setProperty('IsPlayable', 'true')
            if self.path:
                self.path = add_url_args(self.path, _play=1)

        if self.context:
            li.addContextMenuItems(self.context)

        for key in self.properties:
            li.setProperty(key, u'{}'.format(self.properties[key]))

        headers = self.get_url_headers()
        mimetype = self.mimetype

        proxy_path = settings.common_settings.get('proxy_path', 'http://{}:{}/'.format(PROXY_HOST, PROXY_PORT))

        def get_url(url):
            _url = url.lower()

            if _url.startswith('plugin://') or (_url.startswith('http') and self.use_proxy):
                url = u'{}{}'.format(proxy_path, url)

            return url

        if self.inputstream and self.inputstream.check():
            if KODI_VERSION < 19:
                li.setProperty('inputstreamaddon', self.inputstream.addon_id)
            else:
                li.setProperty('inputstream', self.inputstream.addon_id)

            li.setProperty('{}.manifest_type'.format(self.inputstream.addon_id), self.inputstream.manifest_type)
            li.setProperty('{}.license_flags'.format(self.inputstream.addon_id), 'force_secure_decoder')

            if self.inputstream.license_type:
                li.setProperty('{}.license_type'.format(self.inputstream.addon_id), self.inputstream.license_type)

            if headers:
                li.setProperty('{}.stream_headers'.format(self.inputstream.addon_id), headers)

            if self.inputstream.license_key:
                li.setProperty('{}.license_key'.format(self.inputstream.addon_id), u'{url}|Content-Type={content_type}&{headers}|{challenge}|{response}'.format(
                    url = get_url(self.inputstream.license_key),
                    headers = headers,
                    content_type = self.inputstream.content_type,
                    challenge = self.inputstream.challenge,
                    response = self.inputstream.response,
                ))
            elif headers:
                li.setProperty('{}.license_key'.format(self.inputstream.addon_id), u'|{}'.format(headers))

            if self.inputstream.license_data:
                li.setProperty('{}.license_data'.format(self.inputstream.addon_id), self.inputstream.license_data)

            if self.inputstream.mimetype and not mimetype:
                mimetype = self.inputstream.mimetype

            for key in self.inputstream.properties:
                li.setProperty(self.inputstream.addon_id+'.'+key, self.inputstream.properties[key])
        else:
            self.inputstream = None

        def make_sub(url, language='unk', mimetype=''):
            if not url.lower().startswith('http') and not url.lower().startswith('plugin://'):
                return url

            ## using dash, we can embed subs
            if self.inputstream and self.inputstream.manifest_type == 'mpd':
                if mimetype not in ('application/ttml+xml', 'text/vtt') and not url.lower().startswith('plugin://'):
                    ## can't play directly - covert to webvtt
                    url = url_for(ROUTE_WEBVTT, url=url)
                    mimetype = 'text/vtt'

                proxy_data['subtitles'].append([mimetype, language, url])
                return None

            ## only srt or webvtt (text/) supported
            if not mimetype.startswith('text/') and not url.lower().startswith('plugin://'):
                url = url_for(ROUTE_WEBVTT, url=url)
                mimetype = 'text/vtt'

            proxy_url = '{}.srt'.format(language)
            proxy_data['path_subs'][proxy_url] = url

            return u'{}{}'.format(proxy_path, proxy_url)

        if self.path and self.path.lower().startswith('http'):
            if not mimetype:
                parse = urlparse(self.path.lower())
                if parse.path.endswith('.m3u') or parse.path.endswith('.m3u8'):
                    mimetype = 'application/vnd.apple.mpegurl'
                elif parse.path.endswith('.mpd'):
                    mimetype = 'application/dash+xml'
                elif parse.path.endswith('.ism'):
                    mimetype = 'application/vnd.ms-sstr+xml'

            self.path = url_sub(self.path)
            self.path = fix_url(self.path)

            proxy_data = {
                'manifest': self.path,
                'session_id': hash_6(time.time()),
                'audio_whitelist': settings.get('audio_whitelist', ''),
                'subs_whitelist':  settings.get('subs_whitelist', ''),
                'audio_description': str(int(settings.getBool('audio_description', True))),
                'subs_forced': str(int(settings.getBool('subs_forced', True))),
                'subs_non_forced': str(int(settings.getBool('subs_non_forced', True))),
                'subtitles': [],
                'path_subs': {},
                'addon_id': ADDON_ID,
                'quality': QUALITY_DISABLED,
                'manifest_middleware': None,
                'type': None,
            }

            if mimetype == 'application/vnd.apple.mpegurl':
                proxy_data['type'] = 'm3u8'
            elif mimetype == 'application/dash+xml':
                proxy_data['type'] = 'mpd'

            proxy_data.update(self.proxy_data)

            if self.subtitles:
                subs = []
                for sub in self.subtitles:
                    sub = make_sub(*sub)
                    if sub:
                        subs.append(sub)

                li.setSubtitles(list(subs))

            set_kodi_string('_slyguy_quality', json.dumps(proxy_data))

            if proxy_data['manifest_middleware'] or proxy_data['subtitles'] or (proxy_data['quality'] not in (QUALITY_DISABLED, QUALITY_SKIP) and proxy_data['type']):
                self.use_proxy = True

            self.path = get_url(self.path)

            if headers and '|' not in self.path:
                self.path = u'{}|{}'.format(self.path, headers)

        if mimetype:
            li.setMimeType(mimetype)
            li.setContentLookup(False)

        if self.path:
            li.setPath(self.path)

        return li
Beispiel #14
0
def service():
    def setup_buttons():
        log.debug('Setting up buttons')

        try:
            database.connect()

            Button.update(status=Button.Status.INACTIVE,
                          error=None).where(Button.enabled == True).execute()
            Button.update(status=Button.Status.DISABLED,
                          error=None).where(Button.enabled == False).execute()
            btns = list(Button.select().where(Button.enabled == True))

            buttons = []
            for btn in btns:
                if not btn.has_callbacks():
                    continue

                try:
                    button = gpiozero.Button(btn.pin,
                                             pull_up=btn.pull_up,
                                             bounce_time=btn.bounce_time
                                             or None,
                                             hold_time=btn.hold_time,
                                             hold_repeat=btn.hold_repeat)

                    if btn.when_pressed:
                        button.when_pressed = lambda function=btn.when_pressed: callback(
                            function)

                    if btn.when_released:
                        button.when_released = lambda function=btn.when_released: callback(
                            function)

                    if btn.when_held:
                        button.when_held = lambda function=btn.when_held: callback(
                            function)
                except Exception as e:
                    log.exception(e)
                    btn.status = Button.Status.ERROR
                    btn.error = e
                else:
                    btn.status = Button.Status.ACTIVE
                    buttons.append(button)

                btn.save()

            return buttons
        except Exception as e:
            log.debug(e)
            return []
        finally:
            database.close()

    monitor = xbmc.Monitor()

    while not monitor.abortRequested():
        buttons = setup_buttons()

        set_kodi_string('_gpio_reload')
        while not monitor.abortRequested():
            if not monitor.waitForAbort(1) and get_kodi_string('_gpio_reload'):
                break

        for button in buttons:
            button.close()

    gpiozero.Device.pin_factory.close()
Beispiel #15
0
def _setup(check_only=False, reinstall=True, run_merge=True):
    addon = get_addon(IPTV_SIMPLE_ID,
                      required=not check_only,
                      install=not check_only)
    if not addon:
        return False

    output_dir = settings.get('output_dir', '').strip() or ADDON_PROFILE
    playlist_path = os.path.join(output_dir, PLAYLIST_FILE_NAME)
    epg_path = os.path.join(output_dir, EPG_FILE_NAME)

    is_setup = addon.getSetting('m3uPathType') == '0' and addon.getSetting('epgPathType') == '0' \
                and addon.getSetting('m3uPath') == playlist_path and addon.getSetting('epgPath') == epg_path

    if check_only:
        return is_setup

    elif is_setup and not reinstall:
        if run_merge:
            set_kodi_string('_iptv_merge_force_run', '1')

        return True

    ## IMPORT ANY CURRENT URL SOURCES ##
    cur_epg_url = addon.getSetting('epgUrl')
    cur_epg_type = addon.getSetting('epgPathType')
    if cur_epg_url:
        epg = EPG(source_type=EPG.TYPE_URL,
                  path=cur_epg_url,
                  enabled=cur_epg_type == '1')
        try:
            epg.save()
        except:
            pass

    cur_m3u_url = addon.getSetting('m3uUrl')
    cur_m3u_type = addon.getSetting('m3uPathType')
    start_chno = int(addon.getSetting('startNum') or 1)
    #user_agent = addon.getSetting('userAgent')
    if cur_m3u_url:
        playlist = Playlist(source_type=Playlist.TYPE_URL,
                            path=cur_m3u_url,
                            enabled=cur_m3u_type == '1')
        if start_chno != 1:
            playlist.use_start_chno = True
            playlist.start_chno = start_chno

        try:
            playlist.save()
        except:
            pass
    ################################

    addon.setSetting('epgPath', epg_path)
    addon.setSetting('m3uPath', playlist_path)
    addon.setSetting('epgUrl', '')
    addon.setSetting('m3uUrl', '')
    addon.setSetting('m3uPathType', '0')
    addon.setSetting('epgPathType', '0')

    set_kodi_setting('epg.futuredaystodisplay', 7)
    #  set_kodi_setting('epg.ignoredbforclient', True)
    set_kodi_setting('pvrmanager.syncchannelgroups', True)
    set_kodi_setting('pvrmanager.preselectplayingchannel', True)
    set_kodi_setting('pvrmanager.backendchannelorder', True)
    set_kodi_setting('pvrmanager.usebackendchannelnumbers', True)

    if run_merge:
        set_kodi_string('_iptv_merge_force_run', '1')

    gui.ok(_.SETUP_IPTV_COMPLETE)

    return True