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

Last change on this file since 6347 was 6338, checked in by uli, 14 years ago

Add component to store object related history (shouldnt this be part of logging?) as metadata.

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