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

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

Move ProductOption? interfaces to productoptions to avoid nasty circular imports.

Use ISO_4217_CURRENCIES.

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