# 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/base.py
# class Transport:
#     def __init__(self, manager, session, request):
#         self.manager = manager
#         self.session = session
#         self.request = request
# 
# 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
# 
# def cache_headers():
#     d = datetime.now() + td365
#     return (
#         (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds),
#         (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds),
#         (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")),
#     )


from aiohttp import web, hdrs
from ..protocol import loads, ENCODING
from .base import Transport
from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers
class XHRSendTransport(Transport):
    async def process(self):
        request = self.request

        if request.method not in (hdrs.METH_GET, hdrs.METH_POST, hdrs.METH_OPTIONS):
            return web.HTTPForbidden(text="Method is not allowed")

        if self.request.method == hdrs.METH_OPTIONS:
            headers = (
                (hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"),
                (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"),
            )
            headers += session_cookie(request)
            headers += cors_headers(request.headers)
            headers += cache_headers()
            return web.Response(status=204, headers=headers)

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

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

        await self.session._remote_messages(messages)

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

# 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/base.py
# class Transport:
#     def __init__(self, manager, session, request):
#         self.manager = manager
#         self.session = session
#         self.request = request
# 
# 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
# 
# def cache_headers():
#     d = datetime.now() + td365
#     return (
#         (hdrs.ACCESS_CONTROL_MAX_AGE, td365seconds),
#         (hdrs.CACHE_CONTROL, "max-age=%s, public" % td365seconds),
#         (hdrs.EXPIRES, d.strftime("%a, %d %b %Y %H:%M:%S")),
#     )


# Path: sockjs/transports/xhrsend.py
from aiohttp import web, hdrs
from ..protocol import loads, ENCODING
from .base import Transport
from .utils import CACHE_CONTROL, session_cookie, cors_headers, cache_headers

class XHRSendTransport(Transport):
    async def process(self):
        request = self.request

        if request.method not in (hdrs.METH_GET, hdrs.METH_POST, hdrs.METH_OPTIONS):
            return web.HTTPForbidden(text="Method is not allowed")

        if self.request.method == hdrs.METH_OPTIONS:
            headers = (
                (hdrs.ACCESS_CONTROL_ALLOW_METHODS, "OPTIONS, POST"),
                (hdrs.CONTENT_TYPE, "application/javascript; charset=UTF-8"),
            )
            headers += session_cookie(request)
            headers += cors_headers(request.headers)
            headers += cache_headers()
            return web.Response(status=204, headers=headers)

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

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

        await self.session._remote_messages(messages)

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

            (hdrs.CACHE_CONTROL, CACHE_CONTROL),