1 | ## $Id: utils.py 12378 2015-01-03 13:41:03Z 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 | """ |
---|
20 | import grok |
---|
21 | import psutil |
---|
22 | import string |
---|
23 | import pytz |
---|
24 | from random import SystemRandom as r |
---|
25 | from zope.i18n import translate |
---|
26 | from waeup.ikoba.interfaces import IIkobaUtils |
---|
27 | from waeup.ikoba.interfaces import MessageFactory as _ |
---|
28 | from waeup.ikoba.smtp import send_mail as send_mail_internally |
---|
29 | from waeup.ikoba.utils.helpers import get_sorted_preferred |
---|
30 | from waeup.ikoba.payments.currencies import ISO_4217_CURRENCIES |
---|
31 | |
---|
32 | |
---|
33 | def send_mail(from_name, from_addr, |
---|
34 | rcpt_name, rcpt_addr, |
---|
35 | subject, body, config): |
---|
36 | """Wrapper for the real SMTP functionality in :mod:`waeup.ikoba.smtp`. |
---|
37 | |
---|
38 | Merely here to stay compatible with lots of calls to this place. |
---|
39 | """ |
---|
40 | mail_id = send_mail_internally( |
---|
41 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
42 | subject, body, config) |
---|
43 | return True |
---|
44 | |
---|
45 | |
---|
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. |
---|
49 | INT_PHONE_PREFIXES = [ |
---|
50 | (99, _('Germany'), '49'), |
---|
51 | (1, _('Nigeria'), '234'), |
---|
52 | (99, _('U.S.'), '1'), |
---|
53 | ] |
---|
54 | |
---|
55 | |
---|
56 | def sorted_phone_prefixes(data=INT_PHONE_PREFIXES, request=None): |
---|
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([ |
---|
75 | ('%s (+%s)' % (x[1], x[2]), '+%s' % x[2]) |
---|
76 | for x in sorted(data) |
---|
77 | ]) |
---|
78 | |
---|
79 | |
---|
80 | class IkobaUtils(grok.GlobalUtility): |
---|
81 | """A collection of parameters and methods subject to customization. |
---|
82 | |
---|
83 | """ |
---|
84 | grok.implements(IIkobaUtils) |
---|
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). |
---|
88 | PORTAL_LANGUAGE = 'en' |
---|
89 | |
---|
90 | PREFERRED_LANGUAGES_DICT = { |
---|
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'), |
---|
97 | } |
---|
98 | |
---|
99 | # CURRENCIES must be equal to or an excerpt of ISO_4217_CURRENCIES |
---|
100 | CURRENCIES = ISO_4217_CURRENCIES |
---|
101 | |
---|
102 | #: A function to return |
---|
103 | @classmethod |
---|
104 | def sorted_phone_prefixes(cls, data=INT_PHONE_PREFIXES, request=None): |
---|
105 | return sorted_phone_prefixes(data, request) |
---|
106 | |
---|
107 | CON_CATS_DICT = { |
---|
108 | 'sample': 'Sample Category', |
---|
109 | 'license': 'License', |
---|
110 | 'no': 'no contract', |
---|
111 | } |
---|
112 | |
---|
113 | PAYMENT_CATEGORIES = { |
---|
114 | 'license': 'License Fee', |
---|
115 | } |
---|
116 | |
---|
117 | #: Set positive number for allowed max, negative for required min |
---|
118 | #: avail. |
---|
119 | #: |
---|
120 | #: Use integer for bytes value, float for percent |
---|
121 | #: value. `cpu-load`, of course, accepts float values only. |
---|
122 | #: `swap-mem` = Swap Memory, `virt-mem` = Virtual Memory, |
---|
123 | #: `cpu-load` = CPU load in percent. |
---|
124 | SYSTEM_MAX_LOAD = { |
---|
125 | 'swap-mem': None, |
---|
126 | 'virt-mem': None, |
---|
127 | 'cpu-load': 100.0, |
---|
128 | } |
---|
129 | |
---|
130 | EXPORTER_NAMES = ( |
---|
131 | 'pdfdocuments', |
---|
132 | 'htmldocuments', |
---|
133 | 'users', |
---|
134 | 'products', |
---|
135 | 'customers', |
---|
136 | 'customersampledocuments', |
---|
137 | 'samplecontracts') |
---|
138 | |
---|
139 | BATCH_PROCESSOR_NAMES = ( |
---|
140 | 'customerprocessor', |
---|
141 | 'customersampledocumentprocessor', |
---|
142 | 'samplecontractprocessor', |
---|
143 | 'productprocessor', |
---|
144 | 'pdfdocumentprocessor', |
---|
145 | 'htmldocumentprocessor', |
---|
146 | 'userprocessor') |
---|
147 | |
---|
148 | def sendContactForm(self, from_name, from_addr, rcpt_name, rcpt_addr, |
---|
149 | from_username, usertype, portal, body, subject): |
---|
150 | """Send an email with data provided by forms. |
---|
151 | """ |
---|
152 | config = grok.getSite()['configuration'] |
---|
153 | text = _(u"""Fullname: ${a} |
---|
154 | User Id: ${b} |
---|
155 | User Type: ${c} |
---|
156 | Portal: ${d} |
---|
157 | |
---|
158 | ${e} |
---|
159 | """) |
---|
160 | text = _(text, mapping={ |
---|
161 | 'a': from_name, |
---|
162 | 'b': from_username, |
---|
163 | 'c': usertype, |
---|
164 | 'd': portal, |
---|
165 | 'e': body}) |
---|
166 | body = translate(text, 'waeup.ikoba', |
---|
167 | target_language=self.PORTAL_LANGUAGE) |
---|
168 | if not (from_addr and rcpt_addr): |
---|
169 | return False |
---|
170 | return send_mail( |
---|
171 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
172 | subject, body, config) |
---|
173 | |
---|
174 | @property |
---|
175 | def tzinfo(self): |
---|
176 | # For Nigeria: pytz.timezone('Africa/Lagos') |
---|
177 | # For Germany: pytz.timezone('Europe/Berlin') |
---|
178 | return pytz.utc |
---|
179 | |
---|
180 | def fullname(self, firstname, lastname, middlename=None): |
---|
181 | """Full name constructor. |
---|
182 | """ |
---|
183 | # We do not necessarily have the middlename attribute |
---|
184 | if middlename: |
---|
185 | name = '%s %s %s' % (firstname, middlename, lastname) |
---|
186 | else: |
---|
187 | name = '%s %s' % (firstname, lastname) |
---|
188 | return string.capwords( |
---|
189 | name.replace('-', ' - ')).replace(' - ', '-') |
---|
190 | |
---|
191 | def genPassword(self, length=8, chars=string.letters + string.digits): |
---|
192 | """Generate a random password. |
---|
193 | """ |
---|
194 | return ''.join([r().choice(chars) for i in range(length)]) |
---|
195 | |
---|
196 | def sendCredentials(self, user, password=None, url_info=None, msg=None): |
---|
197 | """Send credentials as email. |
---|
198 | |
---|
199 | Input is the customer for which credentials are sent and the |
---|
200 | password. |
---|
201 | |
---|
202 | Returns True or False to indicate successful operation. |
---|
203 | """ |
---|
204 | subject = 'Your Ikoba credentials' |
---|
205 | text = _(u"""Dear ${a}, |
---|
206 | |
---|
207 | ${b} |
---|
208 | Registration and Application Portal of |
---|
209 | ${c}. |
---|
210 | |
---|
211 | Your user name: ${d} |
---|
212 | Your password: ${e} |
---|
213 | ${f} |
---|
214 | |
---|
215 | Please remember your user name and keep |
---|
216 | your password secret! |
---|
217 | |
---|
218 | Please also note that passwords are case-sensitive. |
---|
219 | |
---|
220 | Regards |
---|
221 | """) |
---|
222 | config = grok.getSite()['configuration'] |
---|
223 | from_name = config.name_admin |
---|
224 | from_addr = config.email_admin |
---|
225 | rcpt_name = user.title |
---|
226 | rcpt_addr = user.email |
---|
227 | text = _(text, mapping={ |
---|
228 | 'a': rcpt_name, |
---|
229 | 'b': msg, |
---|
230 | 'c': config.name, |
---|
231 | 'd': user.name, |
---|
232 | 'e': password, |
---|
233 | 'f': url_info}) |
---|
234 | |
---|
235 | body = translate(text, 'waeup.ikoba', |
---|
236 | target_language=self.PORTAL_LANGUAGE) |
---|
237 | return send_mail( |
---|
238 | from_name, from_addr, rcpt_name, rcpt_addr, |
---|
239 | subject, body, config) |
---|
240 | |
---|
241 | def getPaymentItem(self, payment): |
---|
242 | """Return payment item. |
---|
243 | |
---|
244 | This method can be used to customize the display_item property method. |
---|
245 | """ |
---|
246 | return payment.p_item |
---|
247 | |
---|
248 | def expensive_actions_allowed(self, type=None, request=None): |
---|
249 | """Tell, whether expensive actions are currently allowed. |
---|
250 | |
---|
251 | Check system load/health (or other external circumstances) and |
---|
252 | locally set values to see, whether expensive actions should be |
---|
253 | allowed (`True`) or better avoided (`False`). |
---|
254 | |
---|
255 | Use this to allow or forbid exports, report generations, or |
---|
256 | similar actions. |
---|
257 | """ |
---|
258 | max_values = self.SYSTEM_MAX_LOAD |
---|
259 | for (key, func) in ( |
---|
260 | ('swap-mem', psutil.swap_memory), |
---|
261 | ('virt-mem', psutil.virtual_memory), |
---|
262 | ): |
---|
263 | max_val = max_values.get(key, None) |
---|
264 | if max_val is None: |
---|
265 | continue |
---|
266 | mem_val = func() |
---|
267 | if isinstance(max_val, float): |
---|
268 | # percents |
---|
269 | if max_val < 0.0: |
---|
270 | max_val = 100.0 + max_val |
---|
271 | if mem_val.percent > max_val: |
---|
272 | return False |
---|
273 | else: |
---|
274 | # number of bytes |
---|
275 | if max_val < 0: |
---|
276 | max_val = mem_val.total + max_val |
---|
277 | if mem_val.used > max_val: |
---|
278 | return False |
---|
279 | return True |
---|