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

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

We need to deepcopy dicts. A simple copy is useless.

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