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

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

Turn ResultEntry? (school grades) components into ProductOptionEntry? components.

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