Esempio n. 1
0
    async def __call__(self):
        tm = get_tm(self.request)
        await tm.abort(self.request)
        ws = web.WebSocketResponse()
        await ws.prepare(self.request)

        async for msg in ws:
            if msg.tp == aiohttp.WSMsgType.text:
                message = ujson.loads(msg.data)
                if message['op'] == 'close':
                    await ws.close()
                elif message['op'] == 'GET':
                    txn = await tm.begin(request=self.request)
                    try:
                        await self.handle_ws_request(ws, message)
                    except Exception:
                        await ws.close()
                        raise
                    finally:
                        # only currently support GET requests which are *never*
                        # supposed to be commits
                        await tm.abort(txn=txn)
                else:
                    await ws.close()
            elif msg.tp == aiohttp.WSMsgType.error:
                logger.debug(
                    'ws connection closed with exception {0:s}'.format(
                        ws.exception()))

        logger.debug('websocket connection closed')

        return {}
Esempio n. 2
0
    async def __call__(self):
        tm = get_tm()
        await tm.abort()
        ws = web.WebSocketResponse()
        await ws.prepare(self.request)

        async for msg in ws:
            if msg.type == aiohttp.WSMsgType.text:
                try:
                    message = ujson.loads(msg.data)
                except ValueError:
                    logger.warning(
                        'Invalid websocket payload, ignored: {}'.format(
                            msg.data))
                    continue
                if message['op'] == 'close':
                    await ws.close()
                elif message['op'].lower() == 'get':
                    txn = await tm.begin()
                    try:
                        await self.handle_ws_request(ws, message)
                    except Exception:
                        logger.error('Exception on ws', exc_info=True)
                    finally:
                        # only currently support GET requests which are *never*
                        # supposed to be commits
                        await tm.abort(txn=txn)
            elif msg.type == aiohttp.WSMsgType.error:
                logger.debug(
                    'ws connection closed with exception {0:s}'.format(
                        ws.exception()))

        logger.debug('websocket connection closed')

        return {}
Esempio n. 3
0
    async def __call__(self):
        tm = get_tm()
        await tm.abort()
        ws = self.request.get_ws()
        await ws.prepare()

        async for msg in ws:
            try:
                message = msg.json
            except WebSocketJsonDecodeError:
                # We only care about json messages
                logger.warning(
                    "Invalid websocket payload, ignored: {}".format(msg))
                continue

            if message["op"].lower() == "close":
                break
            elif message["op"].lower() == "get":
                txn = await tm.begin()
                try:
                    await self.handle_ws_request(ws, message)
                except Exception:
                    logger.error("Exception on ws", exc_info=True)
                finally:
                    # only currently support GET requests which are *never*
                    # supposed to be commits
                    await tm.abort(txn=txn)

        logger.debug("websocket connection closed")
        await ws.close()
Esempio n. 4
0
    async def __call__(self):
        tm = get_tm(self.request)
        await tm.abort(self.request)
        ws = web.WebSocketResponse()
        await ws.prepare(self.request)

        async for msg in ws:
            if msg.type == aiohttp.WSMsgType.text:
                try:
                    message = ujson.loads(msg.data)
                except ValueError:
                    logger.warning('Invalid websocket payload, ignored: {}'.format(
                        msg.data))
                    continue
                if message['op'] == 'close':
                    await ws.close()
                elif message['op'].lower() == 'get':
                    txn = await tm.begin(request=self.request)
                    try:
                        await self.handle_ws_request(ws, message)
                    except Exception:
                        logger.error('Exception on ws', exc_info=True)
                    finally:
                        # only currently support GET requests which are *never*
                        # supposed to be commits
                        await tm.abort(txn=txn)
            elif msg.type == aiohttp.WSMsgType.error:
                logger.debug('ws connection closed with exception {0:s}'
                             .format(ws.exception()))

        logger.debug('websocket connection closed')

        return {}
Esempio n. 5
0
    async def __call__(self):
        ws = web.WebSocketResponse()
        await ws.prepare(self.request)

        async for msg in ws:
            if msg.tp == aiohttp.MsgType.text:
                message = ujson.loads(msg.data)
                if message['op'] == 'close':
                    await ws.close()
                elif message['op'] == 'GET':
                    method = app_settings['http_methods']['GET']
                    path = tuple(p for p in message['value'].split('/') if p)

                    # avoid circular import
                    from guillotina.traversal import do_traverse

                    obj, tail = await do_traverse(self.request,
                                                  self.request.site, path)

                    traverse_to = None

                    if tail and len(tail) == 1:
                        view_name = tail[0]
                    elif tail is None or len(tail) == 0:
                        view_name = ''
                    else:
                        view_name = tail[0]
                        traverse_to = tail[1:]

                    permission = getUtility(IPermission,
                                            name='guillotina.AccessContent')

                    allowed = IInteraction(self.request).check_permission(
                        permission.id, obj)
                    if not allowed:
                        response = {'error': 'Not allowed'}
                        ws.send_str(ujson.dumps(response))

                    try:
                        view = queryMultiAdapter((obj, self.request),
                                                 method,
                                                 name=view_name)
                    except AttributeError:
                        view = None

                    if traverse_to is not None:
                        if view is None or not ITraversableView.providedBy(
                                view):
                            response = {'error': 'Not found'}
                            ws.send_str(ujson.dumps(response))
                        else:
                            try:
                                view = await view.publish_traverse(traverse_to)
                            except Exception as e:
                                logger.error("Exception on view execution",
                                             exc_info=e)
                                response = {'error': 'Not found'}
                                ws.send_str(ujson.dumps(response))

                    view_result = await view()
                    if isinstance(view_result, Response):
                        view_result = view_result.response

                    # Return the value
                    ws.send_str(ujson.dumps(view_result))

                    # Wait for possible value
                    futures_to_wait = self.request._futures.values()
                    if futures_to_wait:
                        await asyncio.gather(futures_to_wait)
                        self.request._futures = {}
                else:
                    await ws.close()
            elif msg.tp == aiohttp.MsgType.error:
                logger.debug(
                    'ws connection closed with exception {0:s}'.format(
                        ws.exception()))

        logger.debug('websocket connection closed')

        return {}