source: main/waeup.ikoba/trunk/src/waeup/ikoba/utils/utils.py @ 12305

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

Make EXPORTER_NAMES tuples customizable. We have many new subobject classes in custom packages.

  • Property svn:keywords set to Id
File size: 8.7 KB
RevLine 
[7358]1## $Id: utils.py 12297 2014-12-22 16:42: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##
[11949]18"""General helper utilities for Ikoba.
[7358]19"""
20import grok
[11815]21import psutil
[7365]22import string
[8181]23import pytz
[9866]24from copy import deepcopy
[8181]25from random import SystemRandom as r
[7734]26from zope.i18n import translate
[11949]27from waeup.ikoba.interfaces import IIkobaUtils
28from waeup.ikoba.interfaces import MessageFactory as _
29from waeup.ikoba.smtp import send_mail as send_mail_internally
30from waeup.ikoba.utils.helpers import get_sorted_preferred
[7358]31
[11814]32
33def send_mail(from_name, from_addr,
34              rcpt_name, rcpt_addr,
35              subject, body, config):
[11949]36    """Wrapper for the real SMTP functionality in :mod:`waeup.ikoba.smtp`.
[7382]37
[7471]38    Merely here to stay compatible with lots of calls to this place.
[7400]39    """
[7471]40    mail_id = send_mail_internally(
41        from_name, from_addr, rcpt_name, rcpt_addr,
42        subject, body, config)
[7399]43    return True
44
[11814]45
[7874]46#: A list of phone prefixes (order num, country, prefix).
47#: Items with same order num will be sorted alphabetically.
48#: The lower the order num, the higher the precedence.
49INT_PHONE_PREFIXES = [
50    (99, _('Germany'), '49'),
[11814]51    (1, _('Nigeria'), '234'),
[7874]52    (99, _('U.S.'), '1'),
53    ]
54
[11814]55
56def sorted_phone_prefixes(data=INT_PHONE_PREFIXES, request=None):
[7874]57    """Sorted tuples of phone prefixes.
58
59    Ordered as shown above and formatted for use in select boxes.
60
61    If request is given, we'll try to translate all country names in
62    order to sort alphabetically correctly.
63
64    XXX: This is a function (and not a constant) as different
65    languages might give different orders. This is not tested yet.
66
67    XXX: If we really want to use alphabetic ordering here, we might
68    think about caching results of translations.
69    """
70    if request is not None:
71        data = [
72            (x, translate(y, context=request), z)
73            for x, y, z in data]
74    return tuple([
[11814]75        ('%s (+%s)' % (x[1], x[2]), '+%s' % x[2])
[7874]76        for x in sorted(data)
77        ])
78
[11814]79
[11949]80class IkobaUtils(grok.GlobalUtility):
[7678]81    """A collection of parameters and methods subject to customization.
[7829]82
[7358]83    """
[11949]84    grok.implements(IIkobaUtils)
[7678]85    # This the only place where we define the portal language
86    # which is used for the translation of system messages
87    # (e.g. object histories).
[7744]88    PORTAL_LANGUAGE = 'en'
[7358]89
[7701]90    PREFERRED_LANGUAGES_DICT = {
[11814]91        'en': (1, u'English'),
92        'fr': (2, u'Français'),
93        'de': (3, u'Deutsch'),
94        'ha': (4, u'Hausa'),
95        'yo': (5, u'Yoruba'),
96        'ig': (6, u'Igbo'),
[7701]97        }
98
[7874]99    #: A function to return
100    @classmethod
101    def sorted_phone_prefixes(cls, data=INT_PHONE_PREFIXES, request=None):
102        return sorted_phone_prefixes(data, request)
[7871]103
[12098]104    CON_CATS_DICT = {
[12092]105        'sample': 'Sample Category',
[12078]106        'license': 'License',
[12098]107        'no': 'no contract',
[12078]108        }
109
[7841]110    EXAM_SUBJECTS_DICT = {
[7843]111        'math': 'Mathematics',
112        'computer_science': 'Computer Science',
[7841]113        }
[7836]114
[7917]115    #: Exam grades. The tuple is sorted as it should be displayed in
116    #: select boxes.
117    EXAM_GRADES = (
118        ('A', 'Best'),
119        ('B', 'Better'),
120        ('C', 'Good'),
121        )
[7836]122
[9405]123    PAYMENT_CATEGORIES = {
[11981]124        'license': 'License Fee',
[9405]125        }
126
[11800]127    #: Set positive number for allowed max, negative for required min
128    #: avail.
129    #:
130    #: Use integer for bytes value, float for percent
131    #: value. `cpu-load`, of course, accepts float values only.
132    #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory,
[12060]133    #: `cpu-load` = CPU load in percent.
[11800]134    SYSTEM_MAX_LOAD = {
135        'swap-mem': None,
136        'virt-mem': None,
137        'cpu-load': 100.0,
138        }
139
[12297]140    EXPORTER_NAMES = (
[12283]141        'pdfdocuments',
142        'htmldocuments',
143        'users',
[12297]144        'products',
145        'customers',
146        'customersampledocuments',
147        'samplecontracts')
[12283]148
149    BATCH_PROCESSOR_NAMES = (
150        'customerprocessor',
151        'customersampledocumentprocessor',
152        'samplecontractprocessor',
153        'productprocessor',
154        'pdfdocumentprocessor',
155        'htmldocumentprocessor',
156        'userprocessor')
157
[11814]158    def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr,
159                        from_username, usertype, portal, body, subject):
[7358]160        """Send an email with data provided by forms.
161        """
162        config = grok.getSite()['configuration']
[7734]163        text = _(u"""Fullname: ${a}
164User Id: ${b}
165User Type: ${c}
166Portal: ${d}
[7358]167
[7734]168${e}
169""")
[11814]170        text = _(text, mapping={
171            'a': from_name,
172            'b': from_username,
173            'c': usertype,
174            'd': portal,
175            'e': body})
[11949]176        body = translate(text, 'waeup.ikoba',
[7734]177            target_language=self.PORTAL_LANGUAGE)
[8436]178        if not (from_addr and rcpt_addr):
179            return False
[7400]180        return send_mail(
[11814]181            from_name, from_addr, rcpt_name, rcpt_addr,
182            subject, body, config)
[7359]183
[8181]184    @property
185    def tzinfo(self):
186        # For Nigeria: pytz.timezone('Africa/Lagos')
[9543]187        # For Germany: pytz.timezone('Europe/Berlin')
[8181]188        return pytz.utc
189
[11814]190    def fullname(self, firstname, lastname, middlename=None):
[7477]191        """Full name constructor.
192        """
[7359]193        # We do not necessarily have the middlename attribute
194        if middlename:
[8603]195            name = '%s %s %s' % (firstname, middlename, lastname)
[7359]196        else:
[8603]197            name = '%s %s' % (firstname, lastname)
[11814]198        return string.capwords(
199            name.replace('-', ' - ')).replace(' - ', '-')
[7365]200
201    def genPassword(self, length=8, chars=string.letters + string.digits):
[7477]202        """Generate a random password.
203        """
[7365]204        return ''.join([r().choice(chars) for i in range(length)])
205
[8853]206    def sendCredentials(self, user, password=None, url_info=None, msg=None):
[7399]207        """Send credentials as email.
208
[11947]209        Input is the customer for which credentials are sent and the
[7399]210        password.
211
212        Returns True or False to indicate successful operation.
[7365]213        """
[11949]214        subject = 'Your Ikoba credentials'
[7734]215        text = _(u"""Dear ${a},
[7365]216
[7734]217${b}
[12192]218Registration and Application Portal of
[7734]219${c}.
[7365]220
[7734]221Your user name: ${d}
222Your password: ${e}
[8853]223${f}
[7365]224
225Please remember your user name and keep
226your password secret!
227
[7382]228Please also note that passwords are case-sensitive.
229
[7365]230Regards
[7734]231""")
[7399]232        config = grok.getSite()['configuration']
233        from_name = config.name_admin
[7402]234        from_addr = config.email_admin
[7407]235        rcpt_name = user.title
236        rcpt_addr = user.email
[11814]237        text = _(text, mapping={
238            'a': rcpt_name,
239            'b': msg,
240            'c': config.name,
241            'd': user.name,
242            'e': password,
243            'f': url_info})
[7734]244
[11949]245        body = translate(text, 'waeup.ikoba',
[7734]246            target_language=self.PORTAL_LANGUAGE)
[7399]247        return send_mail(
[11814]248            from_name, from_addr, rcpt_name, rcpt_addr,
249            subject, body, config)
[9987]250
251    def getPaymentItem(self, payment):
252        """Return payment item.
253
254        This method can be used to customize the display_item property method.
255        """
256        return payment.p_item
[11815]257
258    def expensive_actions_allowed(self, type=None, request=None):
259        """Tell, whether expensive actions are currently allowed.
260
261        Check system load/health (or other external circumstances) and
262        locally set values to see, whether expensive actions should be
263        allowed (`True`) or better avoided (`False`).
264
265        Use this to allow or forbid exports, report generations, or
266        similar actions.
267        """
268        max_values = self.SYSTEM_MAX_LOAD
[11816]269        for (key, func) in (
270            ('swap-mem', psutil.swap_memory),
[11818]271            ('virt-mem', psutil.virtual_memory),
[11816]272            ):
273            max_val = max_values.get(key, None)
274            if max_val is None:
275                continue
276            mem_val = func()
[11815]277            if isinstance(max_val, float):
[11816]278                # percents
[11821]279                if max_val < 0.0:
280                    max_val = 100.0 + max_val
[11816]281                if mem_val.percent > max_val:
[11815]282                    return False
283            else:
[11816]284                # number of bytes
[11821]285                if max_val < 0:
286                    max_val = mem_val.total + max_val
[11816]287                if mem_val.used > max_val:
[11815]288                    return False
289        return True
Note: See TracBrowser for help on using the repository browser.