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

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

We need documents which can be accessed or downloaded from product pages. These documents can provide general information of registration processes or pdf forms to be filled offline and later uploaded by customers.

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