# Path: mod_dash/server_negotiate.py
# class DASHNegotiateServer(NegotiateServerModule):
#     """ Negotiator for MPEG DASH test """
# 
#     def __init__(self):
#         NegotiateServerModule.__init__(self)
#         self.peers = {}
# 
#     @staticmethod
#     def _stream_to_sha256(stream):
#         """ Stream to SHA256 identifier """
#         sha256 = hashlib.new("sha256")
#         sha256.update(str(hash(stream)))
#         return base64.b64encode(sha256.digest())
# 
#     def unchoke(self, stream, request_body):
#         """ Invoked when we must unchoke a session """
# 
#         sha256 = self._stream_to_sha256(stream)
# 
#         if sha256 in self.peers:
#             raise RuntimeError("dash: multiple unchokes: %s", sha256)
# 
#         self.peers[sha256] = []
#         stream.atclose(self._update_peers)
# 
#         logging.debug("dash: add sha256: %s", sha256)
# 
#         return {
#                 "authorization": sha256,
#                 "port": 8080,
# 
#                 # For now just accept the proposal from the client
#                 "dash_rates": request_body["dash_rates"],
#                }
# 
#     def collect(self, stream, request_body):
#         """ Invoked when we must save the result of a session """
# 
#         sha256 = self._stream_to_sha256(stream)
# 
#         if sha256 not in self.peers:
#             raise RuntimeError("dash: not authorized: %s", sha256)
# 
#         # Note: no more than one collect per session
#         result = self.peers.pop(sha256)
# 
#         logging.debug("dash: del sha256 (OK): %s", sha256)
# 
#         server_timestamp = utils.timestamp()
# 
#         BACKEND.store_generic("dash", {
#                                        "srvr_schema_version": 3,
#                                        "srvr_timestamp": server_timestamp,
#                                        "client": request_body,
#                                        "server": result,
#                                       })
# 
#         #
#         # Return back, at a minimum, the server timestamp.
#         # TODO Also gather and return Web100 stats.
#         #
#         for index in range(len(request_body)):
#             if index <= len(result):
#                 result.append({})
#             result[index]["timestamp"] = server_timestamp
# 
#         return result
# 
#     def _update_peers(self, stream, ignored):
#         """ Invoked when a session has been closed """
# 
#         sha256 = self._stream_to_sha256(stream)
# 
#         # Note: if collect is successful self.peers[sha256] doesn't exist
#         if sha256 in self.peers:
#             logging.warning("dash: del sha256 (ERR): %s", sha256)
#             del self.peers[sha256]
# 
# Path: mod_dash/server_glue.py
# class DASHServerGlue(DASHServerSmpl):
#     """ Glue for DASH on the server side """
# 
#     def __init__(self, poller, negotiator):
#         DASHServerSmpl.__init__(self, poller)
#         self.negotiator = negotiator
# 
#     def got_request_headers(self, stream, request):
#         """ Filter incoming HTTP requests """
# 
#         auth = request["Authorization"]
#         if not auth:
#             return False
# 
#         if auth not in self.negotiator.peers:
#             return False
# 
#         return DASHServerSmpl.got_request_headers(self, stream, request)


import logging
from mod_dash.client_negotiate import DASHNegotiateClient
from mod_dash.server_negotiate import DASHNegotiateServer
from mod_dash.server_glue import DASHServerGlue

""" The entry point of the DASH module """



def _run_test(message):
    """ Run the DASH test """
    client = DASHNegotiateClient(message["poller"])
    client.configure(message["conf"])
    client.connect((message["address"], message["port"]))

def mod_load(context, message):
    """ Invoked when the module loads """
    logging.debug("dash: init for context '%s'... in progress", context)

    if context == "server":

        # Adapted from mod_dash/main.py

        negotiate_server = message["negotiate_server"]
        http_server = message["http_server"]

        logging.debug("dash: register negotiate server module... in progress")

        dash_negotiate_server = DASHNegotiateServer()
        negotiate_server.register_module("dash", dash_negotiate_server)

        logging.debug("dash: register negotiate server module... complete")
        logging.debug("dash: register HTTP server child... in progress")


# Path: mod_dash/server_negotiate.py
# class DASHNegotiateServer(NegotiateServerModule):
#     """ Negotiator for MPEG DASH test """
# 
#     def __init__(self):
#         NegotiateServerModule.__init__(self)
#         self.peers = {}
# 
#     @staticmethod
#     def _stream_to_sha256(stream):
#         """ Stream to SHA256 identifier """
#         sha256 = hashlib.new("sha256")
#         sha256.update(str(hash(stream)))
#         return base64.b64encode(sha256.digest())
# 
#     def unchoke(self, stream, request_body):
#         """ Invoked when we must unchoke a session """
# 
#         sha256 = self._stream_to_sha256(stream)
# 
#         if sha256 in self.peers:
#             raise RuntimeError("dash: multiple unchokes: %s", sha256)
# 
#         self.peers[sha256] = []
#         stream.atclose(self._update_peers)
# 
#         logging.debug("dash: add sha256: %s", sha256)
# 
#         return {
#                 "authorization": sha256,
#                 "port": 8080,
# 
#                 # For now just accept the proposal from the client
#                 "dash_rates": request_body["dash_rates"],
#                }
# 
#     def collect(self, stream, request_body):
#         """ Invoked when we must save the result of a session """
# 
#         sha256 = self._stream_to_sha256(stream)
# 
#         if sha256 not in self.peers:
#             raise RuntimeError("dash: not authorized: %s", sha256)
# 
#         # Note: no more than one collect per session
#         result = self.peers.pop(sha256)
# 
#         logging.debug("dash: del sha256 (OK): %s", sha256)
# 
#         server_timestamp = utils.timestamp()
# 
#         BACKEND.store_generic("dash", {
#                                        "srvr_schema_version": 3,
#                                        "srvr_timestamp": server_timestamp,
#                                        "client": request_body,
#                                        "server": result,
#                                       })
# 
#         #
#         # Return back, at a minimum, the server timestamp.
#         # TODO Also gather and return Web100 stats.
#         #
#         for index in range(len(request_body)):
#             if index <= len(result):
#                 result.append({})
#             result[index]["timestamp"] = server_timestamp
# 
#         return result
# 
#     def _update_peers(self, stream, ignored):
#         """ Invoked when a session has been closed """
# 
#         sha256 = self._stream_to_sha256(stream)
# 
#         # Note: if collect is successful self.peers[sha256] doesn't exist
#         if sha256 in self.peers:
#             logging.warning("dash: del sha256 (ERR): %s", sha256)
#             del self.peers[sha256]
# 
# Path: mod_dash/server_glue.py
# class DASHServerGlue(DASHServerSmpl):
#     """ Glue for DASH on the server side """
# 
#     def __init__(self, poller, negotiator):
#         DASHServerSmpl.__init__(self, poller)
#         self.negotiator = negotiator
# 
#     def got_request_headers(self, stream, request):
#         """ Filter incoming HTTP requests """
# 
#         auth = request["Authorization"]
#         if not auth:
#             return False
# 
#         if auth not in self.negotiator.peers:
#             return False
# 
#         return DASHServerSmpl.got_request_headers(self, stream, request)


# Path: mod_dash/neubot_module.py
import logging
from mod_dash.client_negotiate import DASHNegotiateClient
from mod_dash.server_negotiate import DASHNegotiateServer
from mod_dash.server_glue import DASHServerGlue


""" The entry point of the DASH module """



def _run_test(message):
    """ Run the DASH test """
    client = DASHNegotiateClient(message["poller"])
    client.configure(message["conf"])
    client.connect((message["address"], message["port"]))

def mod_load(context, message):
    """ Invoked when the module loads """
    logging.debug("dash: init for context '%s'... in progress", context)

    if context == "server":

        # Adapted from mod_dash/main.py

        negotiate_server = message["negotiate_server"]
        http_server = message["http_server"]

        logging.debug("dash: register negotiate server module... in progress")

        dash_negotiate_server = DASHNegotiateServer()
        negotiate_server.register_module("dash", dash_negotiate_server)

        logging.debug("dash: register negotiate server module... complete")
        logging.debug("dash: register HTTP server child... in progress")


        dash_server = DASHServerGlue(http_server.poller, dash_negotiate_server)