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

Last change on this file since 12071 was 12060, checked in by uli, 10 years ago

Merge changes from uli-payments back into trunk.

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