source: main/waeup.ikoba/branches/uli-fake-gw-provider/src/waeup/ikoba/interfaces.py @ 12642

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

We need allow longer ids.

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