def __init__(self):
     Monitor.__init__(self)
     self.update_interval = 24 * 3600  # Every 24 hours
     self.cache_expiry = 30 * 24 * 3600  # One month
     self._auth = AuthApi(kodiutils.get_setting('username'),
                          kodiutils.get_setting('password'),
                          kodiutils.get_tokens_path())
示例#2
0
def autostart():
    """
    Starts the cleaning service.
    """
    cleaner = Cleaner()
    monitor = Monitor()

    service_sleep = 4  # Lower than 4 causes too much stress on resource limited systems such as RPi
    ticker = 0
    delayed_completed = False

    while not monitor.abortRequested():
        if get_setting(service_enabled):
            scan_interval_ticker = get_setting(scan_interval) * 60 / service_sleep
            delayed_start_ticker = get_setting(delayed_start) * 60 / service_sleep

            if delayed_completed and ticker >= scan_interval_ticker:
                results = cleaner.clean_all()
                if results:
                    notify(results)
                ticker = 0
            elif not delayed_completed and ticker >= delayed_start_ticker:
                delayed_completed = True
                results = cleaner.clean_all()
                if results:
                    notify(results)
                ticker = 0

            xbmc.sleep(service_sleep * 1000)
            ticker += 1
        else:
            xbmc.sleep(service_sleep * 1000)

    print("Abort requested. Terminating.")
    return
示例#3
0
def wait_for_metadata(info_hash):
    close_busy_dialog()
    percent = 0
    timeout = get_metadata_timeout()
    start_time = time.time()
    monitor = Monitor()
    progress = DialogProgress()
    progress.create(ADDON_NAME, translate(30237))

    try:
        while not api.torrent_status(info_hash).has_metadata:
            if monitor.waitForAbort(0.5):
                raise PlayError("Abort requested")
            passed_time = time.time() - start_time
            if 0 < timeout:
                if timeout < passed_time:
                    notification(translate(30238))
                    raise PlayError("No metadata after timeout")
                percent = int(100 * passed_time / timeout)
            else:
                percent = 0 if percent == 100 else (percent + 5)
            progress.update(percent)
            if progress.iscanceled():
                raise CanceledError("User canceled metadata", info_hash)
    finally:
        progress.close()
def _skin_widget_call(window_cls):
    """
    Workaround to intercept calls made by the Skin Widgets currently in use.
    Currently, the Skin widgets associated with add-ons are executed at Kodi startup immediately
    without respecting any services needed by the add-ons. This is causing different
    kinds of problems like widgets not loaded, add-on warning message, etc...
    this loop freeze the add-on instance until the service is ready.
    """
    # Note to "Window.IsMedia":
    # All widgets will be either on Home or in a Custom Window, so "Window.IsMedia" will be false
    # When the user is browsing the plugin, Window.IsMedia will be true because video add-ons open
    # in MyVideoNav.xml (which is a Media window)
    # This is not a safe solution, because DEPENDS ON WHICH WINDOW IS OPEN,
    # for example it can fail if you open add-on video browser while widget is still loading.
    # Needed a proper solution by script.skinshortcuts / script.skin.helper.service, and forks
    limit_sec = 10
    if not getCondVisibility("Window.IsMedia"):
        monitor = Monitor()
        sec_elapsed = 0
        while not window_cls.getProperty('nf_service_status') == 'running':
            if sec_elapsed >= limit_sec or monitor.abortRequested() or monitor.waitForAbort(0.5):
                break
            sec_elapsed += 0.5
        debug('Skin widget workaround enabled - time elapsed: {}', sec_elapsed)
        return True
    return False
示例#5
0
def generate_pairing_code():
    monitor = Monitor()
    progress = DialogProgress()
    progress.create(get_string(32000), get_string(32001))
    chromecast = YoutubeCastV1()
    pairing_code = chromecast.pair()

    i = 0

    if PY3:
        progress.update(i,
                        message="{} {}".format(get_string(32002),
                                               pairing_code))
    else:
        progress.update(i, get_string(32002), pairing_code)

    start_time = time.time()
    while not monitor.abortRequested(
    ) and not chromecast.has_client and not progress.iscanceled() and not (
            time.time() - start_time) > (60 * 1):
        i += 10
        if i > 100:
            i = 0

        if PY3:
            progress.update(i,
                            message="{} {}".format(get_string(32002),
                                                   pairing_code))
        else:
            progress.update(i, get_string(32002), pairing_code)

        monitor.waitForAbort(2)
    progress.close()
示例#6
0
 def __init__(self):
     Monitor.__init__(self)
     self.kodi = KodiWrapper()
     self.vtm_go = VtmGo(self.kodi)
     self.vtm_go_auth = VtmGoAuth(self.kodi)
     self.update_interval = 24 * 3600  # Every 24 hours
     self.cache_expiry = 30 * 24 * 3600  # One month
示例#7
0
 def __init__(self, callback):
     self.mgr = callback
     self.doUtils = DownloadUtils().downloadUrl
     self.xbmcplayer = Player()
     self.playqueue = self.mgr.playqueue
     Monitor.__init__(self)
     log.info("Kodi monitor started.")
示例#8
0
 def __init__(self):
     self.xbmcplayer = Player()
     Monitor.__init__(self)
     for playerid in state.PLAYER_STATES:
         state.PLAYER_STATES[playerid] = dict(state.PLAYSTATE)
         state.OLD_PLAYER_STATES[playerid] = dict(state.PLAYSTATE)
     LOG.info("Kodi monitor started.")
示例#9
0
 def __init__(self, callback):
     self.mgr = callback
     self.doUtils = downloadutils.DownloadUtils().downloadUrl
     self.xbmcplayer = Player()
     self.playqueue = self.mgr.playqueue
     Monitor.__init__(self)
     log.info("Kodi monitor started.")
示例#10
0
class UpNextPlayer(Player):
    """Service class for playback monitoring"""
    last_file = None
    track = False

    def __init__(self):
        self.api = Api()
        self.state = State()
        self.monitor = Monitor()
        Player.__init__(self)

    def set_last_file(self, filename):
        self.state.last_file = filename

    def get_last_file(self):
        return self.state.last_file

    def is_tracking(self):
        return self.state.track

    def disable_tracking(self):
        self.state.track = False

    def reset_queue(self):
        if self.state.queued:
            self.api.reset_queue()
            self.state.queued = False

    def onPlayBackStarted(self):  # pylint: disable=invalid-name
        """Will be called when kodi starts playing a file"""
        self.monitor.waitForAbort(5)
        if not getCondVisibility('videoplayer.content(episodes)'):
            return
        self.state.track = True
        self.reset_queue()

    def onPlayBackPaused(self):  # pylint: disable=invalid-name
        self.state.pause = True

    def onPlayBackResumed(self):  # pylint: disable=invalid-name
        self.state.pause = False

    def onPlayBackStopped(self):  # pylint: disable=invalid-name
        """Will be called when user stops playing a file"""
        self.reset_queue()
        self.api.reset_addon_data()
        self.state = State()  # Reset state

    def onPlayBackEnded(self):  # pylint: disable=invalid-name
        """Will be called when Kodi has ended playing a file"""
        self.reset_queue()
        self.api.reset_addon_data()
        self.state = State()  # Reset state

    def onPlayBackError(self):  # pylint: disable=invalid-name
        """Will be called when when playback stops due to an error"""
        self.reset_queue()
        self.api.reset_addon_data()
        self.state = State()  # Reset state
示例#11
0
 def __init__(self, container, sop_url, localport, playerport):
     Monitor.__init__(self)
     self.player = SopCastPlayer()
     self.container = container
     self.localport = localport
     self.playerport = playerport
     self.sop_url = sop_url
     self.image = "sopcast_{0}".format(self.playerport)
     self.running = False
示例#12
0
 def __init__(self):
     ''' VRT Monitor initialisiation '''
     self._resumepoints = ResumePoints()
     self._container = None
     self._playerinfo = None
     self._favorites = None
     self._apihelper = None
     self.init_watching_activity()
     Monitor.__init__(self)
示例#13
0
 def run(self):
     debug('START player bg service')
     m = Monitor()
     while not m.abortRequested():
         sleep(1000)
         try:
             self.periodical_check()
         except:
             debug('player bg service ERR {}'.format(
                 traceback.format_exc()))
     debug('END player bg service')
示例#14
0
    def __init__(self):
        # Initial logging
        LOG.info("======== START %s ========", v.ADDON_NAME)
        LOG.info("Platform: %s", v.PLATFORM)
        LOG.info("KODI Version: %s", v.KODILONGVERSION)
        LOG.info("%s Version: %s", v.ADDON_NAME, v.ADDON_VERSION)
        LOG.info("PKC Direct Paths: %s", settings('useDirectPaths') == "true")
        LOG.info("Number of sync threads: %s", settings('syncThreadNumber'))
        LOG.info("Full sys.argv received: %s", argv)

        # Reset window props for profile switch
        properties = [
            "plex_online", "plex_serverStatus", "plex_onWake",
            "plex_kodiScan",
            "plex_shouldStop", "plex_dbScan",
            "plex_initialScan", "plex_customplayqueue", "plex_playbackProps",
            "pms_token", "plex_token",
            "pms_server", "plex_machineIdentifier", "plex_servername",
            "plex_authenticated", "PlexUserImage", "useDirectPaths",
            "countError", "countUnauthorized",
            "plex_restricteduser", "plex_allows_mediaDeletion",
            "plex_command", "plex_result", "plex_force_transcode_pix"
        ]
        for prop in properties:
            window(prop, clear=True)

        # Clear video nodes properties
        videonodes.VideoNodes().clearProperties()

        # Init some stuff
        state.VERIFY_SSL_CERT = settings('sslverify') == 'true'
        state.SSL_CERT_PATH = settings('sslcert') \
            if settings('sslcert') != 'None' else None
        state.FULL_SYNC_INTERVALL = int(settings('fullSyncInterval')) * 60
        state.SYNC_THREAD_NUMBER = int(settings('syncThreadNumber'))
        state.SYNC_DIALOG = settings('dbSyncIndicator') == 'true'
        state.ENABLE_MUSIC = settings('enableMusic') == 'true'
        state.BACKGROUND_SYNC = settings(
            'enableBackgroundSync') == 'true'
        state.BACKGROUNDSYNC_SAFTYMARGIN = int(
            settings('backgroundsync_saftyMargin'))
        state.REPLACE_SMB_PATH = settings('replaceSMB') == 'true'
        state.REMAP_PATH = settings('remapSMB') == 'true'
        set_replace_paths()
        state.KODI_PLEX_TIME_OFFSET = float(settings('kodiplextimeoffset'))

        window('plex_minDBVersion', value="2.0.0")
        set_webserver()
        self.monitor = Monitor()
        window('plex_kodiProfile',
               value=tryDecode(translatePath("special://profile")))
        window('fetch_pms_item_number',
               value=settings('fetch_pms_item_number'))
        clientinfo.getDeviceId()
示例#15
0
 def __init__(self):
     # Initial logging
     LOG.info("======== START %s ========", v.ADDON_NAME)
     LOG.info("Platform: %s", v.PLATFORM)
     LOG.info("KODI Version: %s", v.KODILONGVERSION)
     LOG.info("%s Version: %s", v.ADDON_NAME, v.ADDON_VERSION)
     LOG.info("PKC Direct Paths: %s", settings('useDirectPaths') == "true")
     LOG.info("Number of sync threads: %s", settings('syncThreadNumber'))
     LOG.info("Full sys.argv received: %s", argv)
     self.monitor = Monitor()
     # Load/Reset PKC entirely - important for user/Kodi profile switch
     initialsetup.reload_pkc()
示例#16
0
 def __init__(self, engine, env, sop_url, localport, playerport):
     Monitor.__init__(self)
     self.player = SopCastPlayer()
     self.env = env
     if type(engine) == list:
         self.engine = engine
     else:
         self.engine = [engine]
     self.localport = localport
     self.playerport = playerport
     self.sop_url = sop_url
     self.running = False
示例#17
0
    def __init__(self, player):
        from xbmcaddon import Addon

        self.player = player
        self.last_tracked_position = None
        self.last_played_file = None
        self.asset_id = None
        self.duration = None
        self.start_tracking = False
        self.addon_path = 'plugin://' + Addon().getAddonInfo('id')
        xbmc_helper().set_addon(Addon())
        xbmc_Monitor.__init__(self)
示例#18
0
def test_popup(window):
    popup = TestPopup(window, addon_path(), 'default', '1080i')
    popup.show()
    step = 0
    wait = 100
    timeout = 10000
    monitor = Monitor()
    while popup and step < timeout and not monitor.abortRequested():
        if popup.pause:
            continue
        sleep(wait)
        popup.update_progress_control(timeout, wait)
        step += wait
示例#19
0
 def __init__(self, engine, env, tvbus_url, access_code, localport,
              playerport):
     Monitor.__init__(self)
     self.player = TvbusPlayer()
     self.env = env
     if type(engine) == list:
         self.engine = engine
     else:
         self.engine = [engine]
     self.localport = localport
     self.playerport = playerport
     self.tvbus_url = tvbus_url
     self.access_code = access_code
     self.running = False
示例#20
0
    def __init__(self):

        logLevel = self.getLogLevel()
        self.monitor = Monitor()

        window('plex_logLevel', value=str(logLevel))
        window('plex_kodiProfile',
               value=tryDecode(translatePath("special://profile")))
        window('plex_context',
               value='true' if settings('enableContext') == "true" else "")
        window('fetch_pms_item_number',
               value=settings('fetch_pms_item_number'))

        # Initial logging
        log.warn("======== START %s ========" % v.ADDON_NAME)
        log.warn("Platform: %s" % v.PLATFORM)
        log.warn("KODI Version: %s" % v.KODILONGVERSION)
        log.warn("%s Version: %s" % (v.ADDON_NAME, v.ADDON_VERSION))
        log.warn("Using plugin paths: %s"
                 % (settings('useDirectPaths') != "true"))
        log.warn("Number of sync threads: %s"
                 % settings('syncThreadNumber'))
        log.warn("Log Level: %s" % logLevel)
        log.warn("Full sys.argv received: %s" % argv)

        # Reset window props for profile switch
        properties = [
            "plex_online", "plex_serverStatus", "plex_onWake",
            "plex_dbCheck", "plex_kodiScan",
            "plex_shouldStop", "plex_dbScan",
            "plex_initialScan", "plex_customplayqueue", "plex_playbackProps",
            "plex_runLibScan", "pms_token", "plex_token",
            "pms_server", "plex_machineIdentifier", "plex_servername",
            "plex_authenticated", "PlexUserImage", "useDirectPaths",
            "kodiplextimeoffset", "countError", "countUnauthorized",
            "plex_restricteduser", "plex_allows_mediaDeletion",
            "plex_command", "plex_result", "plex_force_transcode_pix"
        ]
        for prop in properties:
            window(prop, clear=True)

        # Clear video nodes properties
        videonodes.VideoNodes().clearProperties()

        # Set the minimum database version
        window('plex_minDBVersion', value="1.5.10")
示例#21
0
def play_info_hash(info_hash, timeout=30, buffer=True):
    start_time = time.time()
    monitor = Monitor()
    progress = DialogProgress()
    progress.create(ADDON_NAME, translate(30237))

    try:
        while not api.torrent_status(info_hash).has_metadata:
            if monitor.waitForAbort(0.5):
                raise PlayError("Abort requested")
            passed_time = time.time() - start_time
            if 0 < timeout < passed_time:
                notification(translate(30238))
                raise PlayError("No metadata after timeout")
            progress.update(int(100 * passed_time / timeout))
            if progress.iscanceled():
                raise PlayError("User canceled metadata")
    finally:
        progress.close()

    files = api.files(info_hash, status=False)
    min_candidate_size = get_min_candidate_size() * 1024 * 1024
    candidate_files = [
        f for f in files if is_video(f.path) and f.length >= min_candidate_size
    ]
    if not candidate_files:
        notification(translate(30239))
        raise PlayError("No candidate files found for {}".format(info_hash))
    elif len(candidate_files) == 1:
        chosen_file = candidate_files[0]
    else:
        sort_files(candidate_files)
        chosen_index = Dialog().select(translate(30240),
                                       [f.name for f in candidate_files])
        if chosen_index < 0:
            raise PlayError("User canceled dialog select")
        chosen_file = candidate_files[chosen_index]

    if buffer:
        buffer_and_play(info_hash, chosen_file.id)
    else:
        play(info_hash, chosen_file.id)
示例#22
0
def _check_addon_external_call(window_cls, prop_nf_service_status):
    """Check system to verify if the calls to the add-on are originated externally"""
    # The calls that are made from outside do not respect and do not check whether the services required
    # for the add-on are actually working and operational, causing problems with the execution of the frontend.

    # A clear example are the Skin widgets, that are executed at Kodi startup immediately and this is cause of different
    # kinds of problems like widgets not loaded, add-on warning message, etc...

    # Cases where it can happen:
    # - Calls made by the Skin Widgets, Scripts, Kodi library
    # - Calls made by others Kodi windows (like file browser)
    # - Calls made by other add-ons

    # To try to solve the problem, when the service is not ready a loop will be started to freeze the add-on instance
    # until the service will be ready.

    is_other_plugin_name = getInfoLabel(
        'Container.PluginName') != g.ADDON.getAddonInfo('id')
    limit_sec = 10

    # Note to Kodi boolean condition "Window.IsMedia":
    # All widgets will be either on Home or in a Custom Window, so "Window.IsMedia" will be false
    # When the user is browsing the plugin, Window.IsMedia will be true because video add-ons open
    # in MyVideoNav.xml (which is a Media window)
    # This is not a safe solution, because DEPENDS ON WHICH WINDOW IS OPEN,
    # for example it can fail if you open add-on video browser while widget is still loading.
    # Needed a proper solution by script.skinshortcuts / script.skin.helper.service, and forks
    if is_other_plugin_name or not getCondVisibility("Window.IsMedia"):
        monitor = Monitor()
        sec_elapsed = 0
        while not _get_service_status(
                window_cls, prop_nf_service_status).get('status') == 'running':
            if sec_elapsed >= limit_sec or monitor.abortRequested(
            ) or monitor.waitForAbort(0.5):
                break
            sec_elapsed += 0.5
        debug(
            'Add-on was initiated by an external call - workaround enabled time elapsed {}s',
            sec_elapsed)
        g.IS_ADDON_EXTERNAL_CALL = True
        return True
    return False
示例#23
0
def wait_for_buffering_completion(info_hash, file_id):
    close_busy_dialog()
    info = api.file_info(info_hash, file_id)
    of = translate(30244)
    timeout = get_buffering_timeout()
    last_time = last_done = 0
    start_time = time.time()

    monitor = Monitor()
    progress = DialogProgress()
    progress.create(ADDON_NAME)

    try:
        while True:
            current_time = time.time()
            status = api.file_status(info_hash, file_id)
            if status.buffering_progress >= 100:
                break

            total_done = status.buffering_total * status.buffering_progress / 100
            speed = float(total_done - last_done) / (current_time - last_time)
            last_time = current_time
            last_done = total_done
            progress.update(
                int(status.buffering_progress),
                "{} - {:.2f}%\n{} {} {} - {}/s\n{}\n".format(
                    get_state_string(status.state), status.buffering_progress,
                    sizeof_fmt(total_done), of,
                    sizeof_fmt(status.buffering_total), sizeof_fmt(speed),
                    info.name))

            if progress.iscanceled():
                raise CanceledError("User canceled buffering", info_hash)
            if 0 < timeout < current_time - start_time:
                notification(translate(30236))
                raise PlayError("Buffering timeout reached")
            if monitor.waitForAbort(1):
                raise PlayError("Abort requested")
    finally:
        progress.close()
示例#24
0
def buffer_and_play(info_hash, file_id):
    api.download_file(info_hash, file_id, buffer=True)

    monitor = Monitor()
    progress = DialogProgress()
    progress.create(ADDON_NAME)

    try:
        timeout = get_buffering_timeout()
        start_time = time.time()
        last_time = 0
        last_done = 0
        while True:
            current_time = time.time()
            status = api.file_status(info_hash, file_id)
            if status.buffering_progress >= 100:
                break

            total_done = status.buffering_total * status.buffering_progress / 100
            speed = float(total_done - last_done) / (current_time - last_time)
            last_time = current_time
            last_done = total_done
            progress.update(
                int(status.buffering_progress),
                "{} - {:.2f}%\n{} {} {} - {}/s\n\n".format(
                    get_state_string(status.state), status.buffering_progress,
                    sizeof_fmt(total_done), translate(30244),
                    sizeof_fmt(status.buffering_total), sizeof_fmt(speed)))

            if progress.iscanceled():
                raise PlayError("User canceled buffering")
            if 0 < timeout < current_time - start_time:
                notification(translate(30236))
                raise PlayError("Buffering timeout reached")
            if monitor.waitForAbort(1):
                raise PlayError("Abort requested")
    finally:
        progress.close()

    play(info_hash, file_id)
示例#25
0
 def __init__(self):
     self.api = Api()
     self.state = State()
     self.monitor = Monitor()
     Player.__init__(self)
示例#26
0
 def __init__(self):
     Monitor.__init__(self)
     self._restart_required = False
示例#27
0
    def speedtest(self, share=False, simple=False, src=None, timeout=10):
        self.img_ping.setVisible(True)
        self.img_ping_glow.setVisible(True)
        start_st = [localize(30960)]  # Running Speed Test add-on

        global SHUTDOWN_EVENT, SOURCE  # pylint: disable=global-statement
        SHUTDOWN_EVENT = threading.Event()

        socket.setdefaulttimeout(timeout)

        if src:
            SOURCE = src
            socket.socket = bound_socket

        start_st.append(localize(30961))  # Retrieving speedtest.net configuration
        self.update_textbox(start_st)
        try:
            config = get_config()
        except URLError:
            return False

        start_st.append(localize(30962))  # Retrieving speedtest.net server list
        self.update_textbox(start_st)
        self.img_centertext.setImage(self.image_centertext_testingping)

        servers = closest_servers(config['client'])

        start_st.append(localize(30963, **config['client']))  # Testing from ISP
        self.update_textbox(start_st)

        best = get_best_server(servers)

        start_st.append(localize(30964))  # Selecting best server based on latency
        start_st.append(localize(30965, **best))  # Hosted by: {sponsor}
        start_st.append(localize(30966, **best))  # 'Host server: {host}
        start_st.append(localize(30967, **best))  # City, State: {name}
        start_st.append(localize(30968, **best))  # Country: {country}
        self.update_textbox(start_st)

        # km2mi = 0.62
        # km = '%(d)0.2f ' % best
        # Distance = float(km)
        # miles = Distance * km2mi
        # start_st.append('Distance: %s mi' % miles)
        start_st.append(localize(30969, **best))  # Distance: {d}
        start_st.append(localize(30970, **best))  # Ping: {latency}
        self.update_textbox(start_st)
        self.ping_textbox.setLabel("%.0f" % float(best['latency']))

        self.img_centertext.setImage(' ')
        self.img_ping.setEnabled(False)
        self.img_ping_glow.setEnabled(False)

        sizes = [350, 500, 750, 1000, 1500, 2000, 2500, 3000, 3500, 4000]
        urls = []
        for size in sizes:
            for _ in range(0, 4):
                urls.append('%s/random%sx%s.jpg' % (os.path.dirname(best['url']), size, size))
        self.img_gauge.setVisible(True)
        Monitor().waitForAbort(1)
        self.config_gauge(0)
        self.img_gauge_arrow.setVisible(True)

        start_st.append(localize(30971))  # Testing download speed...
        self.update_textbox(start_st)
        dlspeed = self.download_speed(urls, simple)
        start_st[-1] = localize(30972, speed=dlspeed * 8 / 1000 / 1000)  # Download speed
        self.update_textbox(start_st)
        self.dl_textbox.setLabel('%0.2f' % float(dlspeed * 8 / 1000 / 1000))

        sizesizes = [int(.25 * 1000 * 1000), int(.5 * 1000 * 1000)]
        sizes = []
        for size in sizesizes:
            for _ in range(0, 25):
                sizes.append(size)

        start_st.append(localize(30973))  # Testing upload speed...
        self.update_textbox(start_st)
        ulspeed = self.upload_speed(best['url'], sizes, simple)
        start_st[-1] = localize(30974, speed=ulspeed * 8 / 1000 / 1000)  # Upload speed
        self.update_textbox(start_st)
        self.ul_textbox.setLabel('%.2f' % float(ulspeed * 8 / 1000 / 1000))
        self.config_gauge(0, ulspeed * 8 / 1000 / 1000, time=3000)
        Monitor().waitForAbort(2)

        if share:
            dlspeedk = int(round(dlspeed * 8 / 1000, 0))
            ping = int(round(best['latency'], 0))
            ulspeedk = int(round(ulspeed * 8 / 1000, 0))

            api_data = [
                'download=%s' % dlspeedk,
                'ping=%s' % ping,
                'upload=%s' % ulspeedk,
                'promo=',
                'startmode=%s' % 'pingselect',
                'recommendedserverid=%s' % best['id'],
                'accuracy=%s' % 1,
                'serverid=%s' % best['id'],
                'hash=%s' % md5(('%s-%s-%s-%s' % (ping, ulspeedk, dlspeedk, '297aae72')).encode()).hexdigest()]

            headers = {'Referer': 'https://c.speedtest.net/flash/speedtest.swf'}
            request = build_request('https://www.speedtest.net/api/api.php', data='&'.join(api_data).encode(), headers=headers)
            fdesc = catch_request(request)
            if fdesc is False:
                log(0, 'Could not submit results to speedtest.net')
                return False
            response = fdesc.read()
            code = fdesc.code
            fdesc.close()

            if int(code) != 200:
                log(0, 'Could not submit results to speedtest.net')
                return False

            qsargs = parse_qs(response.decode())  # pylint: disable=deprecated-method
            resultid = qsargs.get('resultid')
            if not resultid or len(resultid) != 1:
                log(0, 'Could not submit results to speedtest.net')
                return False

            global IMAGE_RESULT  # pylint: disable=global-statement
            IMAGE_RESULT = 'https://www.speedtest.net/result/%s.png' % resultid[0]

        return True
示例#28
0
        unresponsive = []
        with self.lights_lock:
            for light, color in self.lights.iteritems():
                try:
                    action(light, color)
                except IOError as ioe:
                    log("removing unresponsive light %s" % light.label, level=LOGWARNING)
                    unresponsive.append(light)
            for light in unresponsive:
                del self.lights[light]

def log(msg, level=LOGNOTICE):
    xbmc.log("lifxbmc - %s" % msg.replace("\0", ""), level=level) # strings returned from lights sometimes have null chars

if __name__ == '__main__':
    monitor = Monitor()
    player = LifxPlayer()
    
    log("inited")    
     
    while not monitor.abortRequested():
        if monitor.waitForAbort(10):
            break
        
        try:
            lifx = LifxLAN()
            for light, color in lifx.get_color_all_lights():
                if len(addon.getSetting("group_filter")) > 0:
                    pass
                if light not in player:
                    log("discovered new light %s" % light.get_label())
示例#29
0
def closest_servers(client, total=False):

    urls = [
        'https://www.speedtest.net/speedtest-servers-static.php',
        'http://c.speedtest.net/speedtest-servers-static.php',
    ]
    errors = []
    servers = {}
    for url in urls:
        try:
            request = build_request(url)
            handler = catch_request(request)
            if handler is False:
                # errors.append('%s' % e)
                raise SpeedtestCliServerListError
            serversxml = []
            while not Monitor().abortRequested():
                serversxml.append(handler.read(10240))
                if not serversxml[-1]:
                    break
            if int(handler.code) != 200:
                handler.close()
                raise SpeedtestCliServerListError
            handler.close()
            try:
                if 'minidom' in sys.modules:
                    root = minidom.parseString(''.join(serversxml))
                    elements = root.getElementsByTagName('server')
                else:
                    root = ElementTree.fromstring(''.encode().join(serversxml))
                    elements = root.iter(tag='server')
            except SyntaxError:
                raise SpeedtestCliServerListError  # pylint: disable=raise-missing-from
            for server in elements:
                try:
                    attrib = server.attrib
                except AttributeError:
                    attrib = dict(list(server.attributes.items()))
                ddd = distance([float(client['lat']), float(client['lon'])], [float(attrib.get('lat')), float(attrib.get('lon'))])
                attrib['d'] = ddd
                if ddd not in servers:
                    servers[ddd] = [attrib]
                else:
                    servers[ddd].append(attrib)
            del root
            del serversxml
            del elements
        except SpeedtestCliServerListError:
            continue
        if servers:
            break
    if not servers:
        log(0, 'Failed to retrieve list of speedtest.net servers: {errors}', errors='\n'.join(errors))
        sys.exit(1)
    closest = []
    for ddd in sorted(servers.keys()):
        for sss in servers[ddd]:
            closest.append(sss)
            if len(closest) == 5 and not total:
                break
        else:
            continue
        break
    del servers
    return closest
示例#30
0
 def __init__(self):
     Monitor.__init__(self)
     self._player = PlayerMonitor()
     self._proxy_thread = None
     self.update_interval = 24 * 3600  # Every 24 hours
     self.cache_expiry = 30 * 24 * 3600  # One month
示例#31
0
    sock.close()
    return port


thumb_req_port = select_unused_port()
ADDON.setSetting('thumbmail_port', str(thumb_req_port))

thumb_req_server = TCPServer(('127.0.0.1', thumb_req_port),
                             ThumbRequestHandler)
thumb_req_server.server_activate()
thumb_req_server.timeout = 1
utils.log('Started 7Plus Thumbnail HTTP server on port {0}'
          .format(thumb_req_port))

if __name__ == '__main__':
    mon = Monitor()

    # start thread for thumbnail HTTP service
    thumb_req_thread = threading.Thread(target=thumb_req_server.serve_forever)
    thumb_req_thread.daemon = True
    thumb_req_thread.start()

    # kill the services if kodi monitor tells us to
    while not mon.abortRequested():
        if mon.waitForAbort(5):
            thumb_req_server.shutdown()
            break

    # Netflix service shutdown sequence
    thumb_req_server.server_close()
    thumb_req_server.socket.close()
示例#32
0
 def __init__(self):
     Monitor.__init__(self)
     self.player = GslugPlayer()
示例#33
0
# server defaults
SocketServer.TCPServer.allow_reuse_address = True

# configure the MSL Server
msl_server = SocketServer.TCPServer(('127.0.0.1', msl_port), MSLHttpRequestHandler)
msl_server.server_activate()
msl_server.timeout = 1

# configure the Netflix Data Server
nd_server = SocketServer.TCPServer(('127.0.0.1', ns_port), NetflixHttpRequestHandler)
nd_server.server_activate()
nd_server.timeout = 1

if __name__ == '__main__':
    monitor = Monitor()

    # start thread for MLS servie
    msl_thread = threading.Thread(target=msl_server.serve_forever)
    msl_thread.daemon = True
    msl_thread.start()

    # start thread for Netflix HTTP service
    nd_thread = threading.Thread(target=nd_server.serve_forever)
    nd_thread.daemon = True
    nd_thread.start()

    # kill the services if kodi monitor tells us to
    while not monitor.abortRequested():
        if monitor.waitForAbort(5):
            msl_server.shutdown()