示例#1
0
    def reply_message(self):

        # Open the WebSocket and subscribe it to a channel:
        request_body = self.rfile.read(int(self.headers.get('Content-Length')))
        cookies = SimpleCookie(self.headers.get('Cookie'))
        token = cookies['SP_SSO_JWT_COOKIE'].value
        if (not verify_cookie(token)):
            self.send_response(401)
            return ;

        # Set the headers required by the GRIP proxy:
        self.send_response(200)
        self.send_header('Sec-WebSocket-Extensions', 'grip; message-prefix=""')
        self.send_header('Content-Type', 'application/websocket-events')
        self.end_headers()
        in_events = decode_websocket_events(request_body)
        if in_events[0].type == 'OPEN':
            out_events = []
            out_events.append(WebSocketEvent('OPEN'))
            self.wfile.write(encode_websocket_events(out_events))
            logger.info("Connection Opened with Client")
            print("Connection Opened with Client")
        if in_events[0].type == 'TEXT':
            print("Text received from client")
            message = in_events[0].content
            print(message)
            cname = get_channel_name(message)
            print(cname)
            if cname != "all":
                try:
                    create_siddhi_common(message, cname)
                except Exception as e:
                    logger.info("Exception occurred:" +  str(e))
                    print("Exception occurred:" +  str(e))
                    threading.Thread(target=self.publish_message(cname, 'Error while creating the Siddhi app')).start()
                else:
                    logger.info("Siddhi app created")
                    print("Siddhi app created")
                    threading.Thread(target=self.publish_message(cname, 'Created Siddhi app: ' + cname)).start()
            else:
                threading.Thread(target=self.publish_message(cname, 'Please publish a valid Json.' )).start()
                print("Invalid JSON")
            out_events = []
            out_events.append(WebSocketEvent('TEXT', 'c:' + websocket_control_message('subscribe', {'channel': cname})))
            self.wfile.write(encode_websocket_events(out_events))
            print("End of the response")
示例#2
0
    def post(self, channel: str) -> Response:

        try:
            # in_events = decode_websocket_events(request.get_data())
            in_events = decode_websocket_events(request.get_data())
        except ValueError as e:
            log.error(e)
            raise BadRequest("Cannot decode websocket request: invalid format")

        if in_events is None or len(in_events) <= 0:
            log.error("Websocket request: {}", request.data)
            raise BadRequest(
                "Cannot decode websocket request: invalid in_event")
        in_events = in_events[0]

        event_type = None

        try:
            event_type = in_events.type
        except BaseException as e:  # pragma: no cover
            log.error(e)
            raise BadRequest("Cannot decode websocket request: invalid type")

        if event_type is None:  # pragma: no cover
            raise BadRequest("Cannot decode websocket request, no event type")

        out_events = []
        if event_type == "OPEN":
            ctrl_msg = websocket_control_message("subscribe",
                                                 {"channel": channel})
            out_events.append(WebSocketEvent("OPEN"))
            out_events.append(WebSocketEvent(
                "TEXT",
                f"c:{ctrl_msg}",
            ))
            headers = {"Sec-WebSocket-Extensions": "grip"}
            resp = FlaskResponse(
                encode_websocket_events(out_events),
                mimetype="application/websocket-events",
                headers=headers,
            )
            return resp

        log.error("Unknkown event type: {}", event_type)
        raise BadRequest("Cannot understand websocket request")
示例#3
0
    def post(self, channel):

        in_events = decode_websocket_events(request.data)
        if in_events is None or len(in_events) <= 0:
            log.error("Websocket request: {}", request.data)
            raise RestApiException("Cannot decode websocket request")
        in_events = in_events[0]

        event_type = None

        try:
            event_type = in_events.type
        except BaseException as e:
            log.error(e)
            raise RestApiException("Cannot decode websocket request")

        if event_type is None:
            log.error("Event type is None")
            raise RestApiException("Cannot decode websocket request")

        out_events = []
        if event_type == 'OPEN':
            out_events.append(WebSocketEvent('OPEN'))
            out_events.append(
                WebSocketEvent(
                    'TEXT',
                    'c:' + websocket_control_message('subscribe',
                                                     {'channel': channel}),
                ))
            headers = {'Sec-WebSocket-Extensions': 'grip'}
            resp = Response(
                encode_websocket_events(out_events),
                mimetype='application/websocket-events',
                headers=headers,
            )
            return resp

        log.error("Unknkown event type: {}", event_type)
        raise RestApiException("Cannot understand websocket request")
示例#4
0
    def post(self):
        #####################################
        # FIXME add connection last seen timestamp
        connection_id = self.request.headers['Connection-Id']
        in_events = decode_websocket_events(self.request.body)
        out_events = []
        if len(in_events) == 0:
            return

        logger.debug(in_events[0].type)
        if in_events[0].type == 'OPEN':
            out_events.append(WebSocketEvent('OPEN'))
            out_events.append(
                WebSocketEvent('TEXT', 'm:' +
                               json.dumps({'__restream_type': 'ready'})))
        elif in_events[0].type == 'TEXT':
            msg = in_events[0].content
            logger.debug(msg)
            command = parse_message(msg)
            if command['__restream_type'] == 'error':
                out_events.append(
                    WebSocketEvent('TEXT', 'm:' + json.dumps(command)))
            elif command['action'] == 'subscribe':
                if connection_id in connection_channels and command[
                        'channel_id'] in connection_channels[connection_id]:
                    logger.info(
                        "Connection {} already subscribed to {}".format(
                            connection_id, command['channel_id']))
                else:
                    out_events.append(
                        WebSocketEvent(
                            'TEXT',
                            'm:' + json.dumps({
                                '__restream_type': 'subscribe',
                                'channel': command['channel']
                            })))
                    out_events.append(
                        WebSocketEvent(
                            'TEXT', 'c:' + websocket_control_message(
                                'subscribe',
                                {'channel': command['channel_id']})))
                    process_subscribe(command, self.channel_fetchers,
                                      connection_id)
                    logger.info('subscribe {} to {}'.format(
                        connection_id, command['channel_id']))
            elif command['action'] == 'unsubscribe':
                if connection_id not in connection_channels or command[
                        'channel_id'] not in connection_channels[connection_id]:
                    logger.info(
                        "Connection {} not subscribed to {}; won't unsubscribe"
                        .format(connection_id, command['channel_id']))
                else:
                    out_events.append(
                        WebSocketEvent(
                            'TEXT',
                            'm:' + json.dumps({
                                '__restream_type': 'unsubscribe',
                                'channel': command['channel']
                            })))
                    out_events.append(
                        WebSocketEvent(
                            'TEXT', 'c:' + websocket_control_message(
                                'unsubscribe',
                                {'channel': command['channel_id']})))
                    process_unsubscribe(command['channel_id'], connection_id)
                    logger.info('unsubscribe {} from {}'.format(
                        connection_id, command['channel_id']))
        elif in_events[0].type == 'DISCONNECT' or in_events[0].type == 'CLOSE':
            out_events.append(WebSocketEvent(in_events[0].type))
            if connection_id in connection_channels:
                disconnect_all(connection_id)
        else:
            logger.info('event type not recognized: ' + in_events[0].type)

        self.write(encode_websocket_events(out_events))
        self.set_header('Sec-WebSocket-Extensions', 'grip')
        self.set_header('Content-Type', 'application/websocket-events')
        self.finish()
 def detach(self):
     self.send_control(websocket_control_message('detach'))
 def unsubscribe(self, channel):
     self.send_control(
         websocket_control_message('unsubscribe',
                                   {'channel': _get_prefix() + channel}))