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

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

Edit some comments.

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