source: main/waeup.sirp/trunk/src/waeup/sirp/interfaces.py @ 6906

Last change on this file since 6906 was 6905, checked in by Henrik Bettermann, 14 years ago

Remove unused interfaces from main module.

  • Property svn:eol-style set to native
File size: 13.7 KB
RevLine 
[3521]1##
2## interfaces.py
[6361]3import os
[6353]4from hurry.workflow.interfaces import IWorkflow, IWorkflowInfo
[4789]5from zc.sourcefactory.basic import BasicSourceFactory
[6147]6from zope import schema
[4789]7from zope.component import getUtility
[4882]8from zope.component.interfaces import IObjectEvent
[5955]9from zope.interface import Interface, Attribute, implements
[4789]10from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
[3521]11
[6361]12default_frontpage = u'' + open(os.path.join(
13        os.path.dirname(__file__), 'frontpage.rst'), 'rb').read()
14
[4858]15class FatalCSVError(Exception):
16    """Some row could not be processed.
17    """
18    pass
19
[6226]20class DuplicationError(Exception):
21    """An exception that can be raised when duplicates are found.
22
23    When raising :exc:`DuplicationError` you can, beside the usual
24    message, specify a list of objects which are duplicates. These
25    values can be used by catching code to print something helpful or
26    similar.
27    """
28    def __init__(self, msg, entries=[]):
29        self.msg = msg
30        self.entries = entries
31
32    def __str__(self):
33        return '%r' % self.msg
34
[4789]35def SimpleWAeUPVocabulary(*terms):
36    """A well-buildt vocabulary provides terms with a value, token and
37       title for each term
38    """
39    return SimpleVocabulary([
40            SimpleTerm(value, value, title) for title, value in terms])
41
[6143]42class RoleSource(BasicSourceFactory):
[6508]43    """A source for global roles.
44    """
[6143]45    def getValues(self):
[6157]46        # late import: in interfaces we should not import local modules
47        from waeup.sirp.permissions import getWAeUPRoleNames
48        return getWAeUPRoleNames()
49
50    def getTitle(self, value):
51        # late import: in interfaces we should not import local modules
[6143]52        from waeup.sirp.permissions import getRoles
[6157]53        roles = dict(getRoles())
54        if value in roles.keys():
55            title = roles[value].title
[6569]56            if '.' in title:
57                title = title.split('.', 2)[1]
[6157]58        return title
[6143]59
[4789]60class IWAeUPObject(Interface):
61    """A WAeUP object.
[5663]62
63    This is merely a marker interface.
[4789]64    """
65
66class IUniversity(IWAeUPObject):
[3521]67    """Representation of a university.
68    """
69    name = schema.TextLine(
70        title = u'Name of University',
[6361]71        default = u'Sample University',
[3521]72        required = True,
73        )
[5955]74
[6065]75    title = schema.TextLine(
76        title = u'Title of frontpage',
[6361]77        default = u'Welcome to the Student Information and Registration ' +
78                  u'Portal of Sample University',
[6065]79        required = False,
80        )
81
[5407]82    skin = schema.Choice(
83        title = u'Skin',
84        default = u'waeuptheme-gray1.css',
[5968]85        vocabulary = 'waeup.sirp.browser.theming.ThemesVocabulary',
[5407]86        required = True,
87        )
[6136]88
[6065]89    frontpage = schema.Text(
[6132]90        title = u'Content in reST format',
[6065]91        required = False,
[6361]92        default = default_frontpage,
[6136]93        )
[4789]94
[6136]95
[4789]96class IWAeUPContainer(IWAeUPObject):
97    """A container for WAeUP objects.
98    """
99
100class IWAeUPContained(IWAeUPObject):
101    """An item contained in an IWAeUPContainer.
102    """
[6136]103
[4789]104class IWAeUPExporter(Interface):
105    """An exporter for objects.
106    """
107    def export(obj, filepath=None):
108        """Export by pickling.
109
110        Returns a file-like object containing a representation of `obj`.
111
112        This is done using `pickle`. If `filepath` is ``None``, a
113        `cStringIO` object is returned, that contains the saved data.
114        """
115
116class IWAeUPXMLExporter(Interface):
117    """An XML exporter for objects.
118    """
119    def export(obj, filepath=None):
120        """Export as XML.
121
122        Returns an XML representation of `obj`.
123
124        If `filepath` is ``None``, a StringIO` object is returned,
125        that contains the transformed data.
126        """
127
128class IWAeUPXMLImporter(Interface):
129    """An XML import for objects.
130    """
131    def doImport(filepath):
132        """Create Python object from XML.
133
134        Returns a Python object.
135        """
136
[4858]137class IBatchProcessor(Interface):
138    """A batch processor that handles mass-operations.
139    """
140    name = schema.TextLine(
141        title = u'Importer name'
142        )
143
144    mode = schema.Choice(
145        title = u'Import mode',
146        values = ['create', 'update', 'remove']
147        )
[6136]148
[5476]149    def doImport(path, headerfields, mode='create', user='Unknown',
150                 logger=None):
[4858]151        """Read data from ``path`` and update connected object.
[5476]152
153        `headerfields` is a list of headerfields as read from the file
154        to import.
155
156        `mode` gives the import mode to use (``'create'``,
157        ``'update'``, or ``'remove'``.
158
159        `user` is a string describing the user performing the
160        import. Normally fetched from current principal.
161
162        `logger` is the logger to use during import.
[4858]163        """
164
[4789]165class IUserAccount(IWAeUPObject):
166    """A user account.
167    """
168    name = schema.TextLine(
169        title = u'User ID',
[6512]170        description = u'Login name of user',
[4789]171        required = True,)
172    title = schema.TextLine(
[6512]173        title = u'Name',
174        description = u'Real name of user',
[4789]175        required = False,)
176    description = schema.TextLine(
[6512]177        title = u'Description',
[4789]178        required = False,)
179    password = schema.Password(
180        title = u'Password',
181        required = True,)
182    roles = schema.List(
[6508]183        title = u'Global roles',
[4789]184        value_type = schema.Choice(source=RoleSource()))
[6136]185
186
[4789]187class IUserContainer(IWAeUPObject):
188    """A container for users (principals).
189
190    These users are used for authentication purposes.
191    """
192
193    def addUser(name, password, title=None, description=None):
194        """Add a user.
195        """
196
197    def delUser(name):
198        """Delete a user if it exists.
199        """
200
[6141]201class ILocalRolesAssignable(Interface):
202    """The local roles assignable to an object.
203    """
204    def __call__():
205        """Returns a list of dicts.
206
207        Each dict contains a ``name`` referring to the role assignable
208        for the specified object and a `title` to describe the range
209        of users to which this role can be assigned.
210        """
211
[4789]212class IDataCenter(IWAeUPObject):
213    """A data center.
214
215    TODO : declare methods, at least those needed by pages.
216    """
217    pass
218
219class IDataCenterFile(Interface):
220    """A data center file.
221    """
[4858]222
223    name = schema.TextLine(
224        title = u'Filename')
225
226    size = schema.TextLine(
227        title = u'Human readable file size')
228
229    uploaddate = schema.TextLine(
230        title = u'Human readable upload datetime')
231
232    lines = schema.Int(
233        title = u'Number of lines in file')
[6136]234
[4789]235    def getDate():
236        """Get creation timestamp from file in human readable form.
237        """
238
239    def getSize():
240        """Get human readable size of file.
241        """
[4858]242
243    def getLinesNumber():
244        """Get number of lines of file.
245        """
[4882]246
247class IDataCenterStorageMovedEvent(IObjectEvent):
248    """Emitted, when the storage of a datacenter changes.
249    """
[5007]250
[6136]251class IObjectUpgradeEvent(IObjectEvent):
252    """Can be fired, when an object shall be upgraded.
253    """
254
[6180]255class ILocalRoleSetEvent(IObjectEvent):
256    """A local role was granted/revoked for a principal on an object.
257    """
258    role_id = Attribute(
259        "The role id that was set.")
260    principal_id = Attribute(
261        "The principal id for which the role was granted/revoked.")
262    granted = Attribute(
263        "Boolean. If false, then the role was revoked.")
264
[5007]265class IQueryResultItem(Interface):
266    """An item in a search result.
267    """
268    url = schema.TextLine(
269        title = u'URL that links to the found item')
270    title = schema.TextLine(
271        title = u'Title displayed in search results.')
272    description = schema.Text(
273        title = u'Longer description of the item found.')
[6136]274
[5013]275class IWAeUPSIRPPluggable(Interface):
276    """A component that might be plugged into a WAeUP SIRP app.
[5658]277
278    Components implementing this interface are referred to as
279    'plugins'. They are normally called when a new
280    :class:`waeup.sirp.app.University` instance is created.
281
282    Plugins can setup and update parts of the central site without the
283    site object (normally a :class:`waeup.sirp.app.University` object)
284    needing to know about that parts. The site simply collects all
285    available plugins, calls them and the plugins care for their
[5676]286    respective subarea like the applicants area or the datacenter
[5658]287    area.
288
289    Currently we have no mechanism to define an order of plugins. A
290    plugin should therefore make no assumptions about the state of the
291    site or other plugins being run before and instead do appropriate
292    checks if necessary.
293
294    Updates can be triggered for instance by the respective form in
295    the site configuration. You normally do updates when the
296    underlying software changed.
[5013]297    """
[5069]298    def setup(site, name, logger):
299        """Create an instance of the plugin.
[5013]300
[5658]301        The method is meant to be called by the central app (site)
302        when it is created.
303
304        `site`:
305           The site that requests a setup.
306
307        `name`:
308           The name under which the plugin was registered (utility name).
309
310        `logger`:
311           A standard Python logger for the plugins use.
[5069]312        """
313
314    def update(site, name, logger):
315        """Method to update an already existing plugin.
316
317        This might be called by a site when something serious
[5658]318        changes. It is a poor-man replacement for Zope generations
319        (but probably more comprehensive and better understandable).
320
321        `site`:
322           The site that requests an update.
323
324        `name`:
325           The name under which the plugin was registered (utility name).
326
327        `logger`:
328           A standard Python logger for the plugins use.
[5069]329        """
[5898]330
[5899]331class IAuthPluginUtility(Interface):
[5898]332    """A component that cares for authentication setup at site creation.
333
334    Utilities providing this interface are looked up when a Pluggable
335    Authentication Utility (PAU) for any
336    :class:`waeup.sirp.app.University` instance is created and put
337    into ZODB.
338
339    The setup-code then calls the `register` method of the utility and
340    expects a modified (or unmodified) version of the PAU back.
341
342    This allows to define any authentication setup modifications by
343    submodules or third-party modules/packages.
344    """
345
346    def register(pau):
347        """Register any plugins wanted to be in the PAU.
348        """
349
350    def unregister(pau):
351        """Unregister any plugins not wanted to be in the PAU.
352        """
[6273]353
354class IObjectConverter(Interface):
355    """Object converters are available as simple adapters, adapting
356       interfaces (not regular instances).
357
358    """
359
[6277]360    def fromStringDict(self, data_dict, context, form_fields=None):
361        """Convert values in `data_dict`.
[6273]362
[6277]363        Converts data in `data_dict` into real values based on
364        `context` and `form_fields`.
[6273]365
[6277]366        `data_dict` is a mapping (dict) from field names to values
367        represented as strings.
[6273]368
[6277]369        The fields (keys) to convert can be given in optional
370        `form_fields`. If given, form_fields should be an instance of
371        :class:`zope.formlib.form.Fields`. Suitable instances are for
372        example created by :class:`grok.AutoFields`.
[6273]373
[6277]374        If no `form_fields` are given, a default is computed from the
375        associated interface.
[6273]376
[6277]377        The `context` can be an existing object (implementing the
378        associated interface) or a factory name. If it is a string, we
379        try to create an object using
380        :func:`zope.component.createObject`.
381
382        Returns a tuple ``(<FIELD_ERRORS>, <INVARIANT_ERRORS>,
383        <DATA_DICT>)`` where
384
385        ``<FIELD_ERRORS>``
386           is a list of tuples ``(<FIELD_NAME>, <ERROR>)`` for each
387           error that happened when validating the input data in
388           `data_dict`
389
390        ``<INVARIANT_ERRORS>``
391           is a list of invariant errors concerning several fields
392
393        ``<DATA_DICT>``
394           is a dict with the values from input dict converted.
395
396        If errors happen, i.e. the error lists are not empty, always
397        an empty ``<DATA_DICT>`` is returned.
398
399        If ``<DATA_DICT>` is non-empty, there were no errors.
[6273]400        """
[6293]401
[6338]402class IObjectHistory(Interface):
403
404    messages = schema.List(
405        title = u'List of messages stored',
406        required = True,
407        )
408
409    def addMessage(message):
410        """Add a message.
411        """
[6353]412
413class IWAeUPWorkflowInfo(IWorkflowInfo):
414    """A :class:`hurry.workflow.workflow.WorkflowInfo` with additional
415       methods for convenience.
416    """
417    def getManualTransitions():
418        """Get allowed manual transitions.
419
420        Get a sorted list of tuples containing the `transition_id` and
421        `title` of each allowed transition.
422        """
[6481]423
424class ISiteLoggers(Interface):
425
426    loggers = Attribute("A list or generator of registered WAeUPLoggers")
427
428    def register(name, filename=None, site=None, **options):
429        """Register a logger `name` which logs to `filename`.
430
431        If `filename` is not given, logfile will be `name` with
432        ``.log`` as filename extension.
433        """
434
435    def unregister(name):
436        """Unregister a once registered logger.
437        """
438
439class ILogger(Interface):
440    """A logger cares for setup, update and restarting of a Python logger.
441    """
442
443    logger = Attribute("""A :class:`logging.Logger` instance""")
444
445
446    def __init__(name, filename=None, site=None, **options):
447        """Create a WAeUP logger instance.
448        """
449
450    def setup():
451        """Create a Python :class:`logging.Logger` instance.
452
453        The created logger is based on the params given by constructor.
454        """
455
456    def update(**options):
457        """Update the logger.
458
459        Updates the logger respecting modified `options` and changed
460        paths.
461        """
[6754]462
463class ILoggerCollector(Interface):
464
465    def getLoggers(site):
466        """Return all loggers registered for `site`.
467        """
468
469    def registerLogger(site, logging_component):
470        """Register a logging component residing in `site`.
471        """
472
473    def unregisterLogger(site, logging_component):
474        """Unregister a logger.
475        """
Note: See TracBrowser for help on using the repository browser.