Ejemplo n.º 1
0
    def _groupResults(self, results, formatter):
        """
        Group tests together based on their results.

        @param results: An iterable of tuples of two or more elements.  The
            first element of each tuple is a test case.  The remaining
            elements describe the outcome of that test case.

        @param formatter: A callable which turns a test case result into a
            string.  The elements after the first of the tuples in
            C{results} will be passed as positional arguments to
            C{formatter}.

        @return: A C{list} of two-tuples.  The first element of each tuple
            is a unique string describing one result from at least one of
            the test cases in C{results}.  The second element is a list of
            the test cases which had that result.
        """
        groups = OrderedDict()
        for content in results:
            case = content[0]
            outcome = content[1:]
            key = formatter(*outcome)
            groups.setdefault(key, []).append(case)
        return groups.items()
Ejemplo n.º 2
0
    def test_timeout(self):
        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({'timeout':'1'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.timeout, (1, 1, 1))
        self.assertEqual(opts, OrderedDict({'timeout':'1'}))

        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({'timeout':'foo'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.timeout, (1, 3, 5))
        self.assertEqual(opts, OrderedDict())

        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({'timeout':'0'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.timeout, (1, 3, 5))
        self.assertEqual(opts, OrderedDict())

        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({'timeout':'255'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.timeout, (255, 255, 255))
        self.assertEqual(opts, OrderedDict({'timeout':'255'}))

        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({'timeout':'256'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.timeout, (1, 3, 5))
        self.assertEqual(opts, OrderedDict())
Ejemplo n.º 3
0
    def test_blksize(self):
        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({'blksize':'8'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.block_size, 8)
        self.assertEqual(opts, OrderedDict({'blksize':'8'}))

        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({'blksize':'foo'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.block_size, 512)
        self.assertEqual(opts, OrderedDict())

        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({'blksize':'65464'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.block_size, MAX_BLOCK_SIZE)
        self.assertEqual(opts, OrderedDict({'blksize':str(MAX_BLOCK_SIZE)}))

        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({'blksize':'65465'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.block_size, 512)
        self.assertEqual(opts, OrderedDict())

        self.s = MockSession()
        opts = self.proto.processOptions(OrderedDict({'blksize':'7'}))
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.block_size, 512)
        self.assertEqual(opts, OrderedDict())
Ejemplo n.º 4
0
 def __init__(self, defer, appl, cookie, **kwargs):
     self.__cookie = cookie
     self.__appl = appl
     self.__legs = OrderedDict()
     self.__dict__.update(kwargs)
     self.__currentDTMFKey = None
     self.__collectedDTMFKeys = ''
     self.__dtmfSingleMode = True
     super(VoiceApp, self).__init__(defer, **kwargs)
Ejemplo n.º 5
0
 def __init__(self, remote, backend, options=None, _clock=None):
     if options is None:
         self.options = OrderedDict()
     else:
         self.options = options
     self.resultant_options = OrderedDict()
     self.remote = remote
     self.timeout_watchdog = None
     self.backend = backend
     if _clock is not None:
         self._clock = _clock
     else:
         self._clock = reactor
Ejemplo n.º 6
0
 def __init__(self, text=None):
     self.media = None
     self.nettype = 'IN'
     self.addrfamily = 'IP4'
     self.ipaddr = None
     self.port = None
     self.transport = None
     self.formats = []
     self._d = {}
     self._a = {}
     self.rtpmap = OrderedDict()
     self.media = 'audio'
     self.transport = 'RTP/AVP'
     self.keyManagement = None
     if text:
         parse_m(self, 'm', text)
Ejemplo n.º 7
0
 def intersect(self, other):
     # See RFC 3264
     map1 = self.rtpmap
     d1 = {}
     for code,(e,fmt) in map1.items():
         d1[rtpmap2canonical(code,e)] = e
     map2 = other.rtpmap
     outmap = OrderedDict()
     # XXX quadratic - make rtpmap an ordereddict
     for code, (e, fmt) in map2.items():
         canon = rtpmap2canonical(code,e)
         if d1.has_key(canon):
             outmap[code] = (e, fmt)
     self.rtpmap = outmap
     self.formats = [ str(x) for x in self.rtpmap.keys() ]
     self._a['rtpmap'] = OrderedDict([ (code,e) for (code, (e, fmt)) in outmap.items() ])
Ejemplo n.º 8
0
    def from_wire(cls, payload):
        """Parse the payload and return a RRQ/WRQ datagram object.

        @return: datagram object
        @rtype: L{RRQDatagram} or L{WRQDatagram}

        @raise OptionsDecodeError: if we failed to decode the options, requested
        by the client
        @raise PayloadDecodeError: if there were not enough fields in the payload.
        Fields are terminated by NUL.

        """
        parts = payload.split('\x00')
        try:
            filename, mode = parts.pop(0), parts.pop(0)
        except IndexError:
            raise PayloadDecodeError("Not enough fields in the payload")
        if parts and not parts[-1]:
            parts.pop(-1)
        options = OrderedDict()
        # To maintain consistency during testing.
        # The actual order of options is not important as per RFC2347
        if len(parts) % 2:
            raise OptionsDecodeError("No value for option %s" % parts[-1])
        for ind, opt_name in enumerate(parts[::2]):
            if opt_name in options:
                raise OptionsDecodeError("Duplicate option specified: %s" %
                                         opt_name)
            options[opt_name] = parts[ind * 2 + 1]
        return cls(filename, mode, options)
Ejemplo n.º 9
0
    def test_multiple_options(self):
        got_options = OrderedDict()
        got_options['timeout'] = '123'
        got_options['blksize'] = '1024'
        self.s = MockSession()
        opts = self.proto.processOptions(got_options)
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.timeout, (123, 123, 123))
        self.assertEqual(self.s.block_size, 1024)
        self.assertEqual(opts.items(), got_options.items())

        got_options = OrderedDict()
        got_options['blksize'] = '1024'
        got_options['timeout'] = '123'
        self.s = MockSession()
        opts = self.proto.processOptions(got_options)
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.timeout, (123, 123, 123))
        self.assertEqual(self.s.block_size, 1024)
        self.assertEqual(opts.items(), got_options.items())

        got_options = OrderedDict()
        got_options['blksize'] = '1024'
        got_options['foobar'] = 'barbaz'
        got_options['timeout'] = '123'
        self.s = MockSession()
        opts = self.proto.processOptions(got_options)
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.timeout, (123, 123, 123))
        self.assertEqual(self.s.block_size, 1024)
        actual_options = OrderedDict()
        actual_options['blksize'] = '1024'
        actual_options['timeout'] = '123'
        self.assertEqual(opts.items(), actual_options.items())
Ejemplo n.º 10
0
    def test_multiple_options(self):
        got_options = OrderedDict()
        got_options["timeout"] = "123"
        got_options["blksize"] = "1024"
        self.s = MockSession()
        opts = self.proto.processOptions(got_options)
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.timeout, (123, 123, 123))
        self.assertEqual(self.s.block_size, 1024)
        self.assertEqual(opts.items(), got_options.items())

        got_options = OrderedDict()
        got_options["blksize"] = "1024"
        got_options["timeout"] = "123"
        self.s = MockSession()
        opts = self.proto.processOptions(got_options)
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.timeout, (123, 123, 123))
        self.assertEqual(self.s.block_size, 1024)
        self.assertEqual(opts.items(), got_options.items())

        got_options = OrderedDict()
        got_options["blksize"] = "1024"
        got_options["foobar"] = "barbaz"
        got_options["timeout"] = "123"
        self.s = MockSession()
        opts = self.proto.processOptions(got_options)
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.timeout, (123, 123, 123))
        self.assertEqual(self.s.block_size, 1024)
        actual_options = OrderedDict()
        actual_options["blksize"] = "1024"
        actual_options["timeout"] = "123"
        self.assertEqual(opts.items(), actual_options.items())
Ejemplo n.º 11
0
 def intersect(self, other):
     # See RFC 3264
     map1 = self.rtpmap
     d1 = {}
     for code, (e, fmt) in list(map1.items()):
         d1[rtpmap2canonical(code, e)] = e
     map2 = other.rtpmap
     outmap = OrderedDict()
     # XXX quadratic - make rtpmap an ordereddict
     for code, (e, fmt) in list(map2.items()):
         canon = rtpmap2canonical(code, e)
         if canon in d1:
             outmap[code] = (e, fmt)
     self.rtpmap = outmap
     self.formats = [str(x) for x in list(self.rtpmap.keys())]
     self._a['rtpmap'] = OrderedDict([
         (code, e) for (code, (e, fmt)) in list(outmap.items())
     ])
Ejemplo n.º 12
0
 def __init__(self, defer, appl, cookie, **kwargs):
     self.__cookie = cookie
     self.__appl = appl
     self.__legs = OrderedDict()
     self.__dict__.update(kwargs)
     self.__currentDTMFKey = None
     self.__collectedDTMFKeys = ''
     self.__dtmfSingleMode = True
     super(VoiceApp, self).__init__(defer, **kwargs)
Ejemplo n.º 13
0
 def setUp(self):
     self.clock = Clock()
     self.tmp_dir_path = tempfile.mkdtemp()
     self.target = FilePath(self.tmp_dir_path).child('foo')
     self.writer = DelayedWriter(self.target, _clock=self.clock, delay=2)
     self.transport = FakeTransport(hostAddress=('127.0.0.1', self.port))
     self.options = OrderedDict()
     self.options['blksize'] = '9'
     self.options['tsize'] = '45'
     self.ws = RemoteOriginWriteSession(
         ('127.0.0.1', 65465), self.writer, options=self.options,
         _clock=self.clock)
     self.ws.transport = self.transport
Ejemplo n.º 14
0
    def call(self, *args, **kwargs):
        self.info("calling", self.name)
        in_arguments = self.get_in_arguments()
        self.info("in arguments", [a.get_name() for a in in_arguments])
        instance_id = 0
        for arg_name, arg in kwargs.iteritems():
            l = [ a for a in in_arguments if arg_name == a.get_name()]
            if len(l) > 0:
                in_arguments.remove(l[0])
            else:
                self.error("argument %s not valid for action %s" % (arg_name,self.name))
                return
            if arg_name == 'InstanceID':
                instance_id = int(arg)
        if len(in_arguments) > 0:
            self.error("argument %s missing for action %s" % ([ a.get_name() for a in in_arguments],self.name))
            return

        action_name = self.name

        if(hasattr(self.service.device.client, 'overlay_actions') and
           self.service.device.client.overlay_actions.has_key(self.name)):
            self.info("we have an overlay method %r for action %r", self.service.device.client.overlay_actions[self.name], self.name)
            action_name, kwargs = self.service.device.client.overlay_actions[self.name](**kwargs)
            self.info("changing action to %r %r", action_name, kwargs)

        def got_error(failure):
            self.warning("error on %s request with %s %s" % (self.name,self.
                                                            service.service_type,
                                                            self.service.control_url))
            self.info(failure)
            return failure

        if hasattr(self.service.device.client, 'overlay_headers'):
            self.info("action call has headers %r", kwargs.has_key('headers'))
            if kwargs.has_key('headers'):
                kwargs['headers'].update(self.service.device.client.overlay_headers)
            else:
                kwargs['headers'] = self.service.device.client.overlay_headers
            self.info("action call with new/updated headers %r", kwargs['headers'])

        client = self._get_client()

        ordered_arguments = OrderedDict()
        for argument in self.get_in_arguments():
            ordered_arguments[argument.name] = kwargs[argument.name]

        d = client.callRemote(action_name, ordered_arguments)
        d.addCallback(self.got_results, instance_id=instance_id, name=action_name)
        d.addErrback(got_error)
        return d
Ejemplo n.º 15
0
    def get_action_results(self, result, action, instance):
        """ check for out arguments
            if yes: check if there are related ones to StateVariables with
                    non A_ARG_TYPE_ prefix
                    if yes: check if there is a call plugin method for this action
                            if yes: update StateVariable values with call result
                            if no:  get StateVariable values and
                                    add them to result dict
        """
        self.debug('get_action_results', result)
        #print 'get_action_results', action, instance
        notify = []
        for argument in action.get_out_arguments():
            #print 'get_state_variable_contents', argument.name
            if argument.name[0:11] != 'A_ARG_TYPE_':
                variable = self.variables[instance][argument.get_state_variable()]
                variable.update(result[argument.name].decode('utf-8').encode('utf-8'))
                #print 'update state variable contents', variable.name, variable.value, variable.send_events
                if(variable.send_events == 'yes' and variable.moderated == False):
                    notify.append(variable)

            self.service.propagate_notification(notify)
        self.info( 'action_results unsorted', action.name, result)
        if len(result) == 0:
            return result
        ordered_result = OrderedDict()
        for argument in action.get_out_arguments():
            if action.name  == 'XXXBrowse' and argument.name == 'Result':
                didl = DIDLLite.DIDLElement.fromString(result['Result'].decode('utf-8'))
                changed = False
                for item in didl.getItems():
                    new_res = DIDLLite.Resources()
                    for res in item.res:
                        remote_protocol,remote_network,remote_content_format,_ = res.protocolInfo.split(':')
                        if remote_protocol == 'http-get' and remote_network == '*':
                            quoted_url = urllib.quote_plus(res.data)
                            #print "modifying", res.data
                            res.data = urlparse.urlunsplit(('http', self.service.device.external_address,'mirabeau',quoted_url,""))
                            #print "--->", res.data
                            new_res.append(res)
                            changed = True
                    item.res = new_res
                if changed == True:
                    didl.rebuild()
                    ordered_result[argument.name] = didl.toString().replace('<ns0:','<')
                else:
                    ordered_result[argument.name] = result[argument.name].decode('utf-8')
            else:
                ordered_result[argument.name] = result[argument.name].decode('utf-8').encode('utf-8')
        self.info( 'action_results sorted', action.name, ordered_result)
        return ordered_result
Ejemplo n.º 16
0
 def setUp(self):
     self.clock = Clock()
     self.tmp_dir_path = tempfile.mkdtemp()
     self.target = FilePath(self.tmp_dir_path).child('foo')
     with self.target.open('wb') as temp_fd:
         temp_fd.write(self.test_data)
     self.reader = DelayedReader(self.target, _clock=self.clock, delay=2)
     self.transport = FakeTransport(hostAddress=('127.0.0.1', self.port))
     self.options = OrderedDict()
     self.options['blksize'] = '9'
     self.options['tsize'] = '34'
     self.rs = RemoteOriginReadSession(('127.0.0.1', 65465), self.reader,
                                       options=self.options, _clock=self.clock)
     self.rs.transport = self.transport
Ejemplo n.º 17
0
    def _groupResults(self, results, formatter):
        """
        Group tests together based on their results.

        @param results: An iterable of tuples of two or more elements.  The
            first element of each tuple is a test case.  The remaining
            elements describe the outcome of that test case.

        @param formatter: A callable which turns a test case result into a
            string.  The elements after the first of the tuples in
            C{results} will be passed as positional arguments to
            C{formatter}.

        @return: A C{list} of two-tuples.  The first element of each tuple
            is a unique string describing one result from at least one of
            the test cases in C{results}.  The second element is a list of
            the test cases which had that result.
        """
        groups = OrderedDict()
        for content in results:
            case = content[0]
            outcome = content[1:]
            key = formatter(*outcome)
            groups.setdefault(key, []).append(case)
Ejemplo n.º 18
0
 def addRtpMap(self, fmt):
     if fmt.pt is None:
         pts = list(self.rtpmap.keys())
         pts.sort()
         if pts and pts[-1] > 100:
             payload = pts[-1] + 1
         else:
             payload = 101
     else:
         payload = fmt.pt
     rtpmap = "%d %s/%d%s%s" % (payload, fmt.name, fmt.clock, (
         (fmt.params and '/') or ""), fmt.params or "")
     self.rtpmap[int(payload)] = (rtpmap, fmt)
     self._a.setdefault('rtpmap', OrderedDict())[payload] = rtpmap
     self.formats.append(str(payload))
Ejemplo n.º 19
0
 def __init__(self, text=None):
     self.media = None
     self.nettype = 'IN'
     self.addrfamily = 'IP4'
     self.ipaddr = None
     self.port = None
     self.transport = None
     self.formats = []
     self._d = {}
     self._a = {}
     self.rtpmap = OrderedDict()
     self.media = 'audio'
     self.transport = 'RTP/AVP'
     self.keyManagement = None
     if text:
         parse_m(self, 'm', text)
Ejemplo n.º 20
0
 def __init__(self, text=None):
     from time import time
     self._id = None
     self._d = {'v': '0', 't': '0 0', 's': 'sropulpof_midi'}
     self._a = OrderedDict()
     self.mediaDescriptions = []
     # XXX Use the username preference
     self._o_username = '******'
     self._o_sessid = self._o_version = str(int(time() % 1000 * 100))
     self._o_nettype = self.nettype = 'IN'
     self._o_addrfamily = self.addrfamily = 'IP4'
     self._o_ipaddr = self.ipaddr = None
     self.port = None
     if text:
         self.parse(text)
         self.assertSanity()
     else:
         # new SDP
         pass
Ejemplo n.º 21
0
    def processOptions(self, options):
        """Process options mapping, discarding malformed or unknown options.

        @param options: options mapping to process
        @type options: L{OrderedDict<twisted.python.util.OrderedDict>}

        @return: a mapping of processed options. Invalid options are discarded.
        Whether or not the values of options may be changed is decided on a per-
        option basis, according to the standard
        @rtype L{OrderedDict<twisted.python.util.OrderedDict>}

        """
        accepted_options = OrderedDict()
        for name, val in options.iteritems():
            norm_name = name.lower()
            if norm_name in self.supported_options:
                actual_value = getattr(self, 'option_' + norm_name)(val)
                if actual_value is not None:
                    accepted_options[name] = actual_value
        return accepted_options
Ejemplo n.º 22
0
class TestServerFactory:
    implements(pop3.IServerFactory)

    def cap_IMPLEMENTATION(self):
        return "Test Implementation String"

    def cap_EXPIRE(self):
        return 60

    challengers = OrderedDict([("SCHEME_1", None), ("SCHEME_2", None)])

    def cap_LOGIN_DELAY(self):
        return 120

    pue = True
    def perUserExpiration(self):
        return self.pue

    puld = True
    def perUserLoginDelay(self):
        return self.puld
Ejemplo n.º 23
0
 def get_action_results(self, result, action, instance):
     """ check for out arguments
         if yes: check if there are related ones to StateVariables with
                 non A_ARG_TYPE_ prefix
                 if yes: check if there is a call plugin method for this action
                         if yes: update StateVariable values with call result
                         if no:  get StateVariable values and
                                 add them to result dict
     """
     self.debug('get_action_results', result)
     #print 'get_action_results', action, instance
     r = result
     notify = []
     for argument in action.get_out_arguments():
         #print 'get_state_variable_contents', argument.name
         if argument.name[0:11] != 'A_ARG_TYPE_':
             if action.get_callback() != None:
                 variable = self.variables[instance][
                     argument.get_state_variable()]
                 variable.update(r[argument.name])
                 #print 'update state variable contents', variable.name, variable.value, variable.send_events
                 if (variable.send_events == 'yes'
                         and variable.moderated == False):
                     notify.append(variable)
             else:
                 variable = self.variables[instance][
                     argument.get_state_variable()]
                 #print 'get state variable contents', variable.name, variable.value
                 r[argument.name] = variable.value
                 #print "r", r
         self.service.propagate_notification(notify)
     #r= { '%sResponse'%action.name: r}
     self.info('action_results unsorted', action.name, r)
     if len(r) == 0:
         return r
     ordered_result = OrderedDict()
     for argument in action.get_out_arguments():
         ordered_result[argument.name] = r[argument.name]
     self.info('action_results sorted', action.name, ordered_result)
     return ordered_result
Ejemplo n.º 24
0
def parse_a(obj, a, text):
    words = text.split(':', 1)
    if len(words) > 1:
        # I don't know what is happening here, but I got a traceback here
        # because 'words' was too long before the ,1 was added.  The value was:
        # ['alt', '1 1 ', ' 55A94DDE 98A2400C *ip address elided* 6086']
        # Adding the ,1 seems to fix it but I don't know why. -glyph
        attr, attrvalue = words
    else:
        attr, attrvalue = text, None
    if attr == 'rtpmap':
        payload, info = attrvalue.split(' ')
        entry = rtpmap2canonical(int(payload), attrvalue)
        try:
            fmt = RTPDict[entry]
        except KeyError:
            name, clock, params = entry
            fmt = PTMarker(name, None, clock, params)
        obj.rtpmap[int(payload)] = (attrvalue, fmt)
        obj._a.setdefault(attr, OrderedDict())[int(payload)] = attrvalue
    else:
        obj._a.setdefault(attr, []).append(attrvalue)
Ejemplo n.º 25
0
    def from_wire(cls, payload):
        """Parse the payload and return an OACK datagram object.

        @return: datagram object
        @rtype: L{OACKDatagram}

        @raise OptionsDecodeError: if we failed to decode the options

        """
        parts = payload.split('\x00')
        #FIXME: Boo, code duplication
        if parts and not parts[-1]:
            parts.pop(-1)
        options = OrderedDict()
        if len(parts) % 2:
            raise OptionsDecodeError("No value for option %s" % parts[-1])
        for ind, opt_name in enumerate(parts[::2]):
            if opt_name in options:
                raise OptionsDecodeError("Duplicate option specified: %s" %
                                         opt_name)
            options[opt_name] = parts[ind * 2 + 1]
        return cls(options)
Ejemplo n.º 26
0
    def component_headers(self, element, args):
        """Format all relevant commit metadata in an email-style header box"""
        from LibCIA.Web import Template

        message = args.message
        commit = XML.dig(message.xml, "message", "body", "commit")
        source = XML.dig(message.xml, "message", "source")
        author = XML.dig(commit, "author")
        version = XML.dig(commit, "version")
        revision = XML.dig(commit, "revision")
        diffLines = XML.dig(commit, "diffLines")
        url = XML.dig(commit, "url")
        log = XML.dig(commit, "log")
        project = XML.dig(source, "project")
        module = XML.dig(source, "module")
        branch = XML.dig(source, "branch")
        headers = OrderedDict()

        if author:
            headers['Author'] = XML.shallowText(author)
        if project:
            headers['Project'] = XML.shallowText(project)
        if module:
            headers['Module'] = XML.shallowText(module)
        if branch:
            headers['Branch'] = XML.shallowText(branch)
        if version:
            headers['Version'] = XML.shallowText(version)
        if revision:
            headers['Revision'] = XML.shallowText(revision)
        if diffLines:
            headers['Changed Lines'] = XML.shallowText(diffLines)
        if url:
            headers['URL'] = tag(
                'a', href=XML.shallowText(url))[Util.extractSummary(url)]

        return [Template.MessageHeaders(headers)]
Ejemplo n.º 27
0
class VoiceApp(StateMachine):

    _inbound = None

    def __init__(self, defer, appl, cookie, **kwargs):
        self.__cookie = cookie
        self.__appl = appl
        self.__legs = OrderedDict()
        self.__dict__.update(kwargs)
        self.__currentDTMFKey = None
        self.__collectedDTMFKeys = ''
        self.__dtmfSingleMode = True
        super(VoiceApp, self).__init__(defer, **kwargs)

    def getDefaultLeg(self):
        if self.__legs:
            return self.__legs.values()[0]

    def getLeg(self, cookie):
        return self.__legs.get(cookie)

    def setLeg(self, leg, cookie):
        self.__legs[cookie] = leg
        #self.leg.hijackLeg(self)

    def va_selectDefaultFormat(self, ptlist, callcookie):
        return self.getLeg(callcookie).selectDefaultFormat(ptlist)

    def va_incomingRTP(self, packet, callcookie):
        leg = self.getLeg(callcookie)
        if leg is None:
            log.msg('no leg for cookie %s for incoming RTP'%(callcookie,),
                                                                system='doug')
            return
        else:
            return leg.leg_incomingRTP(packet)

    def va_outgoingRTP(self, sample, cookie=None):
        if cookie is None:
            cookie = self.__cookie
        self.__appl.outgoingRTP(cookie, sample)

    def va_start(self, args):
        self._start(callstart=0, args=args)

    def va_callstart(self, inboundLeg, args=None):
        if args is None:
            args = {}
        if inboundLeg is not None:
            self.__legs[inboundLeg.getCookie()] = inboundLeg
            if self._inbound is None:
                self._inbound = inboundLeg
        ce = CallStartedEvent(inboundLeg)
        ce.args = args
        self._triggerEvent(ce)

    def va_callanswered(self, leg=None):
        if leg is None:
            leg = self._inbound
        self._triggerEvent(CallAnsweredEvent(leg))

    def va_callrejected(self, leg=None):
        if leg is None:
            leg = self._inbound
        try:
            del self.__legs[leg]
        except KeyError:
            log.msg("can't find leg %s, current legs: %r"%(
                                    leg, self.__legs.keys()),
                                    system='doug')
        self._triggerEvent(CallRejectedEvent(leg))

    def _clear_legs(self):
        from shtoom.util import stack
        #print self, "clearing running legs %r"%(self.__legs.items())#,stack(8)
        for name, leg in self.__legs.items():
            leg._stopAudio()
            del self.__legs[name]

    _cleanup = _clear_legs

    def va_abort(self):
        self.mediaStop()
        self._clear_legs()
        self._triggerEvent(CallEndedEvent(None))

    def mediaPlay(self, playlist, leg=None):
        if leg is None:
            leg = self.getDefaultLeg()
        leg.mediaPlay(playlist)

    def mediaRecord(self, dest, leg=None):
        if leg is None:
            leg = self.getDefaultLeg()
        leg.mediaRecord(dest)

    def mediaStop(self, leg=None):
        if leg is None:
            leg = self.getDefaultLeg()
        if leg is not None:
            leg.mediaStop()

    def mediaStopRecording(self, leg=None):
        if leg is None:
            leg = self.getDefaultLeg()
        if leg is not None:
            leg.mediaStopRecording()

    def setTimer(self, delay):
        return Timer(self, delay)

    def isPlaying(self, leg=None):
        if leg is None:
            leg = self.getDefaultLeg()
        return leg.isPlaying()

    def isRecording(self, leg=None):
        if leg is None:
            leg = self.getDefaultLeg()
        return leg.isRecording()

    def dtmfMode(self, single=False, inband=False, timeout=0, leg=None):
        if leg is None:
            leg = self.getDefaultLeg()
        leg.dtmfMode(single, inband, timeout)

    def placeCall(self, toURI, fromURI=None):
        from shtoom.doug.leg import Leg
        nleg = Leg(cookie=None, dialog=None, voiceapp=self)
        self.__appl.placeCall(self.__cookie, nleg, toURI, fromURI)

    def va_hangupCall(self, cookie):
        self.__appl.dropCall(cookie)

    def connectLegs(self, leg1, leg2=None):
        from shtoom.doug.leg import Bridge

        if leg2 is None:
            leg2 = self.getDefaultLeg()
        if leg1 is leg2:
            raise ValueError, "can't join %r to itself!"%(leg1)
        else:
            b = Bridge(leg1, leg2)
            return b

    def sendDTMF(self, digits, cookie=None, duration=0.1, delay=0.05):
        "Send a string of DTMF keystrokes"
        for n,key in enumerate(digits):
            if key not in ',01234567890#*':
                raise ValueError, key
            if key == ',':
                # pause
                continue
            n = float(n) # just in case
            if cookie is None:
                cookie = self.__cookie
            i = 0.2
            reactor.callLater(i+n*(duration+delay),
                lambda k=key: self.__appl.startDTMF(cookie, k))
            reactor.callLater(i+n*(duration+delay)+duration,
                lambda k=key: self.__appl.stopDTMF(cookie, k))

    def _inboundDTMFKeyPress(self, dtmf):
        if self.__dtmfSingleMode:
            self._triggerEvent(DTMFReceivedEvent(dtmf, self))
        else:
            self.__collectedDTMFKeys += dtmf
            if dtmf in ('#', '*'):
                dtmf, self.__collectedDTMFKeys = self.__collectedDTMFKeys, ''
                self._triggerEvent(DTMFReceivedEvent(dtmf, self))

    def va_startDTMFevent(self, dtmf, cookie=None):
        c = self.__currentDTMFKey
        if dtmf:
            if c is not dtmf:
                self.va_stopDTMFevent(c)
                self.__currentDTMFKey = dtmf
                self._inboundDTMFKeyPress(dtmf)
            else:
                # repeat
                pass

    def va_stopDTMFevent(self, dtmf, cookie=None):
        # For now, I only care about dtmf start events
        if dtmf == self.__currentDTMFKey:
            self.__currentDTMFKey = None
Ejemplo n.º 28
0
 def clear(self):
     """Remove every item from the dict."""
     self._order = []
     TxOrderedDict.clear(self)
Ejemplo n.º 29
0
 def test_empty_options(self):
     self.s = MockSession()
     opts = self.proto.processOptions(OrderedDict())
     self.proto.applyOptions(self.s, opts)
     self.assertEqual(self.s.block_size, 512)
     self.assertEqual(self.s.timeout, (1, 3, 5))
Ejemplo n.º 30
0
 def clearRtpMap(self):
     self.rtpmap = OrderedDict()
Ejemplo n.º 31
0
    def update_progress(self):
        """Update the list of recent transfers and current transfers."""
        recent_transfers = self.status_frontend.recent_transfers()
        current_transfers = self.status_frontend.files_uploading()
        current_transfers.sort(key=itemgetter(2))
        current_transfers.reverse()
        uploading_data = OrderedDict()
        for filename, size, written in current_transfers:
            uploading_data[filename] = (size, written)

        temp_transfers = {}
        if recent_transfers != self.previous_transfers:
            logger.debug("Update recent transfers with: %r", recent_transfers)
            for item_transfer in self._transfers_items:
                self.child_delete(self._transfers_items[item_transfer])
            for item in recent_transfers:
                recent_file = Dbusmenu.Menuitem()
                recent_file.property_set(
                    Dbusmenu.MENUITEM_PROP_LABEL, item.replace('_', '__'))
                self.child_add_position(recent_file, 0)
                temp_transfers[item] = recent_file
            self._transfers_items = temp_transfers

        if self.separator is None:
            self.separator = Dbusmenu.Menuitem()
            self.separator.property_set(
                Dbusmenu.MENUITEM_PROP_TYPE, Dbusmenu.CLIENT_TYPES_SEPARATOR)
            self.child_append(self.separator)

        items_added = 0
        remove = []
        for item in self._uploading_items:
            if item in uploading_data.keys():
                size, written = uploading_data[item]
                percentage = written * 100 / size
                upload_item = self._uploading_items[item]
                upload_item.property_set_int(
                    SyncMenu.PROGRESS_MENUITEM_PROP_PERCENT_DONE,
                    percentage)
                logger.debug(
                    "Current transfer %s progress update: %r",
                    item, percentage)
                items_added += 1
            else:
                self.child_delete(self._uploading_items[item])
                remove.append(item)
        for item in remove:
            self._uploading_items.pop(item)
        if items_added < 5:
            for item in uploading_data.keys():
                if item not in self._uploading_items and items_added < 5:
                    size, written = uploading_data[item]
                    percentage = written * 100 / size
                    uploading_file = Dbusmenu.Menuitem()
                    uploading_file.property_set(
                        Dbusmenu.MENUITEM_PROP_LABEL, item.replace('_', '__'))
                    uploading_file.property_set(
                        Dbusmenu.MENUITEM_PROP_TYPE,
                        SyncMenu.PROGRESS_MENUITEM_TYPE)
                    uploading_file.property_set_int(
                        SyncMenu.PROGRESS_MENUITEM_PROP_PERCENT_DONE,
                        percentage)
                    logger.debug("Current transfer %s created", item)
                    self.child_append(uploading_file)
                    self._uploading_items[item] = uploading_file
                    items_added += 1
Ejemplo n.º 32
0
class MediaDescription:
    "The MediaDescription encapsulates all of the SDP media descriptions"
    def __init__(self, text=None):
        self.media = None
        self.nettype = 'IN'
        self.addrfamily = 'IP4'
        self.ipaddr = None
        self.port = None
        self.transport = None
        self.formats = []
        self._d = {}
        self._a = {}
        self.rtpmap = OrderedDict()
        self.media = 'audio'
        self.transport = 'RTP/AVP'
        self.keyManagement = None
        if text:
            parse_m(self, 'm', text)

    def setFormats(self, formats):
        if self.media in ( 'audio', 'video'):
            for pt in formats:
                pt = int(pt)
                if pt < 97:
                    try:
                        PT = RTPDict[pt]
                    except KeyError:
                        # We don't know this one - hopefully there's an
                        # a=rtpmap entry for it.
                        continue
                    self.addRtpMap(PT)
                    # XXX the above line is unbound local variable error if not RTPDict.has_key(pt) --Zooko 2004-09-29
        self.formats = formats

    def setMedia(self, media):
        self.media = media
    def setTransport(self, transport):
        self.transport = transport
    def setServerIP(self, l):
        self.ipaddr = l
    def setLocalPort(self, l):
        self.port = l

    def setKeyManagement(self, km):
        parse_a(self, 'keymgmt', km)

    def clearRtpMap(self):
        self.rtpmap = OrderedDict()

    def addRtpMap(self, fmt):
        if fmt.pt is None:
            pts = self.rtpmap.keys()
            pts.sort()
            if pts and pts[-1] > 100:
                payload = pts[-1] + 1
            else:
                payload = 101
        else:
            payload = fmt.pt
        rtpmap = "%d %s/%d%s%s"%(payload, fmt.name, fmt.clock,
                                 ((fmt.params and '/') or ""),
                                 fmt.params or "")
        self.rtpmap[int(payload)] = (rtpmap, fmt)
        self._a.setdefault('rtpmap', OrderedDict())[payload] = rtpmap
        self.formats.append(str(payload))

    def addFMTP(self, streamtype, mode="rtp-midi", profile_level=12, config=0):
        """specific for midirtp"""
        payload = 96
        fmtp = "%d streamtype=%d; mode=%s; profile-level-id=%d; config=%d" % (payload, streamtype, mode, profile_level, config)
        self._a.setdefault('fmtp', OrderedDict())[96]= fmtp

    def intersect(self, other):
        # See RFC 3264
        map1 = self.rtpmap
        d1 = {}
        for code,(e,fmt) in map1.items():
            d1[rtpmap2canonical(code,e)] = e
        map2 = other.rtpmap
        outmap = OrderedDict()
        # XXX quadratic - make rtpmap an ordereddict
        for code, (e, fmt) in map2.items():
            canon = rtpmap2canonical(code,e)
            if d1.has_key(canon):
                outmap[code] = (e, fmt)
        self.rtpmap = outmap
        self.formats = [ str(x) for x in self.rtpmap.keys() ]
        self._a['rtpmap'] = OrderedDict([ (code,e) for (code, (e, fmt)) in outmap.items() ])
Ejemplo n.º 33
0
#PT_L8 =         AudioPTMarker('L8',      clock=None,  params=1)
#PT_RED =        AudioPTMarker('RED',     clock=8000,  params=1)
#PT_VDVI =       AudioPTMarker('VDVI',    clock=None,  params=1)
PT_NTE = PTMarker('telephone-event', clock=8000, params=None, fmtp='0-16')
# Internal shtoom codec. Note that the L16 format, above, is at 44100 KHz.
PT_RAW = AudioPTMarker('RAW_L16', clock=8000, params=1)

PT_CELB = VideoPTMarker('CelB', clock=90000, pt=25)
PT_JPEG = VideoPTMarker('JPEG', clock=90000, pt=26)
PT_NV = VideoPTMarker('nv', clock=90000, pt=28)
PT_H261 = VideoPTMarker('H261', clock=90000, pt=31)
PT_MPV = VideoPTMarker('MPV', clock=90000, pt=32)
PT_MP2T = VideoPTMarker('MP2T', clock=90000, pt=33)
PT_H263 = VideoPTMarker('H263', clock=90000, pt=34)

TryCodecs = OrderedDict()
#TryCodecs[PT_GSM] = codecs.gsm
#TryCodecs[PT_SPEEX] = codecs.speex
#TryCodecs[PT_DVI4] = codecs.dvi4
#TryCodecs[PT_ILBC] = codecs.ilbc


class SDPGenerator:
    "Responsible for generating SDP for the RTPProtocol"

    def getSDP(self, rtp, extrartp=None):
        from sdp import SDP, MediaDescription
        if extrartp:
            raise ValueError("can't handle multiple RTP streams in a call yet")
        s = SDP()
        addr = rtp.getVisibleAddress()
Ejemplo n.º 34
0
    def test_multiple_options(self):
        got_options = OrderedDict()
        got_options['timeout'] = '123'
        got_options['blksize'] = '1024'
        self.s = MockSession()
        opts = self.proto.processOptions(got_options)
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.timeout, (123, 123, 123))
        self.assertEqual(self.s.block_size, 1024)
        self.assertEqual(opts.items(), got_options.items())

        got_options = OrderedDict()
        got_options['blksize'] = '1024'
        got_options['timeout'] = '123'
        self.s = MockSession()
        opts = self.proto.processOptions(got_options)
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.timeout, (123, 123, 123))
        self.assertEqual(self.s.block_size, 1024)
        self.assertEqual(opts.items(), got_options.items())

        got_options = OrderedDict()
        got_options['blksize'] = '1024'
        got_options['foobar'] = 'barbaz'
        got_options['timeout'] = '123'
        self.s = MockSession()
        opts = self.proto.processOptions(got_options)
        self.proto.applyOptions(self.s, opts)
        self.assertEqual(self.s.timeout, (123, 123, 123))
        self.assertEqual(self.s.block_size, 1024)
        actual_options = OrderedDict()
        actual_options['blksize'] = '1024'
        actual_options['timeout'] = '123'
        self.assertEqual(opts.items(), actual_options.items())
Ejemplo n.º 35
0
 def __init__(self, serviceName, serviceParent=None):
     MultiService.__init__(self, serviceName, serviceParent)
     self.services = OrderedDict(self.services)
Ejemplo n.º 36
0
class MediaDescription:
    "The MediaDescription encapsulates all of the SDP media descriptions"

    def __init__(self, text=None):
        self.media = None
        self.nettype = 'IN'
        self.addrfamily = 'IP4'
        self.ipaddr = None
        self.port = None
        self.transport = None
        self.formats = []
        self._d = {}
        self._a = {}
        self.rtpmap = OrderedDict()
        self.media = 'audio'
        self.transport = 'RTP/AVP'
        self.keyManagement = None
        if text:
            parse_m(self, 'm', text)

    def setFormats(self, formats):
        if self.media in ('audio', 'video'):
            for pt in formats:
                pt = int(pt)
                if pt < 97:
                    try:
                        PT = RTPDict[pt]
                    except KeyError:
                        # We don't know this one - hopefully there's an
                        # a=rtpmap entry for it.
                        continue
                    self.addRtpMap(PT)
                    # XXX the above line is unbound local variable error if not RTPDict.has_key(pt) --Zooko 2004-09-29
        self.formats = formats

    def setMedia(self, media):
        self.media = media

    def setTransport(self, transport):
        self.transport = transport

    def setServerIP(self, l):
        self.ipaddr = l

    def setLocalPort(self, l):
        self.port = l

    def setKeyManagement(self, km):
        parse_a(self, 'keymgmt', km)

    def clearRtpMap(self):
        self.rtpmap = OrderedDict()

    def addRtpMap(self, fmt):
        if fmt.pt is None:
            pts = list(self.rtpmap.keys())
            pts.sort()
            if pts and pts[-1] > 100:
                payload = pts[-1] + 1
            else:
                payload = 101
        else:
            payload = fmt.pt
        rtpmap = "%d %s/%d%s%s" % (payload, fmt.name, fmt.clock, (
            (fmt.params and '/') or ""), fmt.params or "")
        self.rtpmap[int(payload)] = (rtpmap, fmt)
        self._a.setdefault('rtpmap', OrderedDict())[payload] = rtpmap
        self.formats.append(str(payload))

    def addFMTP(self, streamtype, mode="rtp-midi", profile_level=12, config=0):
        """specific for midirtp"""
        payload = 96
        fmtp = "%d streamtype=%d; mode=%s; profile-level-id=%d; config=%d" % (
            payload, streamtype, mode, profile_level, config)
        self._a.setdefault('fmtp', OrderedDict())[96] = fmtp

    def intersect(self, other):
        # See RFC 3264
        map1 = self.rtpmap
        d1 = {}
        for code, (e, fmt) in list(map1.items()):
            d1[rtpmap2canonical(code, e)] = e
        map2 = other.rtpmap
        outmap = OrderedDict()
        # XXX quadratic - make rtpmap an ordereddict
        for code, (e, fmt) in list(map2.items()):
            canon = rtpmap2canonical(code, e)
            if canon in d1:
                outmap[code] = (e, fmt)
        self.rtpmap = outmap
        self.formats = [str(x) for x in list(self.rtpmap.keys())]
        self._a['rtpmap'] = OrderedDict([
            (code, e) for (code, (e, fmt)) in list(outmap.items())
        ])
Ejemplo n.º 37
0
    def call(self, *args, **kwargs):
        self.info(f'calling {self.name}')
        in_arguments = self.get_in_arguments()
        args_names = [a.get_name() for a in in_arguments]
        self.info(f'in arguments {args_names}')
        instance_id = 0
        for arg_name, arg in kwargs.items():
            al = [a for a in in_arguments if arg_name == a.get_name()]
            if len(al) > 0:
                in_arguments.remove(al[0])
            else:
                self.error(
                    f'argument {arg_name} not valid for action {self.name}', )
                return
            if arg_name == 'InstanceID':
                instance_id = int(arg)
        if len(in_arguments) > 0:
            args_names = [a.get_name() for a in in_arguments]
            self.error(
                f'argument {[args_names]} '
                f'missing for action {self.name}', )
            return

        action_name = self.name

        if (hasattr(self.service.device.client, 'overlay_actions')
                and self.name in self.service.device.client.overlay_actions):
            self.info(
                f'we have an overlay method ' +
                f'{self.service.device.client.overlay_actions[self.name]} ' +
                f'for action {self.name}')
            action_name, kwargs = self.service.device.client.overlay_actions[
                self.name](**kwargs)
            self.info(f'changing action to {action_name} {kwargs}')

        def got_error(failure):
            self.warning(f'error on {self.name} request with ' +
                         f'{self.service.service_type} ' +
                         f'{self.service.control_url}')
            self.info(failure)
            return failure

        if hasattr(self.service.device.client, 'overlay_headers'):
            self.info(f'action call has headers {"headers"}' in kwargs)
            if 'headers' in kwargs:
                kwargs['headers'].update(
                    self.service.device.client.overlay_headers)
            else:
                kwargs['headers'] = self.service.device.client.overlay_headers
            self.info(f'action call with new/updated headers '
                      f'{kwargs["headers"]}')

        client = self._get_client()

        ordered_arguments = OrderedDict()
        for argument in self.get_in_arguments():
            ordered_arguments[argument.name] = kwargs[argument.name]
        if 'headers' in kwargs:
            ordered_arguments['headers'] = kwargs['headers']

        d = client.callRemote(action_name, ordered_arguments)
        d.addCallback(self.got_results,
                      instance_id=instance_id,
                      name=action_name)
        d.addErrback(got_error)
        return d
Ejemplo n.º 38
0
    def get_action_results(self, result, action, instance):
        '''
        Check for out arguments, if yes:

            - check if there are related ones to StateVariables with
              non `A_ARG_TYPE_ prefix`, if yes:

                - check if there is a call plugin method for this action:

                    - if yes => update StateVariable values with call result.
                    - if no  => get StateVariable values and add them to
                      the result dict.

        '''
        self.debug(f'get_action_results {result}')
        # print 'get_action_results', action, instance
        notify = []
        for argument in action.get_out_arguments():
            # print 'get_state_variable_contents', argument.name
            if argument.name[0:11] != 'A_ARG_TYPE_':
                variable = self.variables[instance][
                    argument.get_state_variable()]
                variable.update(
                    result[argument.name].decode('utf-8').encode('utf-8'))
                # print('update state variable contents',
                #       variable.name, variable.value, variable.send_events)
                if (variable.send_events == 'yes'
                        and variable.moderated is False):
                    notify.append(variable)

            self.service.propagate_notification(notify)
        self.info(f'action_results unsorted {action.name} {result}')
        if len(result) == 0:
            return result
        ordered_result = OrderedDict()
        for argument in action.get_out_arguments():
            if action.name == 'XXXBrowse' and argument.name == 'Result':
                didl = DIDLLite.DIDLElement.fromString(
                    result['Result'].decode('utf-8'))
                changed = False
                for item in didl.getItems():
                    new_res = DIDLLite.Resources()
                    for res in item.res:
                        (
                            remote_protocol,
                            remote_network,
                            remote_content_format,
                            _,
                        ) = res.protocolInfo.split(':')
                        if (remote_protocol == 'http-get'
                                and remote_network == '*'):
                            quoted_url = urllib.parse.quote_plus(res.data)
                            res.data = urllib.parse.urlunsplit((
                                'http',
                                self.service.device.external_address,
                                'mirabeau',
                                quoted_url,
                                '',
                            ))
                            new_res.append(res)
                            changed = True
                    item.res = new_res
                if changed:
                    didl.rebuild()
                    ordered_result[argument.name] = didl.toString()
                else:
                    ordered_result[argument.name] = result[
                        argument.name].decode('utf-8')
            else:
                ordered_result[argument.name] = (
                    result[argument.name].decode('utf-8').encode('utf-8'))
        self.info(f'action_results sorted {action.name} {ordered_result}')
        return ordered_result
Ejemplo n.º 39
0
 def clearRtpMap(self):
     self.rtpmap = OrderedDict()
Ejemplo n.º 40
0
class DependentMultiService(MultiService):
    """
    I am a MultiService that starts services in insert order,
    and stops them in the reverse order.  The service starts
    and stops are chained, so be very careful about services
    that may fail to start or stop.
    """
    def __init__(self, serviceName, serviceParent=None):
        MultiService.__init__(self, serviceName, serviceParent)
        self.services = OrderedDict(self.services)
    def _finishStartService(self, res):
        return ApplicationService.startService(self) or defer.succeed(None)
    def _rollbackStartedServices(self, failure, service):
        v = self.services.values()
        startedServices = v[:v.index(service)]
        startedServices.reverse()
        for svc in startedServices:
            svc.stopService()
        return failure
    def startService(self):
        """
        Start all of my Services.
        I return a Deferred that will callback (with no useful result)
        when all services are started.  In the event of a failure, all 
        of the successful services will be stopped (without chained behavior)
        and I will errback with the first unsuccessful service's failure.
        """
        def startServiceDeferred(res, service):
            return service.startService() or defer.succeed(None)
        d = defer.succeed(None)
        for svc in self.services.values():
            d.addCallbacks(startServiceDeferred, callbackArgs=(svc,),
                errback=self._rollbackStartedServices, errbackArgs=(svc,))
        return d.addCallback(self._finishStartService)
    def _emergencyStopService(self, failure, service):
        v = self.services.values()
        runningServices = v[v.index(service):]
        runningServices.reverse()
        for svc in runningServices:
            svc.stopService()
        self._finishStopService()
        return failure
    def _finishStopService(self, res):
        return ApplicationService.stopService(self) or defer.succeed(None)
    def stopService(self):
        """
        Stop all of my Services.
        I return a Deferred that will callback (with no useful result)
        when all services are stopped.  In the event of a failure, the 
        running services will be stopped (without chained behavior) and 
        I will errback with the first unsuccessful service's failure.
        """
        def stopServiceDeferred(res, service):
            return service.stopService() or defer.succeed(None)
        v = self.services.values()
        v.reverse()
        d = defer.succeed(None)
        for svc in v:
            d.addCallbacks(stopServiceDeferred, callbackArgs=(svc,),
                errback=self._emergencyStopService, errbackArgs=(svc,))
        return d.addCallback(self._finishStopService)
Ejemplo n.º 41
0
 def addFMTP(self, streamtype, mode="rtp-midi", profile_level=12, config=0):
     """specific for midirtp"""
     payload = 96
     fmtp = "%d streamtype=%d; mode=%s; profile-level-id=%d; config=%d" % (
         payload, streamtype, mode, profile_level, config)
     self._a.setdefault('fmtp', OrderedDict())[96] = fmtp
Ejemplo n.º 42
0
 def __init__(self):
     self.callbacks = OrderedDict()
Ejemplo n.º 43
0
 def test_tsize_ignored_when_less_than_zero(self):
     self.s = MockSession()
     opts = self.proto.processOptions(OrderedDict({'tsize':'-1'}))
     self.proto.applyOptions(self.s, opts)
     self.assertTrue(self.s.tsize is None)
     self.assertEqual(opts, OrderedDict({}))