source: main/waeup.ikoba/trunk/src/waeup/ikoba/interfaces.py @ 12521

Last change on this file since 12521 was 12443, checked in by Henrik Bettermann, 10 years ago

Increase allowed id length.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 37.7 KB
Line 
1## $Id: interfaces.py 12443 2015-01-11 16:54:48Z henrik $
2##
3## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
4## This program is free software; you can redistribute it and/or modify
5## it under the terms of the GNU General Public License as published by
6## the Free Software Foundation; either version 2 of the License, or
7## (at your option) any later version.
8##
9## This program is distributed in the hope that it will be useful,
10## but WITHOUT ANY WARRANTY; without even the implied warranty of
11## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12## GNU General Public License for more details.
13##
14## You should have received a copy of the GNU General Public License
15## along with this program; if not, write to the Free Software
16## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17##
18import os
19import re
20import codecs
21import zc.async.interfaces
22import zope.i18nmessageid
23from datetime import datetime
24from hurry.file.interfaces import IFileRetrieval
25from hurry.workflow.interfaces import IWorkflowInfo
26from zc.sourcefactory.basic import BasicSourceFactory
27from zope import schema
28from zope.pluggableauth.interfaces import IPrincipalInfo
29from zope.security.interfaces import IGroupClosureAwarePrincipal as IPrincipal
30from zope.component import getUtility
31from zope.component.interfaces import IObjectEvent
32from zope.configuration.fields import Path
33from zope.container.interfaces import INameChooser, IContainer
34from zope.interface import Interface, Attribute
35from zope.schema.interfaces import IObject
36from zope.schema.vocabulary import SimpleVocabulary, SimpleTerm
37from waeup.ikoba.schema import PhoneNumber
38from waeup.ikoba.sourcefactory import SmartBasicContextualSourceFactory
39
40_ = MessageFactory = zope.i18nmessageid.MessageFactory('waeup.ikoba')
41
42DELETION_MARKER = 'XXX'
43IGNORE_MARKER = '<IGNORE>'
44WAEUP_KEY = 'waeup.ikoba'
45VIRT_JOBS_CONTAINER_NAME = 'jobs'
46
47# States for various workflows
48
49CREATED = 'created'
50
51STARTED = 'started'
52REQUESTED = 'requested'
53APPROVED = 'approved'
54
55SUBMITTED = 'submitted'
56VERIFIED = 'verified'
57REJECTED = 'rejected'
58EXPIRED = 'expired'
59PUBLISHED = 'published'
60
61
62#: A dict giving job status as tuple (<STRING>, <TRANSLATED_STRING>),
63#: the latter for UI purposes.
64JOB_STATUS_MAP = {
65    zc.async.interfaces.NEW: ('new', _('new')),
66    zc.async.interfaces.COMPLETED: ('completed', _('completed')),
67    zc.async.interfaces.PENDING: ('pending', _('pending')),
68    zc.async.interfaces.ACTIVE: ('active', _('active')),
69    zc.async.interfaces.ASSIGNED: ('assigned', _('assigned')),
70    zc.async.interfaces.CALLBACKS: ('callbacks', _('callbacks')),
71    }
72
73#default_rest_frontpage = u'' + codecs.open(os.path.join(
74#        os.path.dirname(__file__), 'frontpage.rst'),
75#        encoding='utf-8', mode='rb').read()
76
77default_html_frontpage = u'' + codecs.open(os.path.join(
78        os.path.dirname(__file__), 'frontpage.html'),
79        encoding='utf-8', mode='rb').read()
80
81def SimpleIkobaVocabulary(*terms):
82    """A well-buildt vocabulary provides terms with a value, token and
83       title for each term
84    """
85    return SimpleVocabulary([
86            SimpleTerm(value, value, title) for title, value in terms])
87
88class ContextualDictSourceFactoryBase(SmartBasicContextualSourceFactory):
89    """A base for contextual sources based on IkobaUtils dicts.
90
91    To create a real source, you have to set the `DICT_NAME` attribute
92    which should be the name of a dictionary in IkobaUtils.
93    """
94    def getValues(self, context):
95        utils = getUtility(IIkobaUtils)
96        sorted_items = sorted(getattr(utils, self.DICT_NAME).items(),
97                              key=lambda item: item[1])
98        return [item[0] for item in sorted_items]
99
100    def getToken(self, context, value):
101        return str(value)
102
103    def getTitle(self, context, value):
104        utils = getUtility(IIkobaUtils)
105        return getattr(utils, self.DICT_NAME)[value]
106
107# Define a validation method for email addresses
108class NotAnEmailAddress(schema.ValidationError):
109    __doc__ = u"Invalid email address"
110
111#: Regular expression to check email-address formats. As these can
112#: become rather complex (nearly everything is allowed by RFCs), we only
113#: forbid whitespaces, commas and dots following onto each other.
114check_email = re.compile(
115    r"^[^@\s,]+@[^@\.\s,]+(\.[^@\.\s,]+)*$").match
116
117def validate_email(value):
118    if not check_email(value):
119        raise NotAnEmailAddress(value)
120    return True
121
122# Define a validation method for ids
123class NotIdValue(schema.ValidationError):
124    __doc__ = u"Invalid id"
125
126#: Regular expressions to check id formats.
127check_id = re.compile(r"^[a-zA-Z0-9_-]{2,9}$").match
128check_uuid = re.compile( r"^[a-zA-Z0-9]{32}$").match
129
130def validate_id(value):
131    if not check_id(value):
132        raise NotIdValue(value)
133    return True
134
135def validate_uuid(value):
136    # We are using also short ids in tests
137    if not check_uuid(value) and not check_id(value):
138        raise NotIdValue(value)
139    return True
140
141# Define a validation method for international phone numbers
142class InvalidPhoneNumber(schema.ValidationError):
143    __doc__ = u"Invalid phone number"
144
145# represent format +NNN-NNNN-NNNN
146RE_INT_PHONE = re.compile(r"^\+?\d+\-\d+\-[\d\-]+$")
147
148def validate_phone(value):
149    if not RE_INT_PHONE.match(value):
150        raise InvalidPhoneNumber(value)
151    return True
152
153class FatalCSVError(Exception):
154    """Some row could not be processed.
155    """
156    pass
157
158class DuplicationError(Exception):
159    """An exception that can be raised when duplicates are found.
160
161    When raising :exc:`DuplicationError` you can, beside the usual
162    message, specify a list of objects which are duplicates. These
163    values can be used by catching code to print something helpful or
164    similar.
165    """
166    def __init__(self, msg, entries=[]):
167        self.msg = msg
168        self.entries = entries
169
170    def __str__(self):
171        return '%r' % self.msg
172
173class RoleSource(BasicSourceFactory):
174    """A source for site roles.
175    """
176    def getValues(self):
177        # late import: in interfaces we should not import local modules
178        from waeup.ikoba.permissions import get_waeup_role_names
179        return get_waeup_role_names()
180
181    def getTitle(self, value):
182        # late import: in interfaces we should not import local modules
183        from waeup.ikoba.permissions import get_all_roles
184        roles = dict(get_all_roles())
185        if value in roles.keys():
186            title = roles[value].title
187            if '.' in title:
188                title = title.split('.', 2)[1]
189        return title
190
191class CaptchaSource(BasicSourceFactory):
192    """A source for captchas.
193    """
194    def getValues(self):
195        captchas = ['No captcha', 'Testing captcha', 'ReCaptcha']
196        try:
197            # we have to 'try' because IConfiguration can only handle
198            # interfaces from w.k.interface.
199            from waeup.ikoba.browser.interfaces import ICaptchaManager
200        except:
201            return captchas
202        return sorted(getUtility(ICaptchaManager).getAvailCaptchas().keys())
203
204    def getTitle(self, value):
205        return value
206
207class CurrencySource(BasicSourceFactory):
208    """A source for currencies.
209    """
210    def getValues(self):
211        currencies = getUtility(IIkobaUtils).CURRENCIES
212        return currencies.keys()
213
214    def getToken(self, value):
215        return value
216
217    def getTitle(self, value):
218        currencies = getUtility(IIkobaUtils).CURRENCIES
219        return currencies[value][1]
220
221class IIkobaUtils(Interface):
222    """A collection of methods which are subject to customization.
223    """
224
225    PORTAL_LANGUAGE = Attribute("Dict of global language setting")
226    PREFERRED_LANGUAGES_DICT = Attribute("Dict of preferred languages")
227    SYSTEM_MAX_LOAD = Attribute("Dict of maximum system loads.")
228
229    def sendContactForm(
230          from_name,from_addr,rcpt_name,rcpt_addr,
231          from_username,usertype,portal,body,subject):
232        """Send an email with data provided by forms.
233        """
234
235    def fullname(firstname,lastname,middlename):
236        """Full name constructor.
237        """
238
239    def sendCredentials(user, password, url_info, msg):
240        """Send credentials as email.
241
242        Input is the customer for which credentials are sent and the
243        password.
244
245        Returns True or False to indicate successful operation.
246        """
247
248    def genPassword(length, chars):
249        """Generate a random password.
250        """
251
252class IIkobaObject(Interface):
253    """A Ikoba object.
254
255    This is merely a marker interface.
256    """
257
258class ICompany(IIkobaObject):
259    """Representation of an company.
260    """
261
262
263class IIkobaContainer(IIkobaObject):
264    """A container for Ikoba objects.
265    """
266
267class IIkobaContained(IIkobaObject):
268    """An item contained in an IIkobaContainer.
269    """
270
271class ICSVExporter(Interface):
272    """A CSV file exporter for objects.
273    """
274    fields = Attribute("""List of fieldnames in resulting CSV""")
275
276    title = schema.TextLine(
277        title = u'Title',
278        description = u'Description to be displayed in selections.',
279        )
280    def mangle_value(value, name, obj):
281        """Mangle `value` extracted from `obj` or suobjects thereof.
282
283        This is called by export before actually writing to the result
284        file.
285        """
286
287    def get_filtered(site, **kw):
288        """Get datasets in `site` to be exported.
289
290        The set of data is specified by keywords, which might be
291        different for any implementaion of exporter.
292
293        Returns an iterable.
294        """
295
296    def export(iterable, filepath=None):
297        """Export iterables as rows in a CSV file.
298
299        If `filepath` is not given, a string with the data should be
300        returned.
301
302        What kind of iterables are acceptable depends on the specific
303        exporter implementation.
304        """
305
306    def export_all(site, filepath=None):
307        """Export all items in `site` as CSV file.
308
309        if `filepath` is not given, a string with the data should be
310        returned.
311        """
312
313    def export_filtered(site, filepath=None, **kw):
314        """Export those items in `site` specified by `args` and `kw`.
315
316        If `filepath` is not given, a string with the data should be
317        returned.
318
319        Which special keywords are supported is up to the respective
320        exporter.
321        """
322
323class IIkobaExporter(Interface):
324    """An exporter for objects.
325    """
326    def export(obj, filepath=None):
327        """Export by pickling.
328
329        Returns a file-like object containing a representation of `obj`.
330
331        This is done using `pickle`. If `filepath` is ``None``, a
332        `cStringIO` object is returned, that contains the saved data.
333        """
334
335class IIkobaXMLExporter(Interface):
336    """An XML exporter for objects.
337    """
338    def export(obj, filepath=None):
339        """Export as XML.
340
341        Returns an XML representation of `obj`.
342
343        If `filepath` is ``None``, a StringIO` object is returned,
344        that contains the transformed data.
345        """
346
347class IIkobaXMLImporter(Interface):
348    """An XML import for objects.
349    """
350    def doImport(filepath):
351        """Create Python object from XML.
352
353        Returns a Python object.
354        """
355
356class IBatchProcessor(Interface):
357    """A batch processor that handles mass-operations.
358    """
359    name = schema.TextLine(
360        title = _(u'Processor name')
361        )
362
363    def doImport(path, headerfields, mode='create', user='Unknown',
364                 logger=None, ignore_empty=True):
365        """Read data from ``path`` and update connected object.
366
367        `headerfields` is a list of headerfields as read from the file
368        to import.
369
370        `mode` gives the import mode to use (``'create'``,
371        ``'update'``, or ``'remove'``.
372
373        `user` is a string describing the user performing the
374        import. Normally fetched from current principal.
375
376        `logger` is the logger to use during import.
377
378        `ignore_emtpy` in update mode ignores empty fields if true.
379        """
380
381class IContactForm(IIkobaObject):
382    """A contact form.
383    """
384
385    email_from = schema.ASCIILine(
386        title = _(u'Email Address:'),
387        default = None,
388        required = True,
389        constraint=validate_email,
390        )
391
392    email_to = schema.ASCIILine(
393        title = _(u'Email to:'),
394        default = None,
395        required = True,
396        constraint=validate_email,
397        )
398
399    subject = schema.TextLine(
400        title = _(u'Subject:'),
401        required = True,)
402
403    fullname = schema.TextLine(
404        title = _(u'Full Name:'),
405        required = True,)
406
407    body = schema.Text(
408        title = _(u'Text:'),
409        required = True,)
410
411class IIkobaPrincipalInfo(IPrincipalInfo):
412    """Infos about principals that are users of Ikoba Ikoba.
413    """
414    email = Attribute("The email address of a user")
415    phone = Attribute("The phone number of a user")
416    public_name = Attribute("The public name of a user")
417
418
419class IIkobaPrincipal(IPrincipal):
420    """A principle for Ikoba Ikoba.
421
422    This interface extends zope.security.interfaces.IPrincipal and
423    requires also an `id` and other attributes defined there.
424    """
425
426    email = schema.TextLine(
427        title = _(u'Email Address'),
428        description = u'',
429        required=False,)
430
431    phone = PhoneNumber(
432        title = _(u'Phone'),
433        description = u'',
434        required=False,)
435
436    public_name = schema.TextLine(
437        title = _(u'Public Name'),
438        required = False,)
439
440class IFailedLoginInfo(IIkobaObject):
441    """Info about failed logins.
442
443    Timestamps are supposed to be stored as floats using time.time()
444    or similar.
445    """
446    num = schema.Int(
447        title = _(u'Number of failed logins'),
448        description = _(u'Number of failed logins'),
449        required = True,
450        default = 0,
451        )
452
453    last = schema.Float(
454        title = _(u'Timestamp'),
455        description = _(u'Timestamp of last failed login or `None`'),
456        required = False,
457        default = None,
458        )
459
460    def as_tuple():
461        """Get login info as tuple ``<NUM>, <TIMESTAMP>``.
462        """
463
464    def set_values(num=0, last=None):
465        """Set number of failed logins and timestamp of last one.
466        """
467
468    def increase():
469        """Increase the current number of failed logins and set timestamp.
470        """
471
472    def reset():
473        """Set failed login counters back to zero.
474        """
475
476
477class IUserAccount(IIkobaObject):
478    """A user account.
479    """
480
481    failed_logins = Attribute("""FailedLoginInfo for this account""")
482
483    name = schema.TextLine(
484        title = _(u'User Id'),
485        description = u'Login name of user',
486        required = True,)
487
488    title = schema.TextLine(
489        title = _(u'Full Name'),
490        required = True,)
491
492    public_name = schema.TextLine(
493        title = _(u'Public Name'),
494        description = u"Substitute for officer's real name "
495                       "in object histories.",
496        required = False,)
497
498    description = schema.Text(
499        title = _(u'Description/Notice'),
500        required = False,)
501
502    email = schema.ASCIILine(
503        title = _(u'Email Address'),
504        default = None,
505        required = True,
506        constraint=validate_email,
507        )
508
509    phone = PhoneNumber(
510        title = _(u'Phone'),
511        default = None,
512        required = False,
513        )
514
515    roles = schema.List(
516        title = _(u'Portal Roles'),
517        value_type = schema.Choice(source=RoleSource()),
518        required = False,
519        )
520
521
522
523class IPasswordValidator(Interface):
524    """A password validator utility.
525    """
526
527    def validate_password(password, password_repeat):
528        """Validates a password by comparing it with
529        control password and checking some other requirements.
530        """
531
532
533class IUsersContainer(IIkobaObject):
534    """A container for users (principals).
535
536    These users are used for authentication purposes.
537    """
538
539    def addUser(name, password, title=None, description=None):
540        """Add a user.
541        """
542
543    def delUser(name):
544        """Delete a user if it exists.
545        """
546
547class ILocalRolesAssignable(Interface):
548    """The local roles assignable to an object.
549    """
550    def __call__():
551        """Returns a list of dicts.
552
553        Each dict contains a ``name`` referring to the role assignable
554        for the specified object and a `title` to describe the range
555        of users to which this role can be assigned.
556        """
557
558class IConfigurationContainer(IIkobaObject):
559    """A container for session configuration objects.
560    """
561
562    name = schema.TextLine(
563        title = _(u'Name of Company'),
564        default = _(u'Sample Company'),
565        required = True,
566        )
567
568    acronym = schema.TextLine(
569        title = _(u'Abbreviated Title of Company'),
570        default = u'WAeUP.Ikoba',
571        required = True,
572        )
573
574    frontpage = schema.Text(
575        title = _(u'Content in HTML format'),
576        required = False,
577        default = default_html_frontpage,
578        )
579
580    frontpage_dict = schema.Dict(
581        title = u'Content as language dictionary with values in html format',
582        required = False,
583        default = {},
584        )
585
586    name_admin = schema.TextLine(
587        title = _(u'Name of Administrator'),
588        default = u'Administrator',
589        required = True,
590        )
591
592    email_admin = schema.ASCIILine(
593        title = _(u'Email Address of Administrator'),
594        default = 'contact@waeup.org',
595        required = True,
596        constraint=validate_email,
597        )
598
599    email_subject = schema.TextLine(
600        title = _(u'Subject of Email to Administrator'),
601        default = _(u'Ikoba Contact'),
602        required = True,
603        )
604
605    smtp_mailer = schema.Choice(
606        title = _(u'SMTP mailer to use when sending mail'),
607        vocabulary = 'Mail Delivery Names',
608        default = 'No email service',
609        required = True,
610        )
611
612    captcha = schema.Choice(
613        title = _(u'Captcha used for public registration pages'),
614        source = CaptchaSource(),
615        default = u'No captcha',
616        required = True,
617        )
618
619
620class IDataCenter(IIkobaObject):
621    """A data center.
622
623    A data center manages files (uploads, downloads, etc.).
624
625    Beside providing the bare paths needed to keep files, it also
626    provides some helpers to put results of batch processing into
627    well-defined final locations (with well-defined filenames).
628
629    The main use-case is managing of site-related files, i.e. files
630    for import, export etc.
631
632    DataCenters are _not_ meant as storages for object-specific files
633    like passport photographs and similar.
634
635    It is up to the datacenter implementation how to organize data
636    (paths) inside its storage path.
637    """
638    storage = schema.Bytes(
639        title = u'Path to directory where everything is kept.'
640        )
641
642    deleted_path = schema.Bytes(
643        title = u'Path were data about deleted objects should be stored.'
644        )
645
646    def getPendingFiles(sort='name'):
647        """Get a list of files stored in `storage` sorted by basename.
648        """
649
650    def getFinishedFiles():
651        """Get a list of files stored in `finished` subfolder of `storage`.
652        """
653
654    def setStoragePath(path, move=False, overwrite=False):
655        """Set the path where to store files.
656
657        If `move` is True, move over files from the current location
658        to the new one.
659
660        If `overwrite` is also True, overwrite any already existing
661        files of same name in target location.
662
663        Triggers a DataCenterStorageMovedEvent.
664        """
665
666    def distProcessedFiles(successful, source_path, finished_file,
667                           pending_file, mode='create', move_orig=True):
668        """Distribute processed files over final locations.
669        """
670
671
672class IDataCenterFile(Interface):
673    """A data center file.
674    """
675
676    name = schema.TextLine(
677        title = u'Filename')
678
679    size = schema.TextLine(
680        title = u'Human readable file size')
681
682    uploaddate = schema.TextLine(
683        title = u'Human readable upload datetime')
684
685    lines = schema.Int(
686        title = u'Number of lines in file')
687
688    def getDate():
689        """Get creation timestamp from file in human readable form.
690        """
691
692    def getSize():
693        """Get human readable size of file.
694        """
695
696    def getLinesNumber():
697        """Get number of lines of file.
698        """
699
700class IDataCenterStorageMovedEvent(IObjectEvent):
701    """Emitted, when the storage of a datacenter changes.
702    """
703
704class IObjectUpgradeEvent(IObjectEvent):
705    """Can be fired, when an object shall be upgraded.
706    """
707
708class ILocalRoleSetEvent(IObjectEvent):
709    """A local role was granted/revoked for a principal on an object.
710    """
711    role_id = Attribute(
712        "The role id that was set.")
713    principal_id = Attribute(
714        "The principal id for which the role was granted/revoked.")
715    granted = Attribute(
716        "Boolean. If false, then the role was revoked.")
717
718class IQueryResultItem(Interface):
719    """An item in a search result.
720    """
721    url = schema.TextLine(
722        title = u'URL that links to the found item')
723    title = schema.TextLine(
724        title = u'Title displayed in search results.')
725    description = schema.Text(
726        title = u'Longer description of the item found.')
727
728class IIkobaPluggable(Interface):
729    """A component that might be plugged into a Ikoba Ikoba app.
730
731    Components implementing this interface are referred to as
732    'plugins'. They are normally called when a new
733    :class:`waeup.ikoba.app.Company` instance is created.
734
735    Plugins can setup and update parts of the central site without the
736    site object (normally a :class:`waeup.ikoba.app.Company` object)
737    needing to know about that parts. The site simply collects all
738    available plugins, calls them and the plugins care for their
739    respective subarea like the cutomers area or the datacenter
740    area.
741
742    Currently we have no mechanism to define an order of plugins. A
743    plugin should therefore make no assumptions about the state of the
744    site or other plugins being run before and instead do appropriate
745    checks if necessary.
746
747    Updates can be triggered for instance by the respective form in
748    the site configuration. You normally do updates when the
749    underlying software changed.
750    """
751    def setup(site, name, logger):
752        """Create an instance of the plugin.
753
754        The method is meant to be called by the central app (site)
755        when it is created.
756
757        `site`:
758           The site that requests a setup.
759
760        `name`:
761           The name under which the plugin was registered (utility name).
762
763        `logger`:
764           A standard Python logger for the plugins use.
765        """
766
767    def update(site, name, logger):
768        """Method to update an already existing plugin.
769
770        This might be called by a site when something serious
771        changes. It is a poor-man replacement for Zope generations
772        (but probably more comprehensive and better understandable).
773
774        `site`:
775           The site that requests an update.
776
777        `name`:
778           The name under which the plugin was registered (utility name).
779
780        `logger`:
781           A standard Python logger for the plugins use.
782        """
783
784class IAuthPluginUtility(Interface):
785    """A component that cares for authentication setup at site creation.
786
787    Utilities providing this interface are looked up when a Pluggable
788    Authentication Utility (PAU) for any
789    :class:`waeup.ikoba.app.Company` instance is created and put
790    into ZODB.
791
792    The setup-code then calls the `register` method of the utility and
793    expects a modified (or unmodified) version of the PAU back.
794
795    This allows to define any authentication setup modifications by
796    submodules or third-party modules/packages.
797    """
798
799    def register(pau):
800        """Register any plugins wanted to be in the PAU.
801        """
802
803    def unregister(pau):
804        """Unregister any plugins not wanted to be in the PAU.
805        """
806
807class IObjectConverter(Interface):
808    """Object converters are available as simple adapters, adapting
809       interfaces (not regular instances).
810
811    """
812
813    def fromStringDict(self, data_dict, context, form_fields=None):
814        """Convert values in `data_dict`.
815
816        Converts data in `data_dict` into real values based on
817        `context` and `form_fields`.
818
819        `data_dict` is a mapping (dict) from field names to values
820        represented as strings.
821
822        The fields (keys) to convert can be given in optional
823        `form_fields`. If given, form_fields should be an instance of
824        :class:`zope.formlib.form.Fields`. Suitable instances are for
825        example created by :class:`grok.AutoFields`.
826
827        If no `form_fields` are given, a default is computed from the
828        associated interface.
829
830        The `context` can be an existing object (implementing the
831        associated interface) or a factory name. If it is a string, we
832        try to create an object using
833        :func:`zope.component.createObject`.
834
835        Returns a tuple ``(<FIELD_ERRORS>, <INVARIANT_ERRORS>,
836        <DATA_DICT>)`` where
837
838        ``<FIELD_ERRORS>``
839           is a list of tuples ``(<FIELD_NAME>, <ERROR>)`` for each
840           error that happened when validating the input data in
841           `data_dict`
842
843        ``<INVARIANT_ERRORS>``
844           is a list of invariant errors concerning several fields
845
846        ``<DATA_DICT>``
847           is a dict with the values from input dict converted.
848
849        If errors happen, i.e. the error lists are not empty, always
850        an empty ``<DATA_DICT>`` is returned.
851
852        If ``<DATA_DICT>` is non-empty, there were no errors.
853        """
854
855class IFieldConverter(Interface):
856    def request_data(name, value, schema_field, prefix='', mode='create'):
857        """Create a dict with key-value mapping as created by a request.
858
859        `name` and `value` are expected to be parsed from CSV or a
860        similar input and represent an attribute to be set to a
861        representation of value.
862
863        `mode` gives the mode of import.
864
865        :meth:`update_request_data` is then requested to turn this
866        name and value into vars as they would be sent by a regular
867        form submit. This means we do not create the real values to be
868        set but we only define the values that would be sent in a
869        browser request to request the creation of those values.
870
871        The returned dict should contain names and values of a faked
872        browser request for the given `schema_field`.
873
874        Field converters are normally registered as adapters to some
875        specific zope.schema field.
876        """
877
878class IObjectHistory(Interface):
879
880    messages = schema.List(
881        title = u'List of messages stored',
882        required = True,
883        )
884
885    def addMessage(message):
886        """Add a message.
887        """
888
889class IIkobaWorkflowInfo(IWorkflowInfo):
890    """A :class:`hurry.workflow.workflow.WorkflowInfo` with additional
891       methods for convenience.
892    """
893    def getManualTransitions():
894        """Get allowed manual transitions.
895
896        Get a sorted list of tuples containing the `transition_id` and
897        `title` of each allowed transition.
898        """
899
900class ISiteLoggers(Interface):
901
902    loggers = Attribute("A list or generator of registered IkobaLoggers")
903
904    def register(name, filename=None, site=None, **options):
905        """Register a logger `name` which logs to `filename`.
906
907        If `filename` is not given, logfile will be `name` with
908        ``.log`` as filename extension.
909        """
910
911    def unregister(name):
912        """Unregister a once registered logger.
913        """
914
915class ILogger(Interface):
916    """A logger cares for setup, update and restarting of a Python logger.
917    """
918
919    logger = Attribute("""A :class:`logging.Logger` instance""")
920
921
922    def __init__(name, filename=None, site=None, **options):
923        """Create a Ikoba logger instance.
924        """
925
926    def setup():
927        """Create a Python :class:`logging.Logger` instance.
928
929        The created logger is based on the params given by constructor.
930        """
931
932    def update(**options):
933        """Update the logger.
934
935        Updates the logger respecting modified `options` and changed
936        paths.
937        """
938
939class ILoggerCollector(Interface):
940
941    def getLoggers(site):
942        """Return all loggers registered for `site`.
943        """
944
945    def registerLogger(site, logging_component):
946        """Register a logging component residing in `site`.
947        """
948
949    def unregisterLogger(site, logging_component):
950        """Unregister a logger.
951        """
952
953#
954# External File Storage and relatives
955#
956class IFileStoreNameChooser(INameChooser):
957    """See zope.container.interfaces.INameChooser for base methods.
958    """
959    def checkName(name, attr=None):
960        """Check whether an object name is valid.
961
962        Raises a user error if the name is not valid.
963        """
964
965    def chooseName(name, attr=None):
966        """Choose a unique valid file id for the object.
967
968        The given name may be taken into account when choosing the
969        name (file id).
970
971        chooseName is expected to always choose a valid file id (that
972        would pass the checkName test) and never raise an error.
973
974        If `attr` is not ``None`` it might been taken into account as
975        well when generating the file id. Usual behaviour is to
976        interpret `attr` as a hint for what type of file for a given
977        context should be stored if there are several types
978        possible. For instance for a certain customer some file could
979        be the connected passport photograph or some certificate scan
980        or whatever. Each of them has to be stored in a different
981        location so setting `attr` to a sensible value should give
982        different file ids returned.
983        """
984
985class IExtFileStore(IFileRetrieval):
986    """A file storage that stores files in filesystem (not as blobs).
987    """
988    root = schema.TextLine(
989        title = u'Root path of file store.',
990        )
991
992    def getFile(file_id):
993        """Get raw file data stored under file with `file_id`.
994
995        Returns a file descriptor open for reading or ``None`` if the
996        file cannot be found.
997        """
998
999    def getFileByContext(context, attr=None):
1000        """Get raw file data stored for the given context.
1001
1002        Returns a file descriptor open for reading or ``None`` if no
1003        such file can be found.
1004
1005        Both, `context` and `attr` might be used to find (`context`)
1006        and feed (`attr`) an appropriate file name chooser.
1007
1008        This is a convenience method.
1009        """
1010
1011    def deleteFile(file_id):
1012        """Delete file stored under `file_id`.
1013
1014        Remove file from filestore so, that it is not available
1015        anymore on next call to getFile for the same file_id.
1016
1017        Should not complain if no such file exists.
1018        """
1019
1020    def deleteFileByContext(context, attr=None):
1021        """Delete file for given `context` and `attr`.
1022
1023        Both, `context` and `attr` might be used to find (`context`)
1024        and feed (`attr`) an appropriate file name chooser.
1025
1026        This is a convenience method.
1027        """
1028
1029    def createFile(filename, f):
1030        """Create file given by f with filename `filename`
1031
1032        Returns a hurry.file.File-based object.
1033        """
1034
1035class IFileStoreHandler(Interface):
1036    """Filestore handlers handle specific files for file stores.
1037
1038    If a file to store/get provides a specific filename, a file store
1039    looks up special handlers for that type of file.
1040
1041    """
1042    def pathFromFileID(store, root, filename):
1043        """Turn file id into path to store.
1044
1045        Returned path should be absolute.
1046        """
1047
1048    def createFile(store, root, filename, file_id, file):
1049        """Return some hurry.file based on `store` and `file_id`.
1050
1051        Some kind of callback method called by file stores to create
1052        file objects from file_id.
1053
1054        Returns a tuple ``(raw_file, path, file_like_obj)`` where the
1055        ``file_like_obj`` should be a HurryFile, a IkobaImageFile or
1056        similar. ``raw_file`` is the (maybe changed) input file and
1057        ``path`` the relative internal path to store the file at.
1058
1059        Please make sure the ``raw_file`` is opened for reading and
1060        the file descriptor set at position 0 when returned.
1061
1062        This method also gets the raw input file object that is about
1063        to be stored and is expected to raise any exceptions if some
1064        kind of validation or similar fails.
1065        """
1066
1067class IPDF(Interface):
1068    """A PDF representation of some context.
1069    """
1070
1071    def __call__(view=None, note=None):
1072        """Create a bytestream representing a PDF from context.
1073
1074        If `view` is passed in additional infos might be rendered into
1075        the document.
1076
1077        `note` is optional HTML rendered at bottom of the created
1078        PDF. Please consider the limited reportlab support for HTML,
1079        but using font-tags and friends you certainly can get the
1080        desired look.
1081        """
1082
1083class IMailService(Interface):
1084    """A mail service.
1085    """
1086
1087    def __call__():
1088        """Get the default mail delivery.
1089        """
1090
1091
1092class IDataCenterConfig(Interface):
1093    path = Path(
1094        title = u'Path',
1095        description = u"Directory where the datacenter should store "
1096                      u"files by default (adjustable in web UI).",
1097        required = True,
1098        )
1099
1100
1101class IPayPalConfig(Interface):
1102    path = Path(
1103        title = u'Path',
1104        description = u"Path to config file for PayPal REST API.",
1105        required = True,
1106        )
1107
1108
1109#
1110# Asynchronous job handling and related
1111#
1112class IJobManager(IIkobaObject):
1113    """A manager for asynchronous running jobs (tasks).
1114    """
1115    def put(job, site=None):
1116        """Put a job into task queue.
1117
1118        If no `site` is given, queue job in context of current local
1119        site.
1120
1121        Returns a job_id to identify the put job. This job_id is
1122        needed for further references to the job.
1123        """
1124
1125    def jobs(site=None):
1126        """Get an iterable of jobs stored.
1127        """
1128
1129    def get(job_id, site=None):
1130        """Get the job with id `job_id`.
1131
1132        For the `site` parameter see :meth:`put`.
1133        """
1134
1135    def remove(job_id, site=None):
1136        """Remove job with `job_id` from stored jobs.
1137        """
1138
1139    def start_test_job(site=None):
1140        """Start a test job.
1141        """
1142
1143class IProgressable(Interface):
1144    """A component that can indicate its progress status.
1145    """
1146    percent = schema.Float(
1147        title = u'Percent of job done already.',
1148        )
1149
1150class IJobContainer(IContainer):
1151    """A job container contains IJob objects.
1152    """
1153
1154class IExportJob(zc.async.interfaces.IJob):
1155    def __init__(site, exporter_name):
1156        pass
1157
1158    finished = schema.Bool(
1159        title = u'`True` if the job finished.`',
1160        default = False,
1161        )
1162
1163    failed = schema.Bool(
1164        title = u"`True` iff the job finished and didn't provide a file.",
1165        default = None,
1166        )
1167
1168class IExportJobContainer(IIkobaObject):
1169    """A component that contains (maybe virtually) export jobs.
1170    """
1171    def start_export_job(exporter_name, user_id, *args, **kwargs):
1172        """Start asynchronous export job.
1173
1174        `exporter_name` is the name of an exporter utility to be used.
1175
1176        `user_id` is the ID of the user that triggers the export.
1177
1178        `args` positional arguments passed to the export job created.
1179
1180        `kwargs` keyword arguments passed to the export job.
1181
1182        The job_id is stored along with exporter name and user id in a
1183        persistent list.
1184
1185        Returns the job ID of the job started.
1186        """
1187
1188    def get_running_export_jobs(user_id=None):
1189        """Get export jobs for user with `user_id` as list of tuples.
1190
1191        Each tuples holds ``<job_id>, <exporter_name>, <user_id>`` in
1192        that order. The ``<exporter_name>`` is the utility name of the
1193        used exporter.
1194
1195        If `user_id` is ``None``, all running jobs are returned.
1196        """
1197
1198    def get_export_jobs_status(user_id=None):
1199        """Get running/completed export jobs for `user_id` as list of tuples.
1200
1201        Each tuple holds ``<raw status>, <status translated>,
1202        <exporter title>`` in that order, where ``<status
1203        translated>`` and ``<exporter title>`` are translated strings
1204        representing the status of the job and the human readable
1205        title of the exporter used.
1206        """
1207
1208    def delete_export_entry(entry):
1209        """Delete the export denoted by `entry`.
1210
1211        Removes `entry` from the local `running_exports` list and also
1212        removes the regarding job via the local job manager.
1213
1214        `entry` is a tuple ``(<job id>, <exporter name>, <user id>)``
1215        as created by :meth:`start_export_job` or returned by
1216        :meth:`get_running_export_jobs`.
1217        """
1218
1219    def entry_from_job_id(job_id):
1220        """Get entry tuple for `job_id`.
1221
1222        Returns ``None`` if no such entry can be found.
1223        """
1224
1225class IExportContainerFinder(Interface):
1226    """A finder for the central export container.
1227    """
1228    def __call__():
1229        """Return the currently used global or site-wide IExportContainer.
1230        """
1231
1232class IFilteredQuery(IIkobaObject):
1233    """A query for objects.
1234    """
1235
1236    defaults = schema.Dict(
1237        title = u'Default Parameters',
1238        required = True,
1239        )
1240
1241    def __init__(**parameters):
1242        """Instantiate a filtered query by passing in parameters.
1243        """
1244
1245    def query():
1246        """Get an iterable of objects denoted by the set parameters.
1247
1248        The search should be applied to objects inside current
1249        site. It's the caller's duty to set the correct site before.
1250
1251        Result can be any iterable like a catalog result set, a list,
1252        or similar.
1253        """
1254
1255class IFilteredCatalogQuery(IFilteredQuery):
1256    """A catalog-based query for objects.
1257    """
1258
1259    cat_name = schema.TextLine(
1260        title = u'Registered name of the catalog to search.',
1261        required = True,
1262        )
1263
1264    def query_catalog(catalog):
1265        """Query catalog with the parameters passed to constructor.
1266        """
1267
1268
1269class IIDSource(Interface):
1270    """A source for unique IDs, according to RFC 4122.
1271    """
1272    def get_uuid():
1273        """Get a random unique ID.
1274
1275        Get a 'Universially Unique IDentifier'. The result string
1276        might contain any printable characters.
1277        """
1278
1279    def get_hex_uuid():
1280        """Get a random unique ID as a string representing a hex number.
1281        """
Note: See TracBrowser for help on using the repository browser.