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

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

Fix docstrings as slanged by Sphinx.

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