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

Last change on this file since 13804 was 13803, checked in by Henrik Bettermann, 9 years ago

Enable temporary suspension of officer accounts. Plugins must be
updated after restart.

See r12926.

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