Ejemplo n.º 1
0
class Name(ContactObject):
	"""A name, which may be an alias for an official legal name

	I'm not sure about the internationalization issues
	here, given that "family names" in certain countries are
	mutable depending on individual gender and the like.

	No attempt is made to automatically support display names
	which are reverse order (for instance Chinese).

	Note: multiple names can be defined for an individual
	so you would record a nickname as a separate "given" name,
	rather than encoding it as part of the person's primary name.
	"""
	given = common.StringProperty(
		"given", """Given name(s), personal name(s) or only name, for instance "Cher", "Peter" or "Michael Colin".""",
		defaultValue = "",
	)
	family = common.StringProperty(
		"family", """Family name, clan name, or group name(s). Note that is value may be unspecified.""",
		defaultValue = "",
	)
	display = common.StringProperty(
		"display", """Display name, should be defined if this name should be displayed in the manner other than the application's default display mechanism (for instance "Family, Personal"). Note that is value may be unspecified.""",
		defaultValue = "",
	)
	formOfAddress = common.StringProperty(
		"formOfAddress", """Form of address (title), for example "Dr.", "His Eminence", "Her Majesty", "Ms.". Note that is value may be unspecified, applications may use it if present during default display calculation.""",
		defaultValue = "",
	)
	preferred = common.BooleanProperty(
		"preferred", """Indicate that this name/nickname is the preferred form of address for the individual""",
		defaultValue = 0,
	)
Ejemplo n.º 2
0
class TestData(propertied.Propertied):
    str1 = common.StringProperty("str1",
                                 """Test string property""",
                                 boundaries=(
                                     boundary.Range(minimum="", maximum="z"),
                                     boundary.Length(maximum=10),
                                 ))
    str2 = common.StringProperty("str2",
                                 """Test string property""",
                                 boundaries=(
                                     boundary.Range(minimum="a", maximum="z"),
                                     boundary.Length(maximum=10),
                                 ))
Ejemplo n.º 3
0
Archivo: menu.py Proyecto: daasara/riba
class CollectDigits(Interaction):
    """Collects some number of digits (e.g. an extension) from user"""
    soundFile = common.StringLocaleProperty(
        "soundFile",
        """File (name) for the pre-recorded blurb""",
    )
    textPrompt = common.StringProperty(
        "textPrompt",
        """Textual prompt describing the option""",
    )
    readBack = common.BooleanProperty(
        "readBack",
        """Whether to read the entered value back to the user""",
        defaultValue=False,
    )
    minDigits = common.IntegerProperty(
        "minDigits",
        """Minimum number of digits to collect (only restricted if specified)""",
    )
    maxDigits = common.IntegerProperty(
        "maxDigits",
        """Maximum number of digits to collect (only restricted if specified)""",
    )
    runnerClass = CollectDigitsRunner
    tellInvalid = common.IntegerProperty(
        "tellInvalid",
        """Whether to tell the user that their selection is unrecognised""",
        defaultValue=True,
    )
Ejemplo n.º 4
0
class DeliveryAddress( CommunicationsObject):
	"""A physical delivery address (mailing address)
	
	From the vCard spec:
		Post Office Address (first field)
		Extended Address (second field),
		Street (third field),
		Locality (fourth field),
		Region (fifth field),
		Postal Code (six field),
		Country (seventh field)
	"""
	address = common.StringProperty(
		"address", """The post-office address e.g. "Widgets Inc." or "Great Guy".""",
		defaultValue = "",
	)
	extendedAddress =  common.StringProperty(
		"extendedAddress", "The extended address e.g. Purchasing Department",
		defaultValue = "",
	)
	street = common.StringProperty(
		"street", "The street address e.g. 1426 Someroad Place.",
		defaultValue = "",
	)
	unit = common.StringProperty(
		"unit", "The unit/apartment address e.g.  #32b or Apt. 32 or Suite 32b",
		defaultValue = "",
	)
	locality = common.StringProperty(
		"locality", "The town, post-office district or city e.g. Toronto",
		defaultValue = "",
	)
	region = common.StringProperty(
		"region", "The state, province, district, or territory e.g. Ontario",
		defaultValue = "",
	)
	postalCode = common.StringProperty(
		"postalCode", "The post-office designation (zip-code, postal-code) e.g. M5P 3K8 or 90210",
		defaultValue = "",
	)
	country = common.StringProperty(
		"country", "The country e.g. Canada or United States of America",
		defaultValue = "",
	)
	
	domestic = common.BooleanProperty(
		"domestic", "Whether this address is domestic or international",
		defaultValue = 0,
	)
	postal = common.BooleanProperty(
		"postal", "Whether this address is served by the post office",
		defaultValue = 1,
	)
	parcel = common.BooleanProperty(
		"parcel", "Whether this address accepts parcel deliveries",
		defaultValue = 1,
	)
Ejemplo n.º 5
0
class PhoneNumber( CommunicationsObject ):
	"""A phone number, includes satellite and videophones"""
	number = common.StringProperty(
		"number", "The telephone number",
		defaultValue = "",
	)
	messaging = common.BooleanProperty(
		"messaging", "Whether this connection has messaging (voicemail) support",
		defaultValue = 0,
	)
Ejemplo n.º 6
0
class CommunicationsObject( ContactObject ):
	"""Base type for communication-oriented contact object properties
	"""
	type = common.StringProperty(
		"type", """Indicates the role of this particular communications address, for example "home", "work", "mobile".""",
		defaultValue = ""
	)
	preferred = common.BooleanProperty(
		"preferred", """Indicate that this name/nickname is the preferred address of its type for the individual""",
		defaultValue = 0,
	)
Ejemplo n.º 7
0
class Tag(propertied.Propertied):
    """Represents a particular tag within a document"""
    name = common.StringProperty(
        "name",
        "The name of the tag",
        defaultValue="",
    )
    attributes = common.DictionaryProperty(
        "attributes",
        """The in-tag attributes of the tag""",
        defaultFunction=lambda x, y: {},
    )
    content = common.ListProperty(
        "content",
        """The content (children) of the tag""",
        setDefaultOnGet=1,
        defaultFunction=lambda x, y: [],
    )

    def __cmp__(self, other):
        """Compare this tag to another"""
        if not isinstance(other, Tag):
            return -1
        if other.name != self.name:
            return cmp(self.name, other.name)
        if other.attributes != self.attributes:
            return cmp(self.attributes, other.attributes)
        if other.content != self.content:
            return cmp(self.content, other.content)
        return 0

    def __repr__(self):
        """Create a decent representation of this tag"""
        fragments = []
        name = self.name.decode().encode('utf-8')
        fragments.append("<" + name)
        for key, value in self.attributes.items():
            fragments.append("""%s=%r""" % (key, value))
        fragments = [" ".join(fragments)]
        if self.content:
            fragments.append(">")
            for item in self.content:
                if isinstance(item, str):
                    fragments.append(item)
                else:
                    fragments.append(repr(item))
            fragments.append("</%s>" % (name))
        else:
            fragments.append("/>")
        return "".join(fragments)
Ejemplo n.º 8
0
Archivo: menu.py Proyecto: daasara/riba
class CollectAudio(Interaction):
    """Collects audio file from the user"""
    prompt = common.ListProperty(
        "prompt",
        """(Set of) prompts to run, can be Prompt instances or filenames
		
		Used by the PromptRunner to produce prompt selections
		""",
    )
    textPrompt = common.StringProperty(
        "textPrompt",
        """Textual prompt describing the option""",
    )
    temporaryFile = common.StringLocaleProperty(
        "temporaryFile",
        """Temporary file into which to record the audio before moving to filename""",
    )
    filename = common.StringLocaleProperty(
        "filename",
        """Final filename into which to record the file...""",
    )
    deleteOnFail = common.BooleanProperty(
        "deleteOnFail",
        """Whether to delete failed attempts to record a file""",
        defaultValue=True)
    escapeDigits = common.StringLocaleProperty(
        "escapeDigits",
        """Set of digits which escape from recording the file""",
        defaultValue='#*0123456789',
    )
    timeout = common.FloatProperty(
        "timeout",
        """Duration to wait for recording (maximum record time)""",
        defaultValue=60,
    )
    silence = common.FloatProperty(
        "silence",
        """Duration to wait for recording (maximum record time)""",
        defaultValue=5,
    )
    beep = common.BooleanProperty(
        "beep",
        """Whether to play a "beep" sound at beginning of recording""",
        defaultValue=True,
    )
    runnerClass = CollectAudioRunner
Ejemplo n.º 9
0
Archivo: menu.py Proyecto: daasara/riba
class Menu(Interaction):
    """IVR-based menu, returns options selected by the user and keypresses
	
	The Menu holds a collection of Option instances along with a prompt 
	which presents those options to the user.  The menu will attempt to 
	collect the user's selected option up to maxRepetitions times, playing 
	the prompt each time.
	
	If tellInvalid is true, will allow any character being pressed to stop
	the playback, and will tell the user if the pressed character is not 
	recognised.  Otherwise will simply ignore a pressed character which isn't
	part of an Option object's 'option' property.
	
	The menu will chain into callable Options, so that SubMenu and ExitOn can
	be used to produce effects such as multi-level menus with options to 
	return to the parent menu level.
	
	Returns [(option,char(pressedKey))...] for each level of menu explored
	"""
    INVALID_OPTION_FILE = 'pm-invalid-option'
    prompt = common.ListProperty(
        "prompt",
        """(Set of) prompts to run, can be Prompt instances or filenames
		
		Used by the PromptRunner to produce prompt selections
		""",
    )
    textPrompt = common.StringProperty(
        "textPrompt",
        """Textual prompt describing the option""",
    )
    options = common.ListProperty(
        "options",
        """Set of options the user may select""",
    )
    tellInvalid = common.IntegerProperty(
        "tellInvalid",
        """Whether to tell the user that their selection is unrecognised""",
        defaultValue=True,
    )
    runnerClass = MenuRunner
Ejemplo n.º 10
0
class Callable(propertied.Propertied):
    """Modelling of a callable Python object"""
    name = common.StringProperty(
        'name',
        """The callable object's-name (may be different from underlying object)""",
    )
    implementation = basic.BasicProperty(
        "implementation",
        """The underlying implementation (callable Python object)""",
    )
    arguments = common.ListProperty(
        'arguments',
        """Argument-list for the callable object""",
        baseType=listof_Arguments,
    )
    shortHelp = common.StringProperty(
        'shortHelp',
        """Short help-string suitable for tooltips/status-bars""",
    )
    longHelp = common.StringProperty(
        'longHelp',
        """Longer help-string suitable for context-sensitive help""",
    )
    coerce = common.BooleanProperty(
        "coerce",
        """Whether to coerce arguments if possible""",
        defaultValue=0,
    )

    def __init__(self,
                 implementation,
                 name=__NULL__,
                 arguments=__NULL__,
                 shortHelp=__NULL__,
                 longHelp=__NULL__,
                 **named):
        """Initialize the Callable object

		implementation -- a callable python object
		name -- if provided, will override the given name
		arguments -- if provided, will override calculated arguments
		shortHelp -- short help-string, first line of __doc__ if not given
		longHelp -- long help-string, entire __doc__ string if not given
		"""
        if name is __NULL__:
            name = self._name(implementation)
        if arguments is __NULL__:
            arguments = self._arguments(implementation)
        if shortHelp is __NULL__:
            shortHelp = self._shortHelp(implementation)
        if longHelp is __NULL__:
            longHelp = self._longHelp(implementation)
        super(Callable, self).__init__(implementation=implementation,
                                       name=name,
                                       arguments=arguments,
                                       **named)

    def __str__(self):
        """Return a friendly string representation"""
        return """%s( %s )""" % (self.__class__.__name__, self.implementation)

    def __call__(self, *arguments, **named):
        """Do the actual calling of the callable object"""
        set = {}
        for argument, value in zip(arguments, self.arguments):
            set[argument.name] = (argument, value)
        # XXX potentially there are missing positional arguments!
        if named:
            nameSet = dict([(arg.name, arg) for arg in self.arguments])
            for key, value in named.items():
                if set.has_key(key):
                    raise ValueError(
                        """Redefinition of argument order for argument %s""" %
                        (set.get(key)))
                else:
                    # note that argument may be None
                    set[key] = nameSet.get(key), value
        for key, (argument, value) in set.items():
            if self.coerce and argument and argument.baseType and hasattr(
                    argument.baseType, "coerce"):
                value = argument.baseType.coerce(argument)
            set[key] = value
        # XXX Should keep arguments in order to allow for *args set :(
        return self.implementation(**set)

    def getArgument(self, name):
        """Retieve an argument by name"""
        for argument in self.arguments:
            if argument.name == name:
                return argument
        raise KeyError("""%r object doesn't have a %s argument""" %
                       (self, name))

    def _name(self, value):
        """Try to find a decent name for a callable object"""
        name = "<unknown>"
        for attribute in [
                '__name__', 'name', 'func_name', 'co_name', '__file__',
                "friendlyName"
        ]:
            if hasattr(value, attribute):
                v = getattr(value, attribute)
                if isinstance(v, (str, unicode)):
                    name = v
        if '.' in name:
            return name.split('.')[-1]
        return name

    def _shortHelp(self, value):
        """Try to find the short-docstring for an object"""
        if hasattr(value, '__doc__') and value.__doc__:
            return value.__doc__.split('\n')[0]
        else:
            return ""

    def _longHelp(self, value):
        """Try to find the short-docstring for an object"""
        if hasattr(value, '__doc__') and value.__doc__:
            return value.__doc__
        else:
            return ""

    def _useCall(self, value):
        """Can we use __call__ to call this object?

		returns true if we should be able to use it
		"""
        return (
            # must have __call__
            hasattr(value, '__call__') and (
                # call should be a function or method...
                hasattr(value.__call__, 'im_func')
                or hasattr(value.__call__, 'im_code')))

    def _arguments(self, value):
        """Get a list of arguments for a callable object"""
        if self._useCall(value):
            value = value.__call__
        if hasattr(value, 'im_func'):
            # receiver is a method. Drop the first argument, usually 'self'.
            func = value.im_func
            arguments = inspect.getargspec(func)
            if value.im_self is not None:
                # a bound instance or class method
                arguments = inspect.getargspec(func)
                del arguments[0][0]
            else:
                # an un-bound method
                pass
        elif hasattr(value, 'func_code') or hasattr(value, 'im_code'):
            # receiver is a function.
            func = value
            arguments = inspect.getargspec(func)
        else:
            raise ValueError('unknown reciever type %s %s' %
                             (receiver, type(receiver)))
        names, vararg, varnamed, defaults = arguments
        defaults = defaults or ()
        result = [Argument(name=name) for name in names]
        for name, default in zip(names[-len(defaults):], defaults):
            for item in result:
                if item.name == name:
                    item.default = default
        return result

    def check(cls, value):
        """Strict check to see if value is an instance of cls"""
        return isinstance(value, cls)

    check = classmethod(check)

    def coerce(cls, value):
        """Coerce value to a Callable-object"""
        if cls.check(value):
            return value
        if callable(value):
            return cls(implementation=value, )
        else:
            raise TypeError("Don't know how to convert %r to a %s object" % (
                value,
                cls.__name__,
            ))

    coerce = classmethod(coerce)

    def __eq__(self, other):
        """Determine whether other is our equivalent

		returns true if other is of the same class, with
		the same primary attributes
		"""
        if self.__class__ is not other.__class__:
            return 0
        NULL = []
        for nm in ['name', 'implementation', 'arguments']:
            if hasattr(self, nm) and not hasattr(other, nm):
                return 0
            elif not hasattr(self, nm) and hasattr(other, nm):
                return 0
            elif hasattr(self, nm):
                if getattr(self, nm) != getattr(other, nm):
                    return 0
        return 1
Ejemplo n.º 11
0
class EmailAddress( CommunicationsObject ):
	"""An e-mail address, generally an Internet e-mail address"""
	address = common.StringProperty(
		"address", "The email address",
		defaultValue = "",
	)
Ejemplo n.º 12
0
class OrganisationMember( ContactObject ):
	title = common.StringProperty(
		"title", "The title of this position",
		defaultValue = "",
	)
Ejemplo n.º 13
0
class User(propertied.Propertied):
    email = common.StringProperty(
        "email",
        """The user's email address""",
        boundaries=(checkEmailAddress, ),
    )