# Path: sockjs/transports/base.py
# class StreamingTransport(Transport):
# 
#     timeout = None
#     maxsize = 131072  # 128K bytes
# 
#     def __init__(self, manager, session, request):
#         super().__init__(manager, session, request)
# 
#         self.size = 0
#         self.response = None
# 
#     async def send(self, text):
#         blob = (text + "\n").encode(ENCODING)
#         await self.response.write(blob)
# 
#         self.size += len(blob)
#         if self.size > self.maxsize:
#             return True
#         else:
#             return False
# 
#     async def handle_session(self):
#         assert self.response is not None, "Response is not specified."
# 
#         # session was interrupted
#         if self.session.interrupted:
#             await self.send(close_frame(1002, "Connection interrupted"))
# 
#         # session is closing or closed
#         elif self.session.state in (STATE_CLOSING, STATE_CLOSED):
#             await self.session._remote_closed()
#             await self.send(close_frame(3000, "Go away!"))
# 
#         else:
#             # acquire session
#             try:
#                 await self.manager.acquire(self.session)
#             except SessionIsAcquired:
#                 await self.send(close_frame(2010, "Another connection still open"))
#             else:
#                 try:
#                     while True:
#                         if self.timeout:
#                             try:
#                                 frame, text = await asyncio.wait_for(
#                                     self.session._wait(), timeout=self.timeout
#                                 )
#                             except asyncio.futures.TimeoutError:
#                                 frame, text = FRAME_MESSAGE, "a[]"
#                         else:
#                             frame, text = await self.session._wait()
# 
#                         if frame == FRAME_CLOSE:
#                             await self.session._remote_closed()
#                             await self.send(text)
#                             return
#                         else:
#                             stop = await self.send(text)
#                             if stop:
#                                 break
#                 except asyncio.CancelledError:
#                     await self.session._remote_close(exc=aiohttp.ClientConnectionError)
#                     await self.session._remote_closed()
#                     raise
#                 except SessionIsClosed:
#                     pass
#                 finally:
#                     await self.manager.release(self.session)
# 
# Path: sockjs/transports/utils.py
# CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0"
# 
# def session_cookie(request):
#     cookie = request.cookies.get("JSESSIONID", "dummy")
#     cookies = http.cookies.SimpleCookie()
#     cookies["JSESSIONID"] = cookie
#     cookies["JSESSIONID"]["path"] = "/"
#     return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),)
# 
# def cors_headers(headers, nocreds=False):
#     origin = headers.get(hdrs.ORIGIN, "*")
#     cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),)
# 
#     ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS)
#     if ac_headers:
#         cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),)
# 
#     if origin != "*":
#         return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),)
#     else:
#         return cors
# 
# Path: sockjs/protocol.py
# ENCODING = "utf-8"
# STATE_NEW = 0
# STATE_OPEN = 1
# STATE_CLOSING = 2
# STATE_CLOSED = 3
# FRAME_OPEN = "o"
# FRAME_CLOSE = "c"
# FRAME_MESSAGE = "a"
# FRAME_MESSAGE_BLOB = "a1"
# FRAME_HEARTBEAT = "h"
# IFRAME_HTML = """<!DOCTYPE html>
# <html>
# <head>
# <meta http-equiv="X-UA-Compatible" content="IE=edge" />
# <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
#   <script src="%s"></script>
#   <script>
#     document.domain = document.domain;
#     SockJS.bootstrap_iframe();
#   </script>
# </head>
# <body>
#   <h2>Don't panic!</h2>
#   <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p>
# </body>
# </html>
# """.strip()
# IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest()
# ENCODING = "utf-8"
# MSG_OPEN = 1
# MSG_MESSAGE = 2
# MSG_CLOSE = 3
# MSG_CLOSED = 4
#     def dthandler(obj):
# def dumps(data):
# def close_frame(code, reason):
# def message_frame(message):
# def messages_frame(messages):
#     def tp(self):
# class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])):


import re
from urllib.parse import unquote_plus
from aiohttp import web, hdrs
from .base import StreamingTransport
from .utils import CACHE_CONTROL, session_cookie, cors_headers
from ..protocol import dumps, loads, ENCODING

            await self.handle_session()
            return resp

        elif request.method == hdrs.METH_POST:
            data = await request.read()

            ctype = request.content_type.lower()
            if ctype == "application/x-www-form-urlencoded":
                if not data.startswith(b"d="):
                    return web.HTTPInternalServerError(text="Payload expected.")

                data = unquote_plus(data[2:].decode(ENCODING))
            else:
                data = data.decode(ENCODING)

            if not data:
                return web.HTTPInternalServerError(text="Payload expected.")

            try:
                messages = loads(data)
            except Exception:
                return web.HTTPInternalServerError(text="Broken JSON encoding.")

            await session._remote_messages(messages)

            headers = (
                (hdrs.CONTENT_TYPE, "text/html;charset=UTF-8"),
                (hdrs.CACHE_CONTROL, CACHE_CONTROL),
            )

# Path: sockjs/transports/base.py
# class StreamingTransport(Transport):
# 
#     timeout = None
#     maxsize = 131072  # 128K bytes
# 
#     def __init__(self, manager, session, request):
#         super().__init__(manager, session, request)
# 
#         self.size = 0
#         self.response = None
# 
#     async def send(self, text):
#         blob = (text + "\n").encode(ENCODING)
#         await self.response.write(blob)
# 
#         self.size += len(blob)
#         if self.size > self.maxsize:
#             return True
#         else:
#             return False
# 
#     async def handle_session(self):
#         assert self.response is not None, "Response is not specified."
# 
#         # session was interrupted
#         if self.session.interrupted:
#             await self.send(close_frame(1002, "Connection interrupted"))
# 
#         # session is closing or closed
#         elif self.session.state in (STATE_CLOSING, STATE_CLOSED):
#             await self.session._remote_closed()
#             await self.send(close_frame(3000, "Go away!"))
# 
#         else:
#             # acquire session
#             try:
#                 await self.manager.acquire(self.session)
#             except SessionIsAcquired:
#                 await self.send(close_frame(2010, "Another connection still open"))
#             else:
#                 try:
#                     while True:
#                         if self.timeout:
#                             try:
#                                 frame, text = await asyncio.wait_for(
#                                     self.session._wait(), timeout=self.timeout
#                                 )
#                             except asyncio.futures.TimeoutError:
#                                 frame, text = FRAME_MESSAGE, "a[]"
#                         else:
#                             frame, text = await self.session._wait()
# 
#                         if frame == FRAME_CLOSE:
#                             await self.session._remote_closed()
#                             await self.send(text)
#                             return
#                         else:
#                             stop = await self.send(text)
#                             if stop:
#                                 break
#                 except asyncio.CancelledError:
#                     await self.session._remote_close(exc=aiohttp.ClientConnectionError)
#                     await self.session._remote_closed()
#                     raise
#                 except SessionIsClosed:
#                     pass
#                 finally:
#                     await self.manager.release(self.session)
# 
# Path: sockjs/transports/utils.py
# CACHE_CONTROL = "no-store, no-cache, no-transform, must-revalidate, max-age=0"
# 
# def session_cookie(request):
#     cookie = request.cookies.get("JSESSIONID", "dummy")
#     cookies = http.cookies.SimpleCookie()
#     cookies["JSESSIONID"] = cookie
#     cookies["JSESSIONID"]["path"] = "/"
#     return ((hdrs.SET_COOKIE, cookies["JSESSIONID"].output(header="")[1:]),)
# 
# def cors_headers(headers, nocreds=False):
#     origin = headers.get(hdrs.ORIGIN, "*")
#     cors = ((hdrs.ACCESS_CONTROL_ALLOW_ORIGIN, origin),)
# 
#     ac_headers = headers.get(hdrs.ACCESS_CONTROL_REQUEST_HEADERS)
#     if ac_headers:
#         cors += ((hdrs.ACCESS_CONTROL_ALLOW_HEADERS, ac_headers),)
# 
#     if origin != "*":
#         return cors + ((hdrs.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"),)
#     else:
#         return cors
# 
# Path: sockjs/protocol.py
# ENCODING = "utf-8"
# STATE_NEW = 0
# STATE_OPEN = 1
# STATE_CLOSING = 2
# STATE_CLOSED = 3
# FRAME_OPEN = "o"
# FRAME_CLOSE = "c"
# FRAME_MESSAGE = "a"
# FRAME_MESSAGE_BLOB = "a1"
# FRAME_HEARTBEAT = "h"
# IFRAME_HTML = """<!DOCTYPE html>
# <html>
# <head>
# <meta http-equiv="X-UA-Compatible" content="IE=edge" />
# <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
#   <script src="%s"></script>
#   <script>
#     document.domain = document.domain;
#     SockJS.bootstrap_iframe();
#   </script>
# </head>
# <body>
#   <h2>Don't panic!</h2>
#   <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p>
# </body>
# </html>
# """.strip()
# IFRAME_MD5 = hashlib.md5(IFRAME_HTML.encode()).hexdigest()
# ENCODING = "utf-8"
# MSG_OPEN = 1
# MSG_MESSAGE = 2
# MSG_CLOSE = 3
# MSG_CLOSED = 4
#     def dthandler(obj):
# def dumps(data):
# def close_frame(code, reason):
# def message_frame(message):
# def messages_frame(messages):
#     def tp(self):
# class SockjsMessage(collections.namedtuple("SockjsMessage", ["type", "data"])):


# Path: sockjs/transports/jsonp.py
import re
from urllib.parse import unquote_plus
from aiohttp import web, hdrs
from .base import StreamingTransport
from .utils import CACHE_CONTROL, session_cookie, cors_headers
from ..protocol import dumps, loads, ENCODING


            await self.handle_session()
            return resp

        elif request.method == hdrs.METH_POST:
            data = await request.read()

            ctype = request.content_type.lower()
            if ctype == "application/x-www-form-urlencoded":
                if not data.startswith(b"d="):
                    return web.HTTPInternalServerError(text="Payload expected.")

                data = unquote_plus(data[2:].decode(ENCODING))
            else:
                data = data.decode(ENCODING)

            if not data:
                return web.HTTPInternalServerError(text="Payload expected.")

            try:
                messages = loads(data)
            except Exception:
                return web.HTTPInternalServerError(text="Broken JSON encoding.")

            await session._remote_messages(messages)

            headers = (
                (hdrs.CONTENT_TYPE, "text/html;charset=UTF-8"),
                (hdrs.CACHE_CONTROL, CACHE_CONTROL),
            )

            headers += session_cookie(request)