Esempio n. 1
0
    def run(self):
        """Main loop handling incomming messages"""
        while True:
            message_str = yield self.websocket.read_message()
            if message_str is None:
                logger.debug('Connection closed')
                self.websocket = None
                notification(strings.DISCONNECTED,
                             level='warn',
                             tag='connection')
                break

            try:
                message = json.loads(message_str)
                logger.debug(message)
                data = message['data']

                response_data = self.handler.handler(data)
            except Exception as ex:
                logger.error('Handler failed: {}'.format(str(ex)))
                response_data = {"status": "error", "error": "Unknown error"}

            self.websocket.write_message(
                json.dumps({
                    "correlationId": message['correlationId'],
                    "data": response_data
                }))
Esempio n. 2
0
        def _deco2(request, *args, **kwargs):
            if request.get_cookie('sessionid'):
                session_key = request.get_cookie('sessionid')
            else:
                session_key = request.get_argument('sessionid', '')

            logger.debug('Websocket: session_key: %s' % session_key)
            if session_key:
                session = get_object(Session, session_key=session_key)
                logger.debug('Websocket: session: %s' % session)
                if session and datetime.datetime.now() < session.expire_date:
                    user_id = session.get_decoded().get('_auth_user_id')
                    request.user_id = user_id
                    user = get_object(User, id=user_id)
                    if user:
                        logger.debug(
                            'Websocket: user [ %s ] request websocket' %
                            user.username)
                        request.user = user
                        if role == 'admin':
                            if user.role in ['SU', 'GA']:
                                return func(request, *args, **kwargs)
                            logger.debug(
                                'Websocket: user [ %s ] is not admin.' %
                                user.username)
                        else:
                            return func(request, *args, **kwargs)
                else:
                    logger.debug('Websocket: session expired: %s' %
                                 session_key)
            try:
                request.close()
            except AttributeError:
                pass
            logger.warning('Websocket: Request auth failed.')
Esempio n. 3
0
    def open(self):
        # 获取监控的path
        self.file_path = self.get_argument('file_path', '')
        MonitorHandler.clients.append(self)
        thread = MyThread(target=file_monitor,
                          args=('%s.log' % self.file_path, self))
        MonitorHandler.threads.append(thread)
        self.stream.set_nodelay(True)

        try:
            for t in MonitorHandler.threads:
                if t.is_alive():
                    continue
                t.setDaemon(True)
                t.start()

        except WebSocketClosedError:
            client_index = MonitorHandler.clients.index(self)
            MonitorHandler.threads[client_index].stop()
            MonitorHandler.clients.remove(self)
            MonitorHandler.threads.remove(MonitorHandler.threads[client_index])

        logger.debug(
            "Websocket: Monitor client num: %s, thread num: %s" %
            (len(MonitorHandler.clients), len(MonitorHandler.threads)))
Esempio n. 4
0
    def get_state(self):
        start = time.time()

        volume = kodi_rpc.get_volume()
        muted = kodi_rpc.get_muted()

        player_status = 'stopped'
        player_id = kodi_rpc.get_active_playerid()
        if player_id is not None:
            player_status = 'playing' if kodi_rpc.is_player_playing(
                player_id) else 'paused'

        state = [
            {
                "name": "volume",
                "value": volume
            },
            {
                "name": "muted",
                "value": muted
            },
            {
                "name": "player",
                "value": player_status
            },
        ]

        if utils.cec_available():
            state.append({"name": "power", "value": True})

        logger.debug(u'Fetching state took {} ms'.format(
            int((time.time() - start) * 1000)))

        return state
Esempio n. 5
0
        def _deco2(request, *args, **kwargs):
            if request.get_cookie('sessionid'):
                session_key = request.get_cookie('sessionid')
            else:
                session_key = request.get_argument('sessionid', '')

            logger.debug('Websocket: session_key: %s' % session_key)
            if session_key:
                session = get_object(Session, session_key=session_key)
                logger.debug('Websocket: session: %s' % session)
                if session and datetime.datetime.now() < session.expire_date:
                    user_id = session.get_decoded().get('_auth_user_id')
                    request.user_id = user_id
                    user = get_object(User, id=user_id)
                    if user:
                        logger.debug('Websocket: user [ %s ] request websocket' % user.username)
                        request.user = user
                        if role == 'admin':
                            if user.role in ['SU', 'GA']:
                                return func(request, *args, **kwargs)
                            logger.debug('Websocket: user [ %s ] is not admin.' % user.username)
                        else:
                            return func(request, *args, **kwargs)
                else:
                    logger.debug('Websocket: session expired: %s' % session_key)
            try:
                request.close()
            except AttributeError:
                pass
            logger.warning('Websocket: Request auth failed.')
Esempio n. 6
0
def build_title_index(movies, tvshows):
    start = time.time()

    entities = list(itertools.chain.from_iterable([movies, tvshows]))
    values = [entity['title'] for entity in entities]

    mapped_entities = {}
    for entity in entities:
        value = entity['title']
        if value not in mapped_entities:
            mapped_entities[value] = []

        mapped_entities[value].append(entity)

    logger.debug('Iterating title took {} ms'.format(
        int((time.time() - start) * 1000)))

    start = time.time()
    index = NGram()
    for value in values:
        index.add(value)
    logger.debug('Building title index took {} ms'.format(
        int((time.time() - start) * 1000)))

    return index, mapped_entities
Esempio n. 7
0
def build_cast_index(movies, tvshows, key):
    start = time.time()

    entities = list(itertools.chain.from_iterable([movies, tvshows]))
    values = [[cast[key] for cast in entity['cast']] for entity in entities]
    values = list(set(itertools.chain.from_iterable(values)))

    mapped_entities = {}
    for entity in entities:
        for cast in entity['cast']:
            value = cast[key]
            if value not in mapped_entities:
                mapped_entities[value] = []

            mapped_entities[value].append(entity)

    logger.debug('Iterating {} took {} ms'.format(
        key, int((time.time() - start) * 1000)))

    start = time.time()
    index = NGram()
    for value in values:
        index.add(value)
    logger.debug('Building {} index took {} ms'.format(
        key, int((time.time() - start) * 1000)))

    return index, mapped_entities
Esempio n. 8
0
        def _deco2(request, *args, **kwargs):
            if request.get_cookie("sessionid"):
                session_key = request.get_cookie("sessionid")
            else:
                session_key = request.get_argument("sessionid", "")

            logger.debug("Websocket: session_key: %s" % session_key)
            if session_key:
                session = get_object(Session, session_key=session_key)
                logger.debug("Websocket: session: %s" % session)
                if session and datetime.datetime.now() < session.expire_date:
                    user_id = session.get_decoded().get("_auth_user_id")
                    request.user_id = user_id
                    user = get_object(User, id=user_id)
                    if user:
                        logger.debug("Websocket: user [ %s ] request websocket" % user.username)
                        request.user = user
                        if role == "admin":
                            if user.role in ["SU", "GA"]:
                                return func(request, *args, **kwargs)
                            logger.debug("Websocket: user [ %s ] is not admin." % user.username)
                        else:
                            return func(request, *args, **kwargs)
                else:
                    logger.debug("Websocket: session expired: %s" % session_key)
            try:
                request.close()
            except AttributeError:
                pass
            logger.warning("Websocket: Request auth failed.")
Esempio n. 9
0
    def find_by_filter(self, video_filter):
        start = time.time()

        results = []
        if 'titles' in video_filter and video_filter['titles']:
            results.append(
                self._find_by_values(video_filter['titles'], 'title'))
        if 'collections' in video_filter and video_filter['collections']:
            title_matches = self._find_by_values(video_filter['collections'],
                                                 'title')
            collection_matches = self._find_by_values(
                video_filter['collections'], 'collection')
            results.append(
                list(
                    itertools.chain.from_iterable(
                        [title_matches, collection_matches])))
        if 'genres' in video_filter and video_filter['genres']:
            results.append(
                self._find_by_values(video_filter['genres'], 'genre'))
        if 'actors' in video_filter and video_filter['actors']:
            results.append(
                self._find_by_values(video_filter['actors'], 'actor'))
        if 'roles' in video_filter and video_filter['roles']:
            results.append(self._find_by_values(video_filter['roles'], 'role'))

        entities = cross_section(results)

        if 'mediaType' in video_filter:
            entities = filter_by_media_type(entities,
                                            video_filter['mediaType'])

        logger.debug('Indexed find by filter took {} ms'.format(
            int((time.time() - start) * 1000)))

        return entities
Esempio n. 10
0
def build_collection_index(movies, tvshows):
    start = time.time()

    entities = list(itertools.chain.from_iterable([movies, tvshows]))
    values = list(
        set([
            parse_collection(entity['set']) for entity in entities
            if 'set' in entity and len(entity['set']) > 0
        ]))

    mapped_entities = {}
    for entity in entities:
        if 'set' in entity and entity['set']:
            value = parse_collection(entity['set'])
            if value not in mapped_entities:
                mapped_entities[value] = []

            mapped_entities[value].append(entity)

    logger.debug('Iterating collection took {} ms'.format(
        int((time.time() - start) * 1000)))

    start = time.time()
    index = NGram()
    for value in values:
        index.add(value)
    logger.debug('Building collection index took {} ms'.format(
        int((time.time() - start) * 1000)))

    return index, mapped_entities
Esempio n. 11
0
    def find_and_play(self, video_filter):
        filtered_entities = self.find_entities(video_filter)

        entity = filtering.get_best_match(filtered_entities)
        logger.debug(u'Found Entity {}'.format(str(entity)))

        if not entity:
            notification(strings.NOTHING_FOUND)
            return False

        try:
            if 'movieid' in entity:
                self._set_last_playback_change_at()
                play_movie(entity)
            elif 'tvshowid' in entity:
                season, episode = _pick(video_filter, 'season', 'episode')
                self._set_last_playback_change_at()
                play_tvshow(entity, season, episode)
            else:
                logger.error(
                    'Invalid entity, not "movieid" nor "tvshowid" found')
                return False
        except Exception as error:
            logger.error(u'Failed to play entity: {}'.format(str(error)))

        return True
Esempio n. 12
0
    def open(self):
        # 获取监控的path
        self.file_path = self.get_argument("file_path", "")
        MonitorHandler.clients.append(self)
        thread = MyThread(target=file_monitor, args=("%s.log" % self.file_path, self))
        MonitorHandler.threads.append(thread)
        self.stream.set_nodelay(True)

        try:
            for t in MonitorHandler.threads:
                if t.is_alive():
                    continue
                t.setDaemon(True)
                t.start()

        except WebSocketClosedError:
            client_index = MonitorHandler.clients.index(self)
            MonitorHandler.threads[client_index].stop()
            MonitorHandler.clients.remove(self)
            MonitorHandler.threads.remove(MonitorHandler.threads[client_index])

        logger.debug(
            "Websocket: Monitor client num: %s, thread num: %s"
            % (len(MonitorHandler.clients), len(MonitorHandler.threads))
        )
Esempio n. 13
0
    def open(self):
        logger.debug('Websocket: Open exec request')
        role_name = self.get_argument('role', 'sb')
        self.remote_ip = self.request.headers.get("X-Real-IP")
        if not self.remote_ip:
            self.remote_ip = self.request.remote_ip
        logger.debug('Web执行命令: 请求系统用户 %s' % role_name)
        self.role = get_object(PermRole, name=role_name)
        self.perm = get_group_user_perm(self.user)
        roles = self.perm.get('role').keys()
        if self.role not in roles:
            self.write_message('No perm that role %s' % role_name)
            self.close()
        self.assets = self.perm.get('role').get(self.role).get('asset')

        res = gen_resource({
            'user': self.user,
            'asset': self.assets,
            'role': self.role
        })
        self.runner = MyRunner(res)
        message = '有权限的主机: ' + ', '.join(
            [asset.hostname for asset in self.assets])
        self.__class__.clients.append(self)
        self.write_message(message)
def build_genre_index(movies, tvshows):
    start = time.time()

    entities = list(itertools.chain.from_iterable([movies, tvshows]))
    values = list(
        set(
            itertools.chain.from_iterable(
                [entity['genre'] for entity in entities])))

    mapped_entities = {}
    for entity in entities:
        for genre in entity['genre']:
            if genre not in mapped_entities:
                mapped_entities[genre] = []

            mapped_entities[genre].append(entity)

    logger.debug('Iterating genre took {} ms'.format(
        int((time.time() - start) * 1000)))

    start = time.time()
    index = NGram(items=values, key=lambda x: x.lower())
    logger.debug('Building genre index took {} ms'.format(
        int((time.time() - start) * 1000)))

    return index, mapped_entities
Esempio n. 15
0
 def get(self):
     ws_id = self.get_argument('id')
     Log.objects.filter(id=ws_id).update(is_finished=True)
     for ws in WebTerminalHandler.clients:
         if ws.id == int(ws_id):
             logger.debug("Kill log id %s" % ws_id)
             ws.log.save()
             ws.close()
     logger.debug('Websocket: web terminal client num: %s' % len(WebTerminalHandler.clients))
Esempio n. 16
0
 def update_cache(self):
     if self.library_cache.is_dirty():
         logger.debug('Updating library cache')
         movies = kodi_rpc.get_movies() or []
         tvshows = kodi_rpc.get_tv_shows() or []
         logger.debug(u'Found {} movies and {} tvshows'.format(
             len(movies), len(tvshows)))
         self.library_cache.set_library(movies, tvshows)
         self._update_library_index(movies, tvshows)
Esempio n. 17
0
 def get(self):
     ws_id = self.get_argument('id')
     Log.objects.filter(id=ws_id).update(is_finished=True)
     for ws in WebTerminalHandler.clients:
         if ws.id == int(ws_id):
             logger.debug("Kill log id %s" % ws_id)
             ws.log.save()
             ws.close()
     logger.debug('Websocket: web terminal client num: %s' % len(WebTerminalHandler.clients))
Esempio n. 18
0
    def adjust_volume(self, volume):
        current_volume = kodi_rpc.get_volume()
        logger.debug('Current volume: {}'.format(current_volume))

        new_volume = max(min(current_volume + volume, 100), 0)
        logger.debug('Adjusting volume to: {}'.format(new_volume))

        kodi_rpc.set_volume(new_volume)
        return True
Esempio n. 19
0
 def on_close(self):
     logger.debug('Websocket: Close windows desktop request')
     if self in DesktopHandler.clients:
         DesktopHandler.clients.remove(self)
     try:
         self.log.is_finished = True
         self.log.end_time = timezone.now()
         self.log.save()
         self.close()
     except AttributeError:
         pass
Esempio n. 20
0
    def start(self):
        """Start IO loop and try to connect to the server"""
        self.ioloop.make_current()

        self.connect()
        self.periodic.start()
        self.ioloop.call_later(1, self.periodic_callback)
        logger.debug('Starting IOLoop')
        self.ioloop.start()
        logger.debug('IOLoop ended')
        IOLoop.clear_current()
Esempio n. 21
0
    def on_close(self):
        # 客户端主动关闭
        # self.close()

        logger.debug("Websocket: Monitor client close request")
        try:
            client_index = MonitorHandler.clients.index(self)
            MonitorHandler.clients.remove(self)
            MonitorHandler.threads.remove(MonitorHandler.threads[client_index])
        except ValueError:
            pass
Esempio n. 22
0
    def on_close(self):
        # 客户端主动关闭
        # self.close()

        logger.debug("Websocket: Monitor client close request")
        try:
            client_index = MonitorHandler.clients.index(self)
            MonitorHandler.clients.remove(self)
            MonitorHandler.threads.remove(MonitorHandler.threads[client_index])
        except ValueError:
            pass
Esempio n. 23
0
    def handler(self, data):
        logger.debug(u'handler data: {}'.format(str(data)))
        response_data = {'status': 'ok'}
        if data['type'] == 'command':
            if data['commandType'] == 'searchAndPlay':
                self.search_and_play_handler(data.get('filter', {}))
            elif data['commandType'] == 'searchAndDisplay':
                self.search_and_display_handler(data.get('filter', {}))
            elif data['commandType'] == 'next':
                self.next_handler()
            elif data['commandType'] == 'previous':
                self.previous_handler()
            elif data['commandType'] == 'startOver':
                self.start_over_handler()
            elif data['commandType'] == 'pause':
                self.pause_handler()
            elif data['commandType'] == 'play' or data[
                    'commandType'] == 'resume':
                self.resume_handler()
            elif data['commandType'] == 'stop':
                self.stop_handler()
            elif data['commandType'] == 'rewind':
                self.rewind_handler()
            elif data['commandType'] == 'fastForward':
                self.fastforward_handler()
            elif data['commandType'] == 'seek':
                response_data = self.seek_handler(data.get('deltaPosition', 0))
            elif data['commandType'] == 'setVolume':
                self.set_volume_handler(data.get('volume', 0))
            elif data['commandType'] == 'adjustVolume':
                self.adjust_volume_handler(data.get('volume', 0))
            elif data['commandType'] == 'setMute':
                self.set_mute_handler(data.get('mute', False))
            elif data['commandType'] == 'turnOn' and utils.cec_available():
                self.turnon_handler()
            elif data['commandType'] == 'turnOff' and utils.cec_available():
                self.turnoff_handler()
            else:
                response_data = {'status': 'error', 'error': 'unknown_command'}
        elif data['type'] == 'capabilities' or data[
                'type'] == 'alexa_capabilities':
            response_data = {
                "status": "ok",
                "capabilities": get_alexa_capabilities()
            }
        elif data['type'] == 'state':
            response_data = {"status": "ok", "state": self.kodi.get_state()}
        else:
            response_data = {'status': 'error', 'error': 'unknown_command'}

        logger.debug(u'handler response_data: {}'.format(str(response_data)))

        return response_data
Esempio n. 24
0
def main():
    logger.debug(u'argv: {}'.format(sys.argv[2][1:]))
    logger.debug(u'args: {}'.format(str(__args__)))

    entities = __args__.get('entities', [''])[0].split('x')
    total_items = len(entities)

    logger.debug(u'entities: {}'.format(str(entities)))

    if not entities:
        xbmcplugin.addDirectoryItem(__handle__, '', xbmcgui.ListItem(strings.NO_ITEMS_FOUND), isFolder=False)

    for entity in entities:
        entity_type = entity[:1]
        entity_id = entity[1:]

        if not entity_id:
            continue

        entity_id = int(entity_id)

        if entity_type == 'm':
            details = kodi_rpc.get_movie_details(entity_id)
            logger.debug(details)

            label = details.get('label', 'N/A')
            plot = details.get('plot', 'N/A')
            url = details.get('file', '')
            fanart = details.get('fanart')
            thumbnail = details.get('thumbnail')

            item = xbmcgui.ListItem(label)
            item.setProperty('IsPlayable', 'true')
            item.setInfo('video', {"plot": plot})
            if fanart:
                item.setArt({"fanart": fanart})
            if thumbnail:
                item.setArt({"thumbnail": thumbnail, "poster": thumbnail})

            xbmcplugin.addDirectoryItem(__handle__, url, item, totalItems=total_items)
        elif entity_type == 't':
            details = kodi_rpc.get_tvshow_details(entity_id)
            logger.debug(details)

            label = details.get('label', 'N/A')
            plot = details.get('plot', 'N/A')

            item = xbmcgui.ListItem(label)
            item.setInfo('video', {"plot": plot})

            xbmcplugin.addDirectoryItem(__handle__, '', item, totalItems=total_items)

    xbmcplugin.endOfDirectory(__handle__)
Esempio n. 25
0
 def on_close(self):
     # 客户端主动关闭
     # self.close()
     logger.debug("Websocket: Monitor client close request")
     client_index = LogMonitorHandler.clients.index(self)
     #try:
     #LogMonitorHandler.threads[client_index].stop()
     #except Exception as e:
     #logger.debug("Websocket: LogMonitorHandler stop threads error: %s" % str(e))
     LogMonitorHandler.clients.remove(self)
     LogMonitorHandler.threads.remove(
         LogMonitorHandler.threads[client_index])
Esempio n. 26
0
    def periodic_callback(self):
        """Periodic callback"""
        logger.debug('periodic_callback')
        if self.websocket is None:
            self.connect()
        else:
            self.websocket.write_message(json.dumps({"ping": "pong"}))

        try:
            self.kodi.update_cache()
        except Exception as ex:
            logger.error('Failed to update Kodi library: {}'.format(str(ex)))
Esempio n. 27
0
def filter_entities(video_filter, entities):
    if not entities:
        return []

    entities = [(entity, 100) for entity in entities]

    for filter_type, filter_function in FILTERS:
        if filter_type in video_filter and video_filter[filter_type]:
            entities = filter_function(entities, video_filter[filter_type])

    logger.debug(str([(entity['title'], entity['genre'], score) for entity, score in entities]))

    return entities
Esempio n. 28
0
def play_tvshow(tvshow, season, episode):
    logger.debug('Playing tv show: {}, season: {}, episode: {}'.format(
        tvshow['title'], season, episode))

    if season and episode:
        episode_id = kodi_rpc.get_episodeid(tvshow['tvshowid'], int(season),
                                            int(episode))
    else:
        episode_id = kodi_rpc.get_next_unwatched_episode(tvshow['tvshowid'])

    if episode_id:
        logger.debug('Playing episodeid: {}'.format(episode_id))
        play_episodeid(episode_id)
Esempio n. 29
0
    def _find_by(self, filter_value, value_type):
        index = self.compose_index[value_type]['ix']
        value_map = self.compose_index[value_type]['map']
        threshold = self.compose_index[value_type]['threshold']

        similar_values = index.search(strip_accents(filter_value).lower())
        similar_values = [(value, score) for value, score in similar_values if score > threshold]
        logger.debug(similar_values)

        matched_entities = [(value_map[value], score) for value, score in similar_values]
        matched_entities = [[(entity, score) for entity in entities] for entities, score in matched_entities]
        matched_entities = list(itertools.chain.from_iterable(matched_entities))

        return matched_entities
Esempio n. 30
0
    def connect(self):
        """Connect to the server and update connection to websocket"""
        email = __addon__.getSetting('email')
        secret = __addon__.getSetting('secret')
        if not email or not secret:
            logger.debug('Email and/or secret not defined, not connecting')
            return

        logger.debug('trying to connect')
        try:
            request = HTTPRequest(self.url,
                                  auth_username=email,
                                  auth_password=secret)

            self.websocket = yield websocket_connect(request)
        except Exception as ex:
            logger.debug('connection error: {}'.format(str(ex)))
            self.websocket = None
            notification(strings.FAILED_TO_CONNECT,
                         level='error',
                         tag='connection')
        else:
            logger.debug('Connected')
            self.connected = True
            notification(strings.CONNECTED, tag='connection')
            self.run()
Esempio n. 31
0
 def on_close(self):
     logger.debug('Websocket: Close request')
     if self in WebTerminalHandler.clients:
         WebTerminalHandler.clients.remove(self)
     try:
         self.log_file_f.write('End time is %s' % datetime.datetime.now())
         self.log.is_finished = True
         self.log.end_time = datetime.datetime.now()
         self.log.save()
         self.log_time_f.close()
         self.ssh.close()
         self.close()
     except AttributeError:
         pass
Esempio n. 32
0
 def on_close(self):
     logger.debug('Websocket: Close request')
     if self in WebTerminalHandler.clients:
         WebTerminalHandler.clients.remove(self)
     try:
         self.log_file_f.write('End time is %s' % datetime.datetime.now())
         self.log.is_finished = True
         self.log.end_time = datetime.datetime.now()
         self.log.save()
         self.log_time_f.close()
         self.ssh.close()
         self.close()
     except AttributeError:
         pass
Esempio n. 33
0
    def open(self):
        # 获取监控的path
        self.file_path = self.get_argument('file_path', '')
        logger.debug("Websocket: LogMonitorHandler file_path : %s" %
                     (self.file_path))
        LogMonitorHandler.clients.append(self)
        thread = MyThread(target=file_monitor, args=(self.file_path, self))
        LogMonitorHandler.threads.append(thread)
        logger.debug("Websocket: LogMonitorHandler : %s" %
                     (LogMonitorHandler.threads))
        try:
            for t in LogMonitorHandler.threads:
                if t.is_alive():
                    continue
                t.setDaemon(True)
                t.start()

        except WebSocketClosedError as e:
            client_index = LogMonitorHandler.clients.index(self)
            #LogMonitorHandler.threads[client_index].stop()
            LogMonitorHandler.clients.remove(self)
            LogMonitorHandler.threads.remove(
                LogMonitorHandler.threads[client_index])
            logger.debug("Websocket: LogMonitorHandler client error: %s" %
                         str(e))

        logger.debug(
            "Websocket: LogMonitorHandler client num: %s, thread num: %s" %
            (len(LogMonitorHandler.clients), len(LogMonitorHandler.threads)))
Esempio n. 34
0
    def run_cmd(self, command, pattern):
        self.runner.run('shell', command, pattern=pattern)
        newline_pattern = re.compile(r'\n')
        for k, v in self.runner.results.items():
            for host, output in v.items():
                output = newline_pattern.sub('<br />', output)
                logger.debug(output)
                if k == 'ok':
                    header = "<span style='color: green'>[ %s => %s]</span>\n" % (host, 'Ok')
                else:
                    header = "<span style='color: red'>[ %s => %s]</span>\n" % (host, 'failed')
                self.write_message(header)
                self.write_message(output)

        self.write_message('\n~o~ Task finished ~o~\n')
Esempio n. 35
0
    def run_cmd(self, command, pattern):
        self.runner.run('shell', command, pattern=pattern)
        newline_pattern = re.compile(r'\n')
        for k, v in self.runner.results.items():
            for host, output in v.items():
                output = newline_pattern.sub('<br />', output)
                logger.debug(output)
                if k == 'ok':
                    header = "<span style='color: green'>[ %s => %s]</span>\n" % (host, 'Ok')
                else:
                    header = "<span style='color: red'>[ %s => %s]</span>\n" % (host, 'failed')
                self.write_message(header)
                self.write_message(output)

        self.write_message('\n~o~ Task finished ~o~\n')
Esempio n. 36
0
    def find_and_display(self, video_filter):
        filtered_entities = self.find_entities(video_filter)

        if not filtered_entities:
            notification(strings.NOTHING_FOUND)
            return False

        best_matches = filtering.get_best_matches(filtered_entities, 10)

        display_entities = get_display_entities(best_matches)

        logger.debug('display_entities: {}'.format(str(display_entities)))

        kodi_rpc.execute_addon({"entities": display_entities})

        return True
Esempio n. 37
0
    def open(self):
        logger.debug('Websocket: Open exec request')
        role_name = self.get_argument('role', 'sb')
        self.remote_ip = self.request.remote_ip
        logger.debug('Web执行命令: 请求系统用户 %s' % role_name)
        self.role = get_object(PermRole, name=role_name)
        self.perm = get_group_user_perm(self.user)
        roles = self.perm.get('role').keys()
        if self.role not in roles:
            self.write_message('No perm that role %s' % role_name)
            self.close()
        self.assets = self.perm.get('role').get(self.role).get('asset')

        res = gen_resource({'user': self.user, 'asset': self.assets, 'role': self.role})
        self.runner = MyRunner(res)
        message = '有权限的主机: ' + ', '.join([asset.hostname for asset in self.assets])
        self.__class__.clients.append(self)
        self.write_message(message)
Esempio n. 38
0
    def next_item(self):
        logger.debug('Next item, current_item: {}'.format(
            str(self.current_item)))
        if not self.current_item:
            return False

        if 'tvshowid' in self.current_item:
            tvshow_id, season, episode = _pick(self.current_item, 'tvshowid',
                                               'season', 'episode')

            if tvshow_id and season and episode:
                next_episode_id = get_next_episode_id(tvshow_id, season,
                                                      episode)
                if next_episode_id:
                    play_episodeid(next_episode_id)
                    return True

        return False
Esempio n. 39
0
    def open(self):
        logger.debug("Websocket: Open exec request")
        role_name = self.get_argument("role", "sb")
        self.remote_ip = self.request.headers.get("X-Real-IP")
        if not self.remote_ip:
            self.remote_ip = self.request.remote_ip
        logger.debug("Web执行命令: 请求系统用户 %s" % role_name)
        self.role = get_object(PermRole, name=role_name)
        self.perm = get_group_user_perm(self.user)
        roles = self.perm.get("role").keys()
        if self.role not in roles:
            self.write_message("No perm that role %s" % role_name)
            self.close()
        self.assets = self.perm.get("role").get(self.role).get("asset")

        res = gen_resource({"user": self.user, "asset": self.assets, "role": self.role})
        self.runner = MyRunner(res)
        message = "有权限的主机: " + ", ".join([asset.hostname for asset in self.assets])
        self.__class__.clients.append(self)
        self.write_message(message)
Esempio n. 40
0
    def open(self):
        logger.debug("Websocket: Open request")
        role_name = self.get_argument("role", "sb")
        asset_id = self.get_argument("id", 9999)
        asset = get_object(Asset, id=asset_id)
        self.termlog = TermLogRecorder(User.objects.get(id=self.user_id))
        if asset:
            roles = user_have_perm(self.user, asset)
            logger.debug(roles)
            logger.debug("系统用户: %s" % role_name)
            login_role = ""
            for role in roles:
                if role.name == role_name:
                    login_role = role
                    break
            if not login_role:
                logger.warning(
                    "Websocket: Not that Role %s for Host: %s User: %s "
                    % (role_name, asset.hostname, self.user.username)
                )
                self.close()
                return
        else:
            logger.warning("Websocket: No that Host: %s User: %s " % (asset_id, self.user.username))
            self.close()
            return
        logger.debug(
            "Websocket: request web terminal Host: %s User: %s Role: %s"
            % (asset.hostname, self.user.username, login_role.name)
        )
        self.term = WebTty(self.user, asset, login_role, login_type="web")
        # self.term.remote_ip = self.request.remote_ip
        self.term.remote_ip = self.request.headers.get("X-Real-IP")
        if not self.term.remote_ip:
            self.term.remote_ip = self.request.remote_ip
        self.ssh = self.term.get_connection()
        self.channel = self.ssh.invoke_shell(term="xterm")
        WebTerminalHandler.tasks.append(MyThread(target=self.forward_outbound))
        WebTerminalHandler.clients.append(self)

        for t in WebTerminalHandler.tasks:
            if t.is_alive():
                continue
            try:
                t.setDaemon(True)
                t.start()
            except RuntimeError:
                pass
Esempio n. 41
0
def file_monitor(path='.', client=None):
    wm = WatchManager()
    mask = IN_DELETE | IN_CREATE | IN_MODIFY
    notifier = AsyncNotifier(wm, EventHandler(client))
    wm.add_watch(path, mask, auto_add=True, rec=True)
    if not os.path.isfile(path):
        logger.debug("File %s does not exist." % path)
        sys.exit(3)
    else:
        logger.debug("Now starting monitor file %s." % path)
        global f
        f = open(path, 'r')
        st_size = os.stat(path)[6]
        f.seek(st_size)

    while True:
        try:
            notifier.process_events()
            if notifier.check_events():
                notifier.read_events()
        except KeyboardInterrupt:
            print "keyboard Interrupt."
            notifier.stop()
            break
Esempio n. 42
0
    def open(self):
        logger.debug('Websocket: Open request')
        role_name = self.get_argument('role', 'sb')
        asset_id = self.get_argument('id', 9999)
        asset = get_object(Asset, id=asset_id)
        if asset:
            roles = user_have_perm(self.user, asset)
            logger.debug(roles)
            logger.debug('系统用户: %s' % role_name)
            login_role = ''
            for role in roles:
                if role.name == role_name:
                    login_role = role
                    break
            if not login_role:
                logger.warning('Websocket: Not that Role %s for Host: %s User: %s ' % (role_name, asset.hostname,
                                                                                       self.user.username))
                self.close()
                return
        else:
            logger.warning('Websocket: No that Host: %s User: %s ' % (asset_id, self.user.username))
            self.close()
            return
        logger.debug('Websocket: request web terminal Host: %s User: %s Role: %s' % (asset.hostname, self.user.username,
                                                                                     login_role.name))
        self.term = WebTty(self.user, asset, login_role, login_type='web')
        self.term.remote_ip = self.request.remote_ip
        self.ssh = self.term.get_connection()
        self.channel = self.ssh.invoke_shell(term='xterm')
        WebTerminalHandler.tasks.append(MyThread(target=self.forward_outbound))
        WebTerminalHandler.clients.append(self)

        for t in WebTerminalHandler.tasks:
            if t.is_alive():
                continue
            try:
                t.setDaemon(True)
                t.start()
            except RuntimeError:
                pass
Esempio n. 43
0
 def on_close(self):
     logger.debug('关闭web_exec请求')
Esempio n. 44
0
 def on_close(self):
     logger.debug("关闭web_exec请求")