Beispiel #1
0
class P2PCallPlugin(PluginBase):
    """ This base class for plugin """
    def __init__(self, proxy_config, backend_server_mgr, pyramid_config):
        super().__init__(proxy_config, backend_server_mgr, pyramid_config)
        self.config = self.read_config(
            os.path.join(proxy_config['general']['configs_folder'],
                         'janus-proxy.plugin.p2pcall.yml'))

        # set up DAO
        from januscloud.proxy.dao.mem_videocall_user_dao import MemVideoCallUserDao
        if self.config['general']['user_db'] == 'memory':
            self.user_dao = MemVideoCallUserDao()
        else:
            raise JanusCloudError(
                'user_db url {} not support by videocall plugin'.format(
                    self.config['general']['user_db']),
                JANUS_ERROR_NOT_IMPLEMENTED)

        self.api_base_url = self.get_api_base_url(proxy_config)
        #print('api_base_url:', self.api_base_url)

        includeme(pyramid_config)
        pyramid_config.registry.p2pcall_plugin = self

        log.info('{} initialized!'.format(JANUS_P2PCALL_NAME))

    def get_version(self):
        return JANUS_P2PCALL_VERSION

    def get_version_string(self):
        return JANUS_P2PCALL_VERSION_STRING

    def get_description(self):
        return JANUS_P2PCALL_DESCRIPTION

    def get_name(self):
        return JANUS_P2PCALL_NAME

    def get_author(self):
        return JANUS_P2PCALL_AUTHOR

    def get_package(self):
        return JANUS_P2PCALL_PACKAGE

    def create_handle(self,
                      handle_id,
                      session,
                      opaque_id=None,
                      *args,
                      **kwargs):
        return P2PCallHandle(handle_id, session, self, opaque_id, *args,
                             **kwargs)

    def handle_async_event(self, to_user, from_user, async_event):
        p2pcall_user = self.user_dao.get_by_username(to_user)
        if p2pcall_user is None:
            raise JanusCloudError(
                'Username \'{}\' doesn\'t exist'.format(to_user),
                JANUS_P2PCALL_ERROR_NO_SUCH_USERNAME)
        if p2pcall_user.handle is None:
            raise JanusCloudError('Not support relay http request',
                                  JANUS_P2PCALL_ERROR_INVALID_REQUEST)
        log.debug(
            'an async event ({}) from \'{}\' to \'{}\' is received by http API'
            .format(async_event, from_user, to_user))
        p2pcall_user.handle.on_async_event(from_user, async_event)

    @staticmethod
    def read_config(config_file):

        p2pcall_config_schema = Schema({
            Optional("general"):
            Default(
                {
                    Optional("user_db"): Default(StrVal(), default='memory'),
                    AutoDel(str): object  # for all other key we don't care
                },
                default={}),
            DoNotCare(str):
            object  # for all other key we don't care
        })
        #print('config file:', config_file)
        if config_file is None or config_file == '':
            config = p2pcall_config_schema.validate({})
        else:
            config = parse_config(config_file, p2pcall_config_schema)

        # check other configure option is valid or not

        return config

    @staticmethod
    def get_api_base_url(proxy_config):
        server_addr = None
        server_name = proxy_config['general']['server_name'].strip()
        if len(
                server_name
        ) > 0 and server_name != '127.0.0.1' and 'localhost' not in server_name:
            server_addr = server_name


#            try:
#                ip = socket.gethostbyname(server_name)
#                if ip and ip not in {'127.0.0.1', '0.0.0.0'}:
#                    server_addr = server_name
#            except socket.error as e:
#                # server_name is not a valid host domain name
#                pass
        listen_addr, sep, port = proxy_config['admin_api'][
            'http_listen'].strip().partition(':')
        if server_addr is None and listen_addr != '0.0.0.0':
            server_addr = listen_addr.strip()
        if server_addr is None:
            server_addr = get_host_ip()
        return 'http://' + server_addr + ':' + str(
            port) + JANUS_P2PCALL_API_BASE_PATH
Beispiel #2
0
class VideoCallPlugin(PluginBase):
    def __init__(self, proxy_config, backend_server_mgr, pyramid_config):
        super().__init__(proxy_config, backend_server_mgr, pyramid_config)
        self.config = self.read_config(
            os.path.join(proxy_config['general']['configs_folder'],
                         'janus-proxy.plugin.videocall.yml'))
        self.backend_server_mgr = backend_server_mgr

        # set up DAO
        from januscloud.proxy.dao.mem_videocall_user_dao import MemVideoCallUserDao
        if self.config['general']['user_db'] == 'memory':
            self.user_dao = MemVideoCallUserDao()
        else:
            raise JanusCloudError(
                'user_db url {} not support by videocall plugin'.format(
                    self.config['general']['user_db']),
                JANUS_ERROR_NOT_IMPLEMENTED)

        self.api_base_url = self.get_api_base_url(proxy_config)
        #print('api_base_url:', self.api_base_url)

        includeme(pyramid_config)
        pyramid_config.registry.videocall_plugin = self

        log.info('{} initialized!'.format(JANUS_VIDEOCALL_NAME))

    def get_version(self):
        return JANUS_VIDEOCALL_VERSION

    def get_version_string(self):
        return JANUS_VIDEOCALL_VERSION_STRING

    def get_description(self):
        return JANUS_VIDEOCALL_DESCRIPTION

    def get_name(self):
        return JANUS_VIDEOCALL_NAME

    def get_author(self):
        return JANUS_VIDEOCALL_AUTHOR

    def get_package(self):
        return JANUS_VIDEOCALL_PACKAGE

    def create_handle(self,
                      handle_id,
                      session,
                      opaque_id=None,
                      *args,
                      **kwargs):
        return VideoCallHandle(handle_id, session, self, opaque_id, *args,
                               **kwargs)

    def call_peer(self,
                  peer_username,
                  caller_username,
                  backend_server_url,
                  backend_keepalive_interval=10):
        peer = self.user_dao.get_by_username(peer_username)
        if peer is None:
            raise JanusCloudError(
                'Username \'{}\' doesn\'t exist'.format(peer_username),
                JANUS_VIDEOCALL_ERROR_NO_SUCH_USERNAME)
        if peer.handle:
            # the peer is handled by self
            peer.handle.handle_incoming_call(caller_username,
                                             backend_server_url)
        elif peer.api_url:
            # the peer is handled by the other janus-proxy
            caller = self.user_dao.get_by_username(caller_username)
            if caller is None or caller.handle is None:
                raise JanusCloudError('Not support relay http request',
                                      JANUS_VIDEOCALL_ERROR_INVALID_REQUEST)
            r = requests.post(peer.api_url,
                              data={
                                  'caller_username':
                                  caller_username,
                                  'backend_server_url':
                                  backend_server_url,
                                  'backend_keepalive_interval':
                                  str(backend_keepalive_interval)
                              })
            if r.status_code != requests.codes.ok:
                try:
                    text = r.json()['info']
                except Exception:
                    text = r.text
                raise JanusCloudError(text, r.status_code)

    @staticmethod
    def read_config(config_file):

        videocall_config_schema = Schema({
            Optional("general"):
            Default(
                {
                    Optional("user_db"): Default(StrVal(), default='memory'),
                    AutoDel(str): object  # for all other key we don't care
                },
                default={}),
            DoNotCare(str):
            object  # for all other key we don't care
        })
        #print('config file:', config_file)
        if config_file is None or config_file == '':
            config = videocall_config_schema.validate({})
        else:
            config = parse_config(config_file, videocall_config_schema)

        # check other configure option is valid or not

        return config

    @staticmethod
    def get_api_base_url(proxy_config):
        server_addr = None
        server_name = proxy_config['general']['server_name'].strip()
        if len(
                server_name
        ) > 0 and server_name != '127.0.0.1' and 'localhost' not in server_name:
            server_addr = server_name


#            try:
#                ip = socket.gethostbyname(server_name)
#                if ip and ip not in {'127.0.0.1', '0.0.0.0'}:
#                    server_addr = server_name
#            except socket.error as e:
#                # server_name is not a valid host domain name
#                pass
        listen_addr, sep, port = proxy_config['admin_api'][
            'http_listen'].strip().partition(':')
        if server_addr is None and listen_addr.strip() != '0.0.0.0':
            server_addr = listen_addr.strip()
        if server_addr is None:
            server_addr = get_host_ip()
        return 'http://' + server_addr + ':' + str(
            port) + JANUS_VIDEOCALL_API_BASE_PATH